I'm connecting with c # to rest api server. and a json output comes as below.
WindowsForms, Model and Repository files are as follows.
1-) In other words, I want to transfer the json data incoming "result" object to the model file and show it on the gridview.
2-) Also, when I make a "Get" request, I want to request a "Body" object with a parameter.
example: {"business_code": "dental"}
CustomersModel.cs
namespace HastaTakip.Models
{
public class CustomersModel
{
public result _result { get; set; }
public class result
{
public int id { get; set; }
public string customer_name { get; set; }
public string customer_lastname { get; set; }
public string customer_identity { get; set; }
public string customer_gender { get; set; }
public string customer_phone { get; set; }
public string customer_description { get; set; }
public bool customer_status { get; set; }
public string doctor { get; set; }
public string customer_code { get; set; }
public string business_code { get; set; }
public int user_code_id { get; set; }
}
}
}
CustomersRepository.cs
using System.Net.Http;
using System;
using System.Threading.Tasks;
using HastaTakip.Models;
using Newtonsoft.Json;
namespace HastaTakip.Api
{
public class CustomersRepository
{
public HttpClient _client;
public HttpResponseMessage _response;
public CustomersRepository()
{
_client = new HttpClient();
_client.BaseAddress = new Uri("http://localhost:3000/");
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<CustomersModel> GetList()
{
_response = await _client.GetAsync($"customers");
var json = await _response.Content.ReadAsStringAsync();
var listCS = JsonConvert.DeserializeObject<CustomersModel>(json);
return listCS;
}
}
}
WindowsForms.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HastaTakip.Api;
using HastaTakip.Models;
namespace HastaTakip.Forms
{
public partial class frmCustomerList : Form
{
CustomersRepository _repository = new CustomersRepository();
public frmCustomerList()
{
InitializeComponent();
LoadData();
}
private async void LoadData()
{
var listCS = await _repository.GetList();
gridControl1.DataSource = listCS;
}
private void frmCustomerList_Load(object sender, EventArgs e)
{
}
}
}
Json results
{
"result": [
{
"id": 1,
"customer_name": "Test1",
"customer_lastname": null,
"customer_identity": "54sd45",
"customer_gender": "Man",
"customer_phone": null,
"customer_description": "kkjkjk.",
"customer_status": null,
"doctor": null,
"customer_code": "bcc50586-6960-4766-9468-c9dc55780e40",
"business_code": "dental",
"user_code_id": 1
},
{
"id": 2,
"customer_name": "Depron",
"customer_lastname": null,
"customer_identity": "564434",
"customer_gender": "WOMEN",
"customer_phone": null,
"customer_description": "record test.",
"customer_status": null,
"doctor": null,
"customer_code": "344865b4-1028-4051-9ec4-71db17414787",
"business_code": "dental",
"user_code_id": 1
}
]
}
From the json file you should get back a list or an array but in your model you only have one result the correct way would be:
public class CustomersModel
{
public List<result> _result { get; set; }
}
public class result
{
public int id { get; set; }
public string customer_name { get; set; }
public string customer_lastname { get; set; }
public string customer_identity { get; set; }
public string customer_gender { get; set; }
public string customer_phone { get; set; }
public string customer_description { get; set; }
public bool customer_status { get; set; }
public string doctor { get; set; }
public string customer_code { get; set; }
public string business_code { get; set; }
public int user_code_id { get; set; }
}
also i would never use nested classes unless there is a very good reason. and as long as it is not private i don't see a reason here anyway.
Related
I have a model like below:
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
PrimaryBuyerInputModel like below:
public class PrimaryBuyerInformationInputModel
{
[Required]
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
[Required]
public string BuyerLastName { get; set; }
}
and when I am submitting my form then I am getting JSON like below:
{
"PrimaryBuyerInformation.BuyerFirstName": "Sunil",
"PrimaryBuyerInformation.BuyerMiddleInitial": "",
"PrimaryBuyerInformation.BuyerLastName": "Choudhary",
"TermsCondition": "true"
}
When I am trying to deserialize this json the TermsCondition property successfully done, but the property of PrimaryBuyerInformation is not mapped.
var myObject = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Any idea how to do that ?
Kindly take a cue from the code below, i tested it and you should be able to get your value as request. This solves the issue of you trying to access the property you have mapped in a dot property name format.
Instead your object should be nested in a curly brace showing that the other property belongs to PrimaryBuyerInformationInputModel which is another object entirely.
Best Regards,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = #"{'PrimaryBuyerInformation': {'buyerFirstName': 'Sunil','buyerMiddleInitial': '','buyerLastName': 'Choudhary'},'termsCondition': false}";
var obj = JsonConvert.DeserializeObject<YourInformationInputModel>(json);
Console.WriteLine(obj.PrimaryBuyerInformation.BuyerFirstName);
}
}
public class YourInformationInputModel
{
public YourInformationInputModel()
{
PrimaryBuyerInformation = new PrimaryBuyerInformationInputModel();
}
public PrimaryBuyerInformationInputModel PrimaryBuyerInformation { get; set; }
public bool TermsCondition { get; set; }
}
public class PrimaryBuyerInformationInputModel
{
public string BuyerFirstName { get; set; }
public string BuyerMiddleInitial { get; set; }
public string BuyerLastName { get; set; }
}
JSON
{
"SoftHoldIDs": 444,
"AppliedUsages": [
{
"SoftHoldID": 444,
"UsageYearID": 223232,
"DaysApplied": 0,
"PointsApplied": 1
}
],
"Guests": [
1,
2
]
}
In the above JSON SoftholdIDs is integer and AppliedUsages is class array property in C# Model
Issue is --How we can map JSON to class property.
Class code
public class ReservationDraftRequestDto
{
public int SoftHoldIDs { get; set; }
public int[] Guests { get; set; }
public AppliedUsage[] AppliedUsages { get; set; }
}
public class AppliedUsage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
Tried below code for mapping
ReservationDraftRequestDto reservationDto = null;
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data.ToString());
You need to change
dynamic data = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
to
string data = await reservationDraftRequestDto.Content.ReadAsStringAsync();
this will read your response as string
then do
reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data);
this work
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string json = #"{""SoftHoldIDs"": 444,""AppliedUsages"": [ {""SoftHoldID"": 444,""UsageYearID"": 223232,""DaysApplied"": 0,""PointsApplied"": 1}],""Guests"": [ 1, 2]}";
Rootobject reservationDto = JsonConvert.DeserializeObject<Rootobject>(json.ToString());
Debug.WriteLine(reservationDto.SoftHoldIDs);
foreach (var guest in reservationDto.Guests)
{
Debug.WriteLine(guest);
}
}
}
public class Rootobject
{
public int SoftHoldIDs { get; set; }
public Appliedusage[] AppliedUsages { get; set; }
public int[] Guests { get; set; }
}
public class Appliedusage
{
public int SoftHoldID { get; set; }
public int UsageYearID { get; set; }
public int DaysApplied { get; set; }
public int PointsApplied { get; set; }
}
}
First create class copying json as classwith visualstudio.
Next you have double quote in json respons so deal with it.
Json.NET: Deserilization with Double Quotes
Below is my class for the json output:
class PwdResetRequest
{
public class TopScoringIntent
{
public string intent { get; set; }
public double score { get; set; }
}
public class Intent
{
public string intent { get; set; }
public double score { get; set; }
}
public class Resolution
{
public string value { get; set; }
}
public class Entity
{
public string entity { get; set; }
public string type { get; set; }
public int startIndex { get; set; }
public int endIndex { get; set; }
public Resolution resolution { get; set; }
}
public class RootObject
{
public string query { get; set; }
public TopScoringIntent topScoringIntent { get; set; }
public List<Intent> intents { get; set; }
public List<Entity> entities { get; set; }
}
}
Luis Return result:
{
"query": "create a new password for sjao9841#demo.com",
"topScoringIntent": {
"intent": "ResetLANIDpassword",
"score": 0.9956063
},
"intents": [
{
"intent": "ResetLANIDpassword",
"score": 0.9956063
},
{
"intent": "None",
"score": 0.179328963
}
],
"entities": [
{
"entity": "sjao9841#demo.com",
"type": "builtin.email",
"startIndex": 26,
"endIndex": 47
}
]
}
I have developed the below code for getting the data from the json.
var uri =
"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" +
luisAppId + "?" + queryString;
var response = await client.GetAsync(uri);
var strResponseContent = await response.Content.ReadAsStringAsync();
var json = await response.Content.ReadAsStringAsync();
var token = JObject.Parse(json).SelectToken("entities");
foreach (var item in token)
{
var request = item.ToObject<Entity>();
}
// Display the JSON result from LUIS
Console.WriteLine(strResponseContent.ToString());
}
And I only want the data from the "TopScoringIntent". How can I get that using C#? Below is the code that I tried but nothing came out:
Message=Error reading JObject from JsonReader. Path '', line 0, position 0.
Source=Newtonsoft.Json
I may be missing your intent, but if you only care about specific value rather than the entire javascript object, you could do the following.
dynamic json = JsonConvert.Deserialize(data);
var score = json.TopScoringIntent.Score;
That provides the specific value of score within TopScoringIntent. Obviously, you could also build a collection also well, by modifying slightly.
foreach(var point in json.Intents)
Console.WriteLine($"{point[1]} or {point.score}");
I believe that is what you're looking for, to receive a specific value from your object. Please note dynamics are useful, but this approach is a fairly quick and dirty, may not be ideal for your implementation.
quicktype generated the following C# classes and JSON.Net marshaling code for your sample data:
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var pwdResetRequest = PwdResetRequest.FromJson(jsonString);
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using J = Newtonsoft.Json.JsonPropertyAttribute;
public partial class PwdResetRequest
{
[J("query")] public string Query { get; set; }
[J("topScoringIntent")] public Ntent TopScoringIntent { get; set; }
[J("intents")] public Ntent[] Intents { get; set; }
[J("entities")] public Entity[] Entities { get; set; }
}
public partial class Entity
{
[J("entity")] public string EntityEntity { get; set; }
[J("type")] public string Type { get; set; }
[J("startIndex")] public long StartIndex { get; set; }
[J("endIndex")] public long EndIndex { get; set; }
}
public partial class Ntent
{
[J("intent")] public string Intent { get; set; }
[J("score")] public double Score { get; set; }
}
public partial class PwdResetRequest
{
public static PwdResetRequest FromJson(string json) => JsonConvert.DeserializeObject<PwdResetRequest>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this PwdResetRequest self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter()
{
DateTimeStyles = DateTimeStyles.AssumeUniversal,
},
},
};
}
}
Now you can use System.Linq to get the maximum Ntent by Score:
var uri = $"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/${luisAppId}?${queryString}";
var response = await client.GetAsync(uri);
var json = await response.Content.ReadAsStringAsync();
var request = PwdResetRequest.FromJson(json);
var maxIntent = request.Intents.MaxBy(intent => intent.Score);
Here's the generated code in a playground so you can change the type names and other options.
I have a json object and I am trying to convert it to my c# object. Here is my JSON:
{"GuvenlikNoktaArray": {"GuvenlikNoktası": [{"Id": 1,"GuvenlikNoktası1":"SANTIYE","KartNo":"000001889174217","Sira": 1},{"Id": 2,"GuvenlikNoktası1":"INSAAT","KartNo":"000000803567858","Sira": 2},{"Id": 3,"GuvenlikNoktası1":"ÇALISMA","KartNo":"000003417926233","Sira": 3},{"Id": 4,"GuvenlikNoktası1":"GÜVENLIK","KartNo":"000001888909897","Sira": 4}]}}
And my c# class:
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
And last, my convert try:
public void AddIstasyon(string json_string)
{
GuvenlikNoktası result = new JavaScriptSerializer().Deserialize<GuvenlikNoktası>(json_string);
}
I don't get any errors but when I debuged, I see that all attributes inside 'result' are null. It seems like an empty object. How can I get a correct 'GuvenlikNoktası' object ? (Btw I am pretty sure I am getting the json object correctly).
If you must keep this JSON structure as-is you may use JObject to navigate inside your JSON properties until you reach your target objects to deserizlize. Please can you try the code below;
PS: This code uses Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SO_39847703
{
class Program
{
static void Main(string[] args)
{
string json = "{\"GuvenlikNoktaArray\": {\"GuvenlikNoktası\": [{\"Id\": 1,\"GuvenlikNoktası1\":\"SANTIYE\",\"KartNo\":\"000001889174217\",\"Sira\": 1},{\"Id\": 2,\"GuvenlikNoktası1\":\"INSAAT\",\"KartNo\":\"000000803567858\",\"Sira\": 2},{\"Id\": 3,\"GuvenlikNoktası1\":\"ÇALISMA\",\"KartNo\":\"000003417926233\",\"Sira\": 3},{\"Id\": 4,\"GuvenlikNoktası1\":\"GÜVENLIK\",\"KartNo\":\"000001888909897\",\"Sira\": 4}]}}";
AddIstasyon(json);
}
public static void AddIstasyon(string json_string)
{
dynamic jsonObject = JObject.Parse(json_string);
string jsonToDeserializeStrongType = jsonObject["GuvenlikNoktaArray"]["GuvenlikNoktası"].ToString();
List<GuvenlikNoktası> result = JsonConvert.DeserializeObject<List<GuvenlikNoktası>>(jsonToDeserializeStrongType); ;
}
}
public partial class GuvenlikNoktası
{
public GuvenlikNoktası()
{
this.GüvenlikNoktasıOlay = new HashSet<GüvenlikNoktasıOlay>();
this.PanikButonuAlarmlari = new HashSet<PanikButonuAlarmlari>();
}
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public string Sira { get; set; }
public virtual ICollection<GüvenlikNoktasıOlay> GüvenlikNoktasıOlay { get; set; }
public virtual ICollection<PanikButonuAlarmlari> PanikButonuAlarmlari { get; set; }
}
public class GüvenlikNoktasıOlay
{
}
public class PanikButonuAlarmlari
{
}
}
Hope this helps
Your JSON data and your class definition do not fit together. Therefore the default values (NULL) are provided by the serializer.
In order to deserialize the given JSON data you need a class structure like:
public class Root
{
public LevelOne GuvenlikNoktaArray {get; set;}
}
public class LevelOne {
public IEnumerable<GuvenlikNoktası> GuvenlikNoktası {get; set;}
}
You can use this class.
public class GuvenlikNoktası
{
public int Id { get; set; }
public string GuvenlikNoktası1 { get; set; }
public string KartNo { get; set; }
public int Sira { get; set; }
}
public class GuvenlikNoktaArray
{
public IList<GuvenlikNoktası> GuvenlikNoktası { get; set; }
}
public class Example
{
public GuvenlikNoktaArray GuvenlikNoktaArray { get; set; }
}
You can use this link For your referencehttp://jsonutils.com/.
I am trying to read this xml File which is called "clubregisterquick.xml" and then trying to output it to a list so i can run multiple data on a test. I dont know where im going wrong my fields are showing u null debugging. Quite new to C#
<?xml version="1.0" encoding="utf-8"?>
<ClubRegisterQuick>
<Clubs>
<Club>
<Email>Gambardella#hotmail.com</Email>
<Clubname>Gambardella GAA</Clubname>
<Clubphonenumber>07348555550</Clubphonenumber>
<Firstname>David</Firstname>
<Lastname>Peoples</Lastname>
<Town>Maghera</Town>
<Country>N.Ireland</Country>
<Location>Down</Location>
<Currency>GBP</Currency>
<Password>password1</Password>
<Clubtype>GAA</Clubtype>
</Club>
<Club>
<Email>Matthew#hotmail.com</Email>
<Clubname>Computer GAA</Clubname>
<Clubphonenumber>06855583733</Clubphonenumber>
<Firstname>Paul</Firstname>
<Lastname>Smyth</Lastname>
<Town>Draperstown</Town>
<Country>Ireland</Country>
<Location>Wicklow</Location>
<Currency>EUR</Currency>
<Password>password1</Password>
<Clubtype>Rugby</Clubtype>
</Club>
</Clubs>
</ClubRegisterQuick>
Here is my Code that I am trying to implement it into. I have also yet to change the text for inputting the data as there is no points because i am getting null returned.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System.Collections;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
namespace ClassLibrary2
{
[XmlRoot(ElementName = "ClubRegisterQuick")]
public class Root
{
[XmlElement("Clubs")]
public Clubs clubs { get; set; }
}
public class Clubs
{
public List<Club> clubs { get; set; }
}
public class Club
{
[XmlElement("Email")]
public string Email { get; set; }
[XmlElement("Clubname")]
public string Clubname { get; set; }
[XmlElement("Clubphonenumber")]
public string Clubphonenumber { get; set; }
[XmlElement("Firstname")]
public string Firstname { get; set; }
[XmlElement("Lastname")]
public string Lastname { get; set; }
[XmlElement("Town")]
public string Town { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("PhonCurrencye")]
public string Currency { get; set; }
[XmlElement("Password")]
public string Password { get; set; }
[XmlElement("Clubtype")]
public string Clubtype { get; set; }
}
public static class serialize
{
public static T Deserialize<T>(string path)
{
T result;
using (var stream = File.Open(path, FileMode.Open))
{
result = Deserialize<T>(stream);
}
return result;
}
public static void Serialize<T>(T root, string path)
{
using (var stream = File.Open(path, FileMode.Create))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stream, root);
}
}
public static T Deserialize<T>(Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(stream);
}
[TestClass]
public class RegisterClubQuick
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[TestInitialize]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "******";
verificationErrors = new StringBuilder();
}
[TestCleanup]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[TestMethod]
public void TheRegisterClubQuickTest()
{
var a = serialize.Deserialize<Root>("clubregisterquick.xml");
driver.Navigate().GoToUrl(baseURL + "/Clubs");
Thread.Sleep(3000);
driver.FindElement(By.XPath("//a[contains(text(),'Register your Club')]")).Click();
Thread.Sleep(3000);
driver.FindElement(By.Name("email")).Clear();
driver.FindElement(By.Name("email")).SendKeys("notebook#mailinator1.com");
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//button[#type='submit'])[2]")).Click();
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//input[#name='clubName'])[2]")).Clear();
driver.FindElement(By.XPath("(//input[#name='clubName'])[2]")).SendKeys("NoteBook1 FC");
Thread.Sleep(3000);
new SelectElement(driver.FindElement(By.XPath("//div[#id='pagewrap']/div[3]/div[3]/div/div/div/form/div[2]/select"))).SelectByText("Hurling");
Thread.Sleep(3000);
driver.FindElement(By.Name("firstName")).Clear();
driver.FindElement(By.Name("firstName")).SendKeys("Paul");
Thread.Sleep(3000);
driver.FindElement(By.Name("lastName")).Clear();
driver.FindElement(By.Name("lastName")).SendKeys("McDonnell");
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//input[#name='clubPhoneNumber'])[2]")).Clear();
driver.FindElement(By.XPath("(//input[#name='clubPhoneNumber'])[2]")).SendKeys("07345656559");
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//input[#name='town'])[2]")).Clear();
driver.FindElement(By.XPath("(//input[#name='town'])[2]")).SendKeys("CarrickFergus");
Thread.Sleep(3000);
new SelectElement(driver.FindElement(By.XPath("//div[#id='pagewrap']/div[3]/div[3]/div/div/div/form/div[8]/select"))).SelectByText("N.Ireland");
Thread.Sleep(3000);
new SelectElement(driver.FindElement(By.XPath("//div[#id='pagewrap']/div[3]/div[3]/div/div/div/form/div[9]/select"))).SelectByText("Armagh");
Thread.Sleep(3000);
new SelectElement(driver.FindElement(By.XPath("//div[#id='pagewrap']/div[3]/div[3]/div/div/div/form/div[10]/select"))).SelectByText("GBP");
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//input[#name='password'])[2]")).Clear();
driver.FindElement(By.XPath("(//input[#name='password'])[2]")).SendKeys("password1");
Thread.Sleep(3000);
driver.FindElement(By.Name("confirmPassword")).Clear();
driver.FindElement(By.Name("confirmPassword")).SendKeys("password1");
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//input[#type='checkbox'])[2]")).Click();
Thread.Sleep(3000);
driver.FindElement(By.XPath("(//button[#type='submit'])[4]")).Click();
Thread.Sleep(5000);
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
}
Your 'Clubs' class does not match the XML structure. Also I believe you need to mark your Club class as Serializable. The XmlElement attributes ([XmlElement("Password")] etc) are then redundant if the name matches the element.
I was able to get your example working using the following structure:
[XmlRoot(ElementName="ClubRegisterQuick")]
public class Root
{
public List<Club> Clubs { get; set; }
}
[Serializable]
public class Club
{
public string Email { get; set; }
public string Clubname { get; set; }
public string Clubphonenumber { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Town { get; set; }
public string Country { get; set; }
public string Location { get; set; }
public string Currency { get; set; }
public string Password { get; set; }
public string Clubtype { get; set; }
}
The code below works. Only thing I found wrong was in the class Club you need [XmlElement("Club")] because it is a list. Without the XmlElement an extra set of tags are created which makes it incompatible wit your XML.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Stream stream = File.Open(FILENAME, FileMode.Open);
ClassLibrary2.Root root = ClassLibrary2.serialize.Deserialize<ClassLibrary2.Root>(stream);
stream.Close();
ClassLibrary2.serialize.Serialize(root, FILENAME);
}
}
}
namespace ClassLibrary2
{
[XmlRoot(ElementName = "ClubRegisterQuick")]
public class Root
{
[XmlElement("Clubs")]
public Clubs clubs { get; set; }
}
public class Clubs
{
[XmlElement("Club")]
public List<Club> clubs { get; set; }
}
public class Club
{
[XmlElement("Email")]
public string Email { get; set; }
[XmlElement("Clubname")]
public string Clubname { get; set; }
[XmlElement("Clubphonenumber")]
public string Clubphonenumber { get; set; }
[XmlElement("Firstname")]
public string Firstname { get; set; }
[XmlElement("Lastname")]
public string Lastname { get; set; }
[XmlElement("Town")]
public string Town { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("Currency")]
public string Currency { get; set; }
[XmlElement("Password")]
public string Password { get; set; }
[XmlElement("Clubtype")]
public string Clubtype { get; set; }
}
public static class serialize
{
public static T Deserialize<T>(string path)
{
T result;
using (var stream = File.Open(path, FileMode.Open))
{
result = Deserialize<T>(stream);
}
return result;
}
public static void Serialize<T>(T root, string path)
{
using (var stream = File.Open(path, FileMode.Create))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stream, root);
stream.Flush();
stream.Close();
}
}
public static T Deserialize<T>(Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(stream);
}
}
}