add value to classes and subclasses with c# - c#

I have the following code of my class,
public class ClassGPS
{
[XmlElement("head")]
public Head head;
[XmlElement("events")]
public Events events;
public class Head
{
[XmlAttribute("nemo")]
public string Nemo { get; set; }
[XmlAttribute("dte")]
public string Dte { get; set; }
}
public class Events
{
[XmlElement("event")]
public _EVENT events;
}
public class _EVENT
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlAttribute("desc")]
public string Desc { get; set; }
[XmlElement("gps")]
public _GPS gps;
[XmlElement("mov")]
public _MOV mov;
[XmlElement("geo")]
public _GEO geo;
[XmlElement("passengers")]
public _PASSENGERS passengers;
[XmlElement("sensors")]
public _SENSORS sensors;
}
public class _GPS
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("dte")]
public string Dte { get; set; }
}
public class _MOV
{
[XmlAttribute("plate")]
public string Plate { get; set; }
[XmlAttribute("vel")]
public string Vel { get; set; }
[XmlAttribute("odo")]
public string Odo { get; set; }
[XmlAttribute("rpm")]
public string Rpm { get; set; }
[XmlAttribute("rutDri")]
public string Rutdri { get; set; }
[XmlAttribute("tipDri")]
public string Tipdri { get; set; }
}
public class _GEO
{
[XmlAttribute("lat")]
public string Lat { get; set; }
[XmlAttribute("long")]
public string Long { get; set; }
[XmlAttribute("alt")]
public string Alt { get; set; }
[XmlAttribute("dir")]
public string Dir { get; set; }
}
public class _PASSENGERS
{
[XmlElement("pass")]
public _PASS pass;
}
public class _PASS
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("rut")]
public string Rut { get; set; }
[XmlAttribute("tip")]
public string Tip { get; set; }
}
public class _SENSORS
{
[XmlElement("sensor")]
public _SENSOR sensor;
}
public class _SENSOR
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("unit")]
public string Unit { get; set; }
[XmlAttribute("value")]
public string Value { get; set; }
}
}
and use the code below to fill
public ClassGPS esb()
{
List<ClassGPS._EVENT> listevent = new List<ClassGPS._EVENT>();
List<ClassGPS._PASSENGERS> listpassegers = new List<ClassGPS._PASSENGERS>();
List<ClassGPS._SENSORS> listsensors = new List<ClassGPS._SENSORS>();
ClassGPS gps = new ClassGPS
{
head = new ClassGPS.Head { Nemo = "XYS-XML", Dte = "2012-02-02 15:05:05.456" },
events = new ClassGPS.Events
{
for (int i = 1; i <= 5 ; i++) {
listevent.Add (new ClassGPS._EVENT
{
Type = "PPT",
Desc = "position_time",
gps = new ClassGPS._GPS { Id = i, Dte = "2012-02-02 15:05:05.456" },
mov = new ClassGPS._MOV { Plate = "111456-2", Vel = "98", Odo = "45678987", Rpm = "465489", Rutdri = "13649654", Tipdri = "23133216" },
geo = new ClassGPS._GEO { Lat = "-34.324", Long = "70.366", Alt = "32.506", Dir = "86.32123" },
passengers = new ClassGPS._PASSENGERS
{
for (int x = 1; x <= 9 ; x++) {
listpassegers.Add ( new ClassGPS._PASS {
Id = x,
Rut = "2132132",
Tip = "121325646" })
}
},
sensors = new ClassGPS._SENSORS
{
for (int y = 1; x <= 3 ; x++) {
listsensors.Add ( new ClassGPS._SENSOR {
Type ="LS",
Id = y,
Unit= "%" ,
Value="21" })
}
}
})
}
}
};
return gps;
}
I cannot fill with the code because I don't know how.
I need the following result.
<ClassGPS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<head nemo="XYS-XML" dte="2012-02-02 15:05:05.456" />
<events>
<event type="PPT" desc="position_time">
<gps id="213212315646" dte="2012-02-02 15:05:05.456" />
<mov plate="111456-2" vel="98" odo="45678987" rpm="465489" rutDri="13649654" tipDri="23133216" />
<geo lat="-34.324" long="70.366" alt="32.506" dir="86.32123" />
<passengers>
<pass id="1" rut="2132132" tip="121325646" />
</passengers>
<sensors>
<sensor type="LS" id="1" unit="%" value="21" />
<sensor type="LS" id="1" unit="%" value="21" />
</sensors>
</event>
<event type="PPT" desc="position_time">
<gps id="213212315646" dte="2012-02-02 15:05:05.456" />
<mov plate="111456-2" vel="98" odo="45678987" rpm="465489" rutDri="13649654" tipDri="23133216" />
<geo lat="-34.324" long="70.366" alt="32.506" dir="86.32123" />
<passengers>
<pass id="1" rut="2132132" tip="121325646" />
<pass id="2" rut="2132546132" tip="1213256546" />
</passengers>
<sensors>
<sensor type="LS" id="1" unit="%" value="21" />
</sensors>
</event>
</events>
The passengers, sensors and events can be more than one.

I've modified and shortened your code slightly.
public class Gps
{
[XmlElement("head")]
public HeadData Head { get; set; }
[XmlArray("events")]
[XmlArrayItem("event")]
public List<EventData> Events { get; set; }
public class HeadData
{
[XmlAttribute("nemo")]
public string Nemo { get; set; }
[XmlAttribute("dte")]
public DateTime Dte { get; set; }
}
public class EventData
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlAttribute("desc")]
public string Desc { get; set; }
[XmlElement("gps")]
public GpsData Gps { get; set; }
}
public class GpsData
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("dte")]
public DateTime Dte { get; set; }
}
}
Populate data and serialize
private static void Main(string[] args)
{
var eventData = new List<Gps.EventData>();
for (int i = 0; i < 5; ++i)
{
eventData.Add(new Gps.EventData
{
Desc = "X",
Type = "Y",
Gps = new Gps.GpsData
{
Dte = DateTime.Now,
Id = i.ToString()
}
});
}
Gps gps = new Gps()
{
Head = new Gps.HeadData {Dte = DateTime.Now, Nemo = "XYS-XML"},
Events = eventData
};
var serializer = new XmlSerializer(gps.GetType());
using (var writer = new StreamWriter(#"C:\temp\gps.xml"))
{
serializer.Serialize(writer, gps);
}
Console.ReadLine();
}
XML result
<?xml version="1.0" encoding="utf-8"?>
<Gps xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<head nemo="XYS-XML" dte="2015-04-27T18:48:47.9499022+02:00" />
<events>
<event type="Y" desc="X">
<gps id="0" dte="2015-04-27T18:48:47.9489022+02:00" />
</event>
<event type="Y" desc="X">
<gps id="1" dte="2015-04-27T18:48:47.9499022+02:00" />
</event>
<event type="Y" desc="X">
<gps id="2" dte="2015-04-27T18:48:47.9499022+02:00" />
</event>
<event type="Y" desc="X">
<gps id="3" dte="2015-04-27T18:48:47.9499022+02:00" />
</event>
<event type="Y" desc="X">
<gps id="4" dte="2015-04-27T18:48:47.9499022+02:00" />
</event>
</events>
</Gps>

Related

XML response format is not as my expectation

I am trying to send response as per below to the user. I am facing issue for node ITEM in which ( Type, For, Amount, Description & Rate ) present in the node as per below. But when i am trying to generate the output it is not generation output as per below for this node.
EXPECTED OUTPUT
<ANF>
<QUOTEID>951C3532</QUOTEID>
<CHARGE>161.98</CHARGE>
<ITEMIZEDCHARGES>
<ITEM TYPE="CHARGE" FOR="FREIGHT" AMOUNT="914.41" DESCRIPTION="65 LB CL125, 1 PLT # 94 x 48 x 12 IN" />
<ITEM TYPE="DISCOUNT" FOR="SHIPPER" AMOUNT="-832.11" DESCRIPTION="SHIPPER DISCOUNT" RATE="91%" />
<ITEM TYPE="CHARGE" FOR="MCADJ" AMOUNT="137.70" DESCRIPTION="ABSOLUTE MIN CHARGE ADJUSTMENT" />
</ITEMIZEDCHARGES>
<NOTES>
</NOTES>
<NUMERRORS>0</NUMERRORS>
</ANF>
I have generated the object for this xml response as per below
namespace ResponseXML
{
[XmlRoot(ElementName="ITEM")]
public class ITEM {
[XmlAttribute(AttributeName="TYPE")]
public string TYPE { get; set; }
[XmlAttribute(AttributeName="FOR")]
public string FOR { get; set; }
[XmlAttribute(AttributeName="AMOUNT")]
public string AMOUNT { get; set; }
[XmlAttribute(AttributeName="DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlAttribute(AttributeName="RATE")]
public string RATE { get; set; }
}
[XmlRoot(ElementName="ITEMIZEDCHARGES")]
public class ITEMIZEDCHARGES {
[XmlElement(ElementName="ITEM")]
public List<ITEM> ITEM { get; set; }
}
[XmlRoot(ElementName="ANF")]
public class ANF {
[XmlElement(ElementName="QUOTEID")]
public string QUOTEID { get; set; }
[XmlElement(ElementName="CHARGE")]
public string CHARGE { get; set; }
[XmlElement(ElementName="ITEMIZEDCHARGES")]
public ITEMIZEDCHARGES ITEMIZEDCHARGES { get; set; }
[XmlElement(ElementName="NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName="NUMERRORS")]
public string NUMERRORS { get; set; }
}
}
My code output ITEMIZEDCHARGES
<ITEMIZEDCHARGES>
<ITEM>
<ITEM>
<AMOUNT>45.09</AMOUNT>
<DESCRIPTION></DESCRIPTION>
<FOR i:nil="true" />
<RATE></RATE>
<TYPE></TYPE>
</ITEM>
</ITEM>
</ITEMIZEDCHARGES>
My Code for adding values is as below in object
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = Convert.ToString(zipDetails.Rate);
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEM = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
Can you please advice what i am doing mistake.
Code for response from code
[System.Web.Http.HttpPost]
[System.Web.Http.Route("GetQuote")]
[ResponseType(typeof(IEnumerable<ABF>))]
public HttpResponseMessage GetOrderPriceQuotetest(HttpRequestMessage request)
{
var abf = request.Content.ReadAsStringAsync().Result;
try
{
if (abf != null)
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderPriceRequest.ABF));
using (StringReader reader = new StringReader(abf))
{
OrderPriceRequest.ABF testReq = (OrderPriceRequest.ABF)serializer.Deserialize(reader);
if (testReq != null)
{
ANF fn = new ANF();
fn.CHARGE = 0;
fn.QUOTEID = "";
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = "10";
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEMS = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
else
{
ANF fn = new ANF();
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, abf);
}
}
catch (Exception ex)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
}

How to force to show every class tag during XML serialisation in C#

I have the following console program
using System.Xml;
using System.Xml.Serialization;
namespace myTry {
public class CI_ResponsibleParty{
public CI_ResponsibleParty() { }
[XmlElement(Order = 0, ElementName = "individualName")]
public string IndividualName { get; set; }
[XmlElement(Order = 1, ElementName = "contactInfo")]
public CI_Contact ContactInfo { get; set; }
}
public class CI_Contact{
public CI_Contact() {}
[XmlElement(Order = 1, ElementName = "address")]
public CI_Address Address { get; set; }
}
public class CI_Address{
public CI_Address() {}
[XmlArray(ElementName = "deliveryPoint", Order = 0)]
[XmlArrayItem(typeof(string), ElementName = "CharacterString", Type = typeof(string))]
public List<string> DeliveryPoint { get; set; }
[XmlElement(Order = 1, ElementName = "city")]
public string City { get; set; }
[XmlAttribute(DataType = "ID", AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "uuid")]
public string Uuid { get; set; }
}
}
namespace Application {
class Program {
public static void ReadXML() {
var b = new myTry.CI_ResponsibleParty() {
IndividualName = "dummy ind name",
ContactInfo = new myTry.CI_Contact {
Address = new myTry.CI_Address {
Id = "123",
Uuid = "123",
City = "dummuy city",
}
}
};
var writer = new System.Xml.Serialization.XmlSerializer(typeof(myTry.CI_ResponsibleParty));
var wfile = new System.IO.StreamWriter(#"CI_ResponsibleParty_write.xml");
writer.Serialize(wfile, b);
wfile.Close();
return;
}
static void Main(string[] args) {
ReadXML();
}
}
}
it produces
<?xml version="1.0" encoding="utf-8"?>
<CI_ResponsibleParty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<individualName>dummy ind name</individualName>
<contactInfo>
<address id="123" uuid="123">
<city>dummuy city</city>
</address>
</contactInfo>
</CI_ResponsibleParty>
but I want to have CI_Contact and CI_Address tags as inner tags of contaxtInfo and address tags respectively. i.e.
<?xml version="1.0" encoding="utf-8"?>
<CI_ResponsibleParty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<individualName>dummy ind name</individualName>
<contactInfo>
<CI_Contact>
<address id="123" uuid="123">
<CI_Address>
<city>dummuy city</city>
</CI_Address>
</address>
</CI_Contact>
</contactInfo>
</CI_ResponsibleParty>
How may I do so? What did I do wrong?

How to make list from XML deserialization

I have an XML file with many devices and many slots. I need to make lists of both. I am trying with the device type but it is always null.
<?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
<System Name="Local">
<SysInfo>
<Software>
<VersionCreated>X3 SP5 (RELEASE-181228) (64-bit)</VersionCreated>
<VersionModifed>X3 SP5 (RELEASE-181228) (64-bit)</VersionModifed>
<License_Type>Professional</License_Type>
</Software>
</SysInfo>
<DewesoftSetup>
<Devices>
<StartStoreTime>43874.6969328704</StartStoreTime>
<SampleRate>50000</SampleRate>
<BlockSize>1000</BlockSize>
<IBRate>10</IBRate>
<AAFsr>21000</AAFsr>
<MaxSampling>200000</MaxSampling>
<Device Type="AI">
<Slot Index="0">
<MeasuredValue>VOLTAGE</MeasuredValue>
<Range>10 V</Range>
<LPFilter_Type>BU</LPFilter_Type>
<LPFilter_Hz>10000</LPFilter_Hz>
<LPFilter_Order>2</LPFilter_Order>
<HPFilter_Hz>1</HPFilter_Hz>
<OutMathChEnabled>8;1;0;0;0;0;0;0;0</OutMathChEnabled>
</Slot>
</Device>
<Device Type="DI">
....
</Device>
</Devices>
</DewesoftSetup>
</System>
</DataFileSetup>
public static void readXML()
{
string deviceType;
XmlReader reader = XmlReader.Create(DewesoftCard.xmlFileName);
reader.ReadToFollowing("DeviceName");
reader.Read();
deviceType = reader.Value;
reader.ReadToFollowing("DewesoftSetup");
if (deviceType == "SIRIUSi")
{
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftSiriusDevices));
DewesoftSiriusDevices setupSirius = (DewesoftSiriusDevices)serializer.Deserialize(reader);
}
else if (deviceType == "KRYPTONi TH")
{
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftKryptonDevices));
DewesoftKryptonDevices setupKrypton = (DewesoftKryptonDevices)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftSiriusDevices
{
[XmlElement(ElementName ="Devices")]
public DewesoftSiriusSetup dewesoftSiriusSetup { get; set; }
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
};
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftKryptonDevices
{
[XmlElement(ElementName = "Devices")]
public DewesoftKryptonSetup dewesoftKryptonSetup { get; set; }
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
};
public class DewesoftSiriusSetup
{
public double StartStoreTime;
public int SampleRate;
public int IBRate;
public int AAFsr;
public int MaxSampling;
};
public class DewesoftKryptonSetup
{
public double StartStoreTime;
public int SampleRate;
public int BlockSize;
public int IBRate;
public int MaxSampling;
};
public class DeviceType
{
[XmlAttribute(AttributeName = "Type")]
public string type;
};
The dewesoftSiriusSetup or dewesoftKryptonSetup is populated correctly.
Is there something I am missing from the code? Along with the device type, inside of there I also need the different slots as a list but I havent gotten that far since I feel like if I get the device figured out it will be the same for slots

Deserialize XML into object structure including dictionary

I'm trying to deserialize a given XML File into an object structure.
This is the XML:
<StaticData>
<Configuration>
<SqlCmdParameters />
<Tables>
<Table Schema="dbo" Name="table1">
<Columns>
<Column Name="tab1col1" IsPrimaryKey="false" />
<Column Name="tab1col2" IsPrimaryKey="false" />
</Columns>
</Table>
<Table Schema="dbo" Name="table2">
<Columns>
<Column Name="tab2col1" IsPrimaryKey="false" />
<Column Name="tab2col2" IsPrimaryKey="false" />
</Columns>
</Table>
</Tables>
</Configuration>
<TableDataItems>
<TableData Schema="dbo" Name="table1">
<RowData tab1col1="11" tab1col2="text1" tab1col3="anotherText1" />
<RowData tab1col1="12" tab1col2="text2" tab1col3="anotherText2"/>
<RowData tab1col1="13" tab1col2="text3" tab1col3="anotherText3"/>
</TableData>
<TableData Schema="dbo" Name="table2">
<RowData tab2col1="22" tab2col2="text1" />
<RowData tab2col1="23" tab2col2="text1" />
<RowData tab2col1="24" tab2col2="text1" />
</TableData>
</TableDataItems>
</StaticData>
The classes I want to fill them in are:
[XmlRoot("StaticData")]
public class StaticData
{
[XmlElement("Configuration")]
public Configuration Configuration { get; set; }
[XmlElement("TableDataItems")]
public TableDataItems TableDataItems { get; set; }
}
public class Configuration
{
[XmlElement("Tables")]
public List<Table> Tables { get; set; }
[XmlElement("SqlCmdParameters")]
public List<SqlCommandParameter> SqlCommandParameters { get; set; }
}
public class TableDataItems
{
[XmlElement("TableData")]
public List<Table> TableDatas { get; set; }
}
public class Table
{
[XmlAttribute("Name")]
public string TableName { get; set; }
[XmlAttribute("Schema")]
public string SchemaName { get; set; }
[XmlElement("Columns")]
public List<Column> Columns { get; set; }
[XmlElement("RowData")]
public List<Row> Rows { get; set; }
public Table()
{
Columns = new List<Column>();
Rows = new List<Row>();
}
}
public class Column
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("IsPrimaryKey")]
public bool IsPrimaryKey { get; set; }
}
public class Row
{
public Row()
{
RowData = new Dictionary<string, string>();
}
???What Attribute should I put here???
public Dictionary<string, string> RowData { get; set; }
}
So, everything works fine until I get to the where all the Attributes should be filled into a dictionary.
This is how I deserialize the XML so far:
public void CreateObjectStructureFromXml()
{
using (TextReader textReader = new StringReader(XmlDocument.ToString()))
{
XmlSerializer serializer = new XmlSerializer(typeof(StaticData));
StaticData = (StaticData) serializer.Deserialize(textReader);
}
}
I get an exception as soon as I get to the Row elements.
Can anybody please point me to where I made the mistake or what I should do?
The XML RowData can come with a variable amount of attributes. The attributes are the content of a database table.
Thanks a lot in advance
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Table.tables = doc.Descendants("Table").Select(x => new Table() {
SchemaName = (string)x.Attribute("Schema"),
TableName = (string)x.Attribute("Name"),
Columns = x.Descendants("Column").Select(y => new Column()
{
Name = (string)y.Attribute("Name"),
IsPrimaryKey = (Boolean)y.Attribute("IsPrimaryKey")
}).ToList()
}).ToList();
Dictionary<string, XElement> tableData = doc.Descendants("TableData")
.GroupBy(x => (string)x.Attribute("Name"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
foreach(Table table in Table.tables)
{
XElement xTable = tableData[table.TableName];
table.SchemaName = (string)xTable.Attribute("Schema");
table.Rows = xTable.Elements("RowData").Select(x => new Row() {
RowData = x.Attributes()
.GroupBy(y => y.Name.LocalName, z => (string)z)
.ToDictionary(y => y.Key, z => z.FirstOrDefault())
}).ToList();
}
}
}
public class Table
{
public static List<Table> tables = new List<Table>();
public string TableName { get; set; }
public string SchemaName { get; set; }
public List<Column> Columns { get; set; }
public List<Row> Rows { get; set; }
public Table()
{
Columns = new List<Column>();
Rows = new List<Row>();
}
}
public class Column
{
public string Name { get; set; }
public bool IsPrimaryKey { get; set; }
}
public class Row
{
public Dictionary<string, string> RowData { get; set; }
}
}

Deserialization works but XMLArray is missing c# XMLSerialize

The XML is generated and loaded by the same .NET with c# desktop application using XMLSerialize serialization / deserialization.
The serializable class structur is quiet complex, so I just made a selection of the two relevant classes.
Now, when I deserialize, everything is loaded except the Mapping Messages (or Messages as how the object list is called in the Organization.
Does anyone have an explanation for this behaviour?
Any tips or hints for improving what has already been made are also always appreciated.
Thank you.
I have the following XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsd="Company.Test3.Crm.Crm2Queue.Config.xsd">
<organizations>
<organization name="Vanilla">
<settings>
<ignoreemptyfields>true</ignoreemptyfields>
<throwerroronmissingconfiguration>true</throwerroronmissingconfiguration>
</settings>
<endpoints>
<endpoint>
<serviceUri>http://www.webservicex.net/usaddressverification.asmx</serviceUri>
</endpoint>
</endpoints>
<messages>
<message name="account">
<field name="accountnumber" mappedname="State" />
<field name="address1_county" mappedname="Zip" />
<field name="address1_latitude" mappedname="City" />
</message>
</messages>
<entities>
<entity name="account" messageschema="/XSD/.xsd" identifier="accountid">
<events>
<event name="create" message="" />
<event name="update" message="" />
<event name="delete" message="" />
</events>
</entity>
</entities>
</organization>
</organizations>
</configuration>
Now the serializable class looks as following:
[Serializable()]
public class Organization
{
#region XmlIgnore
[XmlIgnore()]
public string Id { get; set; }
[XmlIgnore()]
public bool Checked { get; set; }
[XmlIgnore()]
public List<MappingMessage> mappingMessages { get; set; }
#endregion
#region Attributes
[XmlAttribute("name")]
public string Name { get; set; }
#endregion
#region Properties
[XmlElement("settings")]
public Settings Settings { get; set; }
public bool ShouldSerializeSettings() { return (Settings != null && (Settings.IgnoreEmptyFields.HasValue || Settings.ThrowErrorOnMissingConfiguration.HasValue)); }
[XmlArray("endpoints")]
[XmlArrayItem("endpoint")]
public List<Endpoint> Endpoints { get; set; }
public bool ShouldSerializeignoreEndpoints() { return (Endpoints.Count > 0); }
[XmlArray("messages")]
[XmlArrayItem("message")]
public List<MappingMessage> Messages
{
get { return mappingMessages.Where(mm => (mm.Fields.Where(fi => !string.IsNullOrEmpty(fi.MappedName)).ToList().Count > 0)).ToList(); }
set { mappingMessages = value; }
}
public bool ShouldSerializeFilledMappingMessages() { return (mappingMessages.Where(mm => (mm.Fields.Where(fi => !string.IsNullOrEmpty(fi.MappedName)).ToList().Count > 0)).ToList().Count > 0); }
//public bool ShouldSerializeMappingMessages() { return (MappingMessages.Where(mm=> (mm.Fields.Where(fi=> !string.IsNullOrEmpty(fi.MappedName)).ToList().Count > 0)).ToList().Count > 0); }
[XmlArray("entities")]
[XmlArrayItem("entity")]
public List<Entity> Entities { get; set; }
public bool ShouldSerializeEntities() { return (Entities.Count > 0); }
#endregion
#region Constructors
public Organization()
{
Settings = new Settings();
Endpoints = new List<Endpoint>();
mappingMessages = new List<MappingMessage>();
Entities = new List<Entity>();
Checked = false;
}
public Organization(string name)
: this()
{
Name = name;
}
public Organization(string id, string name)
: this(name)
{
Id = id;
}
#endregion
}
[Serializable()]
public class MappingMessage
{
#region XmlIgnore
[XmlIgnore()]
public string EntityId { get; set; }
[XmlIgnore()]
public bool Checked { get; set; }
[XmlIgnore()]
public List<Field> Fields { get; set; }
#endregion
#region Attributes
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
#endregion
#region Properties
[XmlElement("field")]
public List<Field> SelectedFields
{
get
{
return Fields.Where(fi=> !string.IsNullOrEmpty(fi.MappedName)).ToList();
}
set
{
Fields = value;
}
}
public bool ShouldSerializeSelectedFields() { return (SelectedFields.Count > 0); }
[XmlElement("subentity")]
public List<SubEntity> SubEntities { get; set; }
public bool ShouldSerializeSubEntities() { return (SubEntities.Count > 0); }
[XmlElement("parententity")]
public List<ParentEntity> ParentEntities { get; set; }
public bool ShouldSerializeParentEntities() { return (ParentEntities.Count > 0); }
#endregion
#region Constructors
public MappingMessage()
{
Checked = false;
Fields = new List<Field>();
SubEntities = new List<SubEntity>();
ParentEntities = new List<ParentEntity>();
}
public MappingMessage(string entityId)
: this()
{
EntityId = entityId;
}
public MappingMessage(string entityId, string name)
: this(entityId)
{
Name = name;
}
#endregion
}
And I use deserialization as shown below:
foreach (ZipEntry zipEntry in zipFile)
{
using (MemoryStream memoryStream = new MemoryStream())
{
if (zipEntry.FileName.ToLower().EndsWith(".crm.crm2queue.config.xml"))
{
using (StreamReader streamReader = new StreamReader(memoryStream, Encoding.UTF8))
{
zipEntry.Extract(memoryStream);
memoryStream.Position = 0;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Ciber.Crm.MappingCRMTo.Data.Configuration));
configuration = (Configuration)xmlSerializer.Deserialize(streamReader);
}
}
}
}
The deserializer tries to fill the list returnepublic List<MappingMessage> Messages. In order to the serializer invoke the setter, you must change the property type to an immutable collection type, say MappingMessage[].
Edit : to see that, you can replace the Entities auto-property by a property with backing field, and set a breakpoint in both getter and setter. You should not break in the setter, only in the getter.

Categories

Resources