Search Results

Search found 48 results on 2 pages for 'xmlattribute'.

Page 1/2 | 1 2  | Next Page >

  • How to get this XmlAttribute

    - by user328738
    From the MusicBrainz REST service, I get the following xml: <artist-list offset="0" count="59"> <artist type="Person" id="xxxxx" ext:score="100"> ... Using WCF and XmlSerializationFormat, I'm able to get the type and id attributes... but How do I get the "ext:score" one? This works: public class Artist { [XmlAttribute("id")] public string ID { get; set; } [XmlAttribute("type")] public ArtistType Type { get; set; } But this doesnt: [XmlAttribute("ext:score")] public string Score { get; set; } It produces a serialization exception. I've also tried just using "score", but it doesn't work. Any help?

    Read the article

  • XmlAttribute/XmlText cannot be used to encode complex type

    - by Conrad C
    I want to serialize a class Ticket into xml. I get the error :"XmlAttribute/XmlText cannot be used to encode complex type" because of my customfield class. This is how the xml for customfields should look like ( the attribute array is nesseray but I don't understand how to create it): <custom_fields type="array"> <custom_field name="Standby Reason" id="6"> <value/> </custom_field> <custom_field name="Close Date" id="84"> Class Ticket public class Ticket { [XmlElement("custom_fields")] public CustomFields Custom_fields { get; set; } Class CustomFields [Serializable] public class CustomFields { [XmlAttribute("array")] public List<CustomField> custom_field { get; set; } Class CustomField [Serializable] public class CustomField { [XmlIgnore] public string Name { get; set; } [XmlElement] public int Id { get; set; } [XmlElement] public string Value { get; set; }

    Read the article

  • Getting an invalidoperationexception when deserialising XML

    - by Paul Johnson
    Hi, I'm writing a simple proof of concept application to load up an XML file and depending on the very simple code, create a window and put something into it (it's for a much larger project). Due to limitations in Mono, I'm having to run in this way. The code I currently have looks like this using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Collections; using System.Xml; using System.Xml.Serialization; namespace form_from_xml { public class xmlhandler : Form { public void loaddesign() { FormData f; f = null; try { string path_env = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar; // code dies on the line below XmlSerializer s = new XmlSerializer(typeof(FormData)); TextReader r = new StreamReader(path_env + "designer-test.xml"); f = (FormData)s.Deserialize(r); r.Close(); } catch (System.IO.FileNotFoundException) { MessageBox.Show("Unable to find the form file", "File not found", MessageBoxButtons.OK); } } } [XmlRoot("Forms")] public class FormData { private ArrayList formData; public FormData() { formData = new ArrayList(); } [XmlElement("Element")] public Elements[] elements { get { Elements[] elements = new Elements[formData.Count]; formData.CopyTo(elements); return elements; } set { if (value == null) return; Elements[] elements = (Elements[])value; formData.Clear(); foreach (Elements element in elements) formData.Add(element); } } public int AddItem(Elements element) { return formData.Add(element); } } public class Elements { [XmlAttribute("formname")] public string name; [XmlAttribute("winxsize")] public int winxs; [XmlAttribute("winysize")] public int winys; [XmlAttribute("type")] public object type; [XmlAttribute("xpos")] public int xpos; [XmlAttribute("ypos")] public int ypos; [XmlAttribute("externaldata")] public bool external; [XmlAttribute("externalplace")] public string externalplace; [XmlAttribute("text")] public string text; [XmlAttribute("questions")] public bool questions; [XmlAttribute("questiontype")] public object qtype; [XmlAttribute("numberqs")] public int numberqs; [XmlAttribute("answerfile")] public string ansfile; [XmlAttribute("backlink")] public int backlink; [XmlAttribute("forwardlink")] public int forwardlink; public Elements() { } public Elements(string fn, int wx, int wy, object t, int x, int y, bool ext, string extpl, string te, bool q, object qt, int num, string ans, int back, int end) { name = fn; winxs = wx; winys = wy; type = t; xpos = x; ypos = y; external = ext; externalplace = extpl; text = te; questions = q; qtype = qt; numberqs = num; ansfile = ans; backlink = back; forwardlink = end; } } } With a very simple xmlhandler xml = new xmlhander(); xml.loaddesign(); attached to a winform button. Everything is in the same namespace and the xml file actually exists. This is annoying me now - can anyone spot the error of my ways? Paul

    Read the article

  • How to specify the order of XmlAttributes, using XmlSerializer

    - by demoncodemonkey
    XmlElement has an "Order" attribute which you can use to specify the precise order of your properties (in relation to each other anyway) when serializing using XmlSerializer. Is there a similar thing for XmlAttribute? I just want to set the order of the attributes from something like <MyType end="bob" start="joe" /> to <MyType start="joe" end="bob" /> This is just for readability, my own benefit really.

    Read the article

  • xmlns='' was not expected when deserializing nested classes

    - by Mavrik
    I have a problem when attempting to serialize class on a server, send it to the client and deserialize is on the destination. On the server I have the following two classes: [XmlRoot("StatusUpdate")] public class GameStatusUpdate { public GameStatusUpdate() {} public GameStatusUpdate(Player[] players, Command command) { this.Players = players; this.Update = command; } [XmlArray("Players")] public Player[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class Player { public Player() {} public Player(PlayerColors color) { Color = color; ... } [XmlAttribute("Color")] public PlayerColors Color { get; set; } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } } (The missing types are all enums). This generates the following XML on serialization: <?xml version="1.0" encoding="utf-16"?> <StatusUpdate> <Players> <Player Color="Cyan" X="67" Y="32" /> </Players> <Command>StartGame</Command> </StatusUpdate> On the client side, I'm attempting to deserialize that into following classes: [XmlRoot("StatusUpdate")] public class StatusUpdate { public StatusUpdate() { } [XmlArray("Players")] [XmlArrayItem("Player")] public PlayerInfo[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class PlayerInfo { public PlayerInfo() { } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } [XmlAttribute("Color")] public PlayerColor Color { get; set; } } However, the deserializer throws an exception: There is an error in XML document (2, 2). <StatusUpdate xmlns=''> was not expected. What am I missing or doing wrong?

    Read the article

  • Change xml attribute in foreach statement c#

    - by user1913479
    I need to save XML-attribute value in a database, using information if checkbox is checked. If checkbox is checked, the attribute value is "TRUE", otherwise it's false. When I use foreach statement, the last enumerated value is usually assigned. Here is the part of my code: XmlAttribute xmlAttribute = xmlDoc.CreateAttribute("BooleanValue"); foreach (string value in list) //list is a List<object> { XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.Element, "VALUE", ""); if (checkBox1.Checked || checkBox2.Checked || checkBox3.Checked) xmlAttribute.Value = "TRUE"; if (!checkBox1.Checked || !checkBox2.Checked || !checkBox3.Checked) xmlAttribute.Value = "FALSE"; xmlNode.Attributes.Append(xmlAttribute); xmlNode.InnerText = val; childNode.AppendChild(xmlNode); } When I run my application, I get an XML attribute xmlAttribute "FALSE" value anyway. What I need to have: I need to have the following XML: <ROOT><NODE><VALUE ATTRIBUTE="TRUE">Value 1</VALUE></NODE> <NODE><VALUE ATTRIBUTE="TRUE">Value 2</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 3</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 4</VALUE></NODE> <NODE><VALUE ATTRIBUTE="TRUE">Value 5</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 6</VALUE></NODE> </ROOT> What I actually get: <ROOT><NODE><VALUE ATTRIBUTE="FALSE">Value 1</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 2</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 3</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 4</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 5</VALUE></NODE> <NODE><VALUE ATTRIBUTE="FALSE">Value 6</VALUE></NODE> </ROOT> Because in C# FALSE value is stayed at last position in foreach loop The question is: how do I do to assign the correct values of my attribute. Thanks

    Read the article

  • xmlns='' was not expected when deserializing nested classes

    - by Mavrik
    I have a problem when attempting to serialize class on a server, send it to the client and deserialize is on the destination. On the server I have the following two classes: [XmlRoot("StatusUpdate")] public class GameStatusUpdate { public GameStatusUpdate() {} public GameStatusUpdate(Player[] players, Command command) { this.Players = players; this.Update = command; } [XmlArray("Players")] public Player[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class Player { public Player() {} public Player(PlayerColors color) { Color = color; ... } [XmlAttribute("Color")] public PlayerColors Color { get; set; } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } } (The missing types are all enums). This generates the following XML on serialization: <?xml version="1.0" encoding="utf-16"?> <StatusUpdate> <Players> <Player Color="Cyan" X="67" Y="32" /> </Players> <Command>StartGame</Command> </StatusUpdate> On the client side, I'm attempting to deserialize that into following classes: [XmlRoot("StatusUpdate")] public class StatusUpdate { public StatusUpdate() { } [XmlArray("Players")] [XmlArrayItem("Player")] public PlayerInfo[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class PlayerInfo { public PlayerInfo() { } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } [XmlAttribute("Color")] public PlayerColor Color { get; set; } } However, the deserializer throws an exception: There is an error in XML document (2, 2). <StatusUpdate xmlns=''> was not expected. What am I missing or doing wrong? EDIT: On request I'm also adding code used to serialize and deserialize: Server: public static byte[] SerializeObject(Object obj) { XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType()); StringWriter writer = new StringWriter(); // Clear pre-defined namespaces XmlSerializerNamespaces xsn = new XmlSerializerNamespaces(); xsn.Add("", ""); xmlSerializer.Serialize(writer, obj, xsn); writer.Flush(); // Send as little-endian UTF-16 string because the Serializer denotes XML as // utf-18 which cannot be easly changed UnicodeEncoding encoder = new UnicodeEncoding(false, false); return encoder.GetBytes(writer.ToString()); } Client: public static object DeserializeXml(string xmlData, Type type) { XmlSerializer xmlSerializer = new XmlSerializer(type); StringReader reader = new StringReader(xmlData); object obj = xmlSerializer.Deserialize(reader); return obj; } Deserialization is invoked with StatusUpdate update = (StatusUpdate) Util.DeserializeXml(xmlData, typeof (StatusUpdate));

    Read the article

  • F# Add Constructor to a Record?

    - by akaphenom
    Basically I want to have a single construct to deal with serializing to both JSON and formatted xml. Records workd nicley for serializing to/from json. However XmlSerializer requires a parameterless construtor. I don't really want to have to go through the exercise of building class objects for these constructs (principal only). I was hoping there could be some shortcut for getting a parameterless constructor onto a record (perhaps with a wioth statement or something). I can't get it to behave - has anybody in the community had any luck? module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Xml open System.Security.Authentication open System.Runtime.Serialization //add assemnbly reference System.Runtime.Serialization System.Xml open System.Xml.Serialization open System.Collections.Generic [<DataContract>] type ChemicalElementRecord = { [<XmlAttribute("name")>] [<field: DataMember(Name="name") >] Name:string [<XmlAttribute("name")>] [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<XmlAttribute("atomic-mass")>] [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } [<XmlRoot("freebase")>] [<DataContract>] type FreebaseResultRecord = { [<XmlAttribute("code")>] [<field: DataMember(Name="code") >] Code:string [<XmlArrayAttribute("results")>] [<XmlArrayItem(typeof<ChemicalElementRecord>, ElementName = "chemical-element")>] [<field: DataMember(Name="result") >] Result: ChemicalElementRecord array [<XmlElement("message")>] [<field: DataMember(Name="message") >] Message:string } let getJsonFromWeb() = let query = "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" let response = request.GetResponse() let result = try use reader = new StreamReader(response.GetResponseStream()) reader.ReadToEnd(); finally response.Close() let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L stream let test = // get some JSON from the web let stream = getJsonFromWeb() // convert the stream of JSON into an F# Record let JsonSerializer = Json.DataContractJsonSerializer(typeof<FreebaseResultRecord>) let result: FreebaseResultRecord = downcast JsonSerializer.ReadObject(stream) // save the Records to disk as JSON use fs = new FileStream(@"C:\temp\freebase.json", FileMode.Create) JsonSerializer.WriteObject(fs,result) fs.Close() // save the Records to disk as System Controlled XML let xmlSerializer = DataContractSerializer(typeof<FreebaseResultRecord>); use fs = new FileStream(@"C:\temp\freebase.xml", FileMode.Create) xmlSerializer.WriteObject(fs,result) fs.Close() use fs = new FileStream(@"C:\temp\freebase-pretty.xml", FileMode.Create) let xmlSerializer = XmlSerializer(typeof<FreebaseResultRecord>) xmlSerializer.Serialize(fs,result) fs.Close() ignore(test)

    Read the article

  • C# Custom user settings class not saving

    - by Zenox
    I have the following class: [Serializable] [XmlRoot ( ElementName = "TextData", IsNullable = false)] public class TextData { private System.Drawing.Font fontColor; [XmlAttribute ( AttributeName = "Font" )] public System.Drawing.Font Font { get; set; } [XmlAttribute ( AttributeName = "FontColor" )] public System.Drawing.Color FontColor { get; set; } [XmlAttribute ( AttributeName = "Text" )] public string Text { get; set; } public TextData ( ) { } // End of TextData } // End of TextData And Im attempting to save it with the following code: // Create our font dialog FontDialog fontDialog = new FontDialog ( ); fontDialog.ShowColor = true; // Display the dialog and check for an ok if ( DialogResult.OK == fontDialog.ShowDialog ( ) ) { // Save our changes for the font settings if ( null == Properties.Settings.Default.MainHeadlineTextData ) { Properties.Settings.Default.MainHeadlineTextData = new TextData ( ); } Properties.Settings.Default.MainHeadlineTextData.Font = fontDialog.Font; Properties.Settings.Default.MainHeadlineTextData.FontColor = fontDialog.Color; Properties.Settings.Default.Save ( ); } Everytime I load the the application, the Properties.Settings.Default.MainHeadlineTextData is still null. Saving does not seem to take effect. I read on another post that the class must be public and it is. Any ideas why this would not be working properly?

    Read the article

  • JAXB marshals XML differently to OutputStream vs. StringWriter

    - by Andy
    I apologize if this has been answered, but the search terms I have been using (i.e. JAXB @XmlAttribute condensed or JAXB XML marshal to String different results) aren't coming up with anything. I am using JAXB to un/marshal objects annotated with @XmlElement and @XmlAttribute annotations. I have a formatter class which provides two methods -- one wraps the marshal method and accepts the object to marshal and an OutputStream, the other just accepts the object and returns the XML output as a String. Unfortunately, these methods do not provide the same output for the same objects. When marshaling to a file, simple object fields internally marked with @XmlAttribute are printed as: <element value="VALUE"></element> while when marshaling to a String, they are: <element value="VALUE"/> I would prefer the second format for both cases, but I am curious as to how to control the difference, and would settle for them being the same regardless. I even created one static marshaller that both methods use to eliminate different instance values. The formatting code follows: /** Marker interface for classes which are listed in jaxb.index */ public interface Marshalable {} /** Local exception class */ public class XMLMarshalException extends BaseException {} /** Class which un/marshals objects to XML */ public class XmlFormatter { private static Marshaller marshaller = null; private static Unmarshaller unmarshaller = null; static { try { JAXBContext context = JAXBContext.newInstance("path.to.package"); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); unmarshaller = context.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException("There was a problem creating a JAXBContext object for formatting the object to XML."); } } public void marshal(Marshalable obj, OutputStream os) throws XMLMarshalException { try { marshaller.marshal(obj, os); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } } public String marshalToString(Marshalable obj) throws XMLMarshalException { try { StringWriter sw = new StringWriter(); marshaller.marshal(obj, sw); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } } } /** Example data */ @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class Data { @XmlAttribute(name = value) private String internalString; } /** Example POJO */ @XmlType @XmlRootElement(namespace = "project/schema") @XmlAccessorType(XmlAccessType.FIELD) public class Container implements Marshalable { @XmlElement(required = false, nillable = true) private int number; @XmlElement(required = false, nillable = true) private String word; @XmlElement(required = false, nillable = true) private Data data; } The result of calling marshal(container, new FileOutputStream("output.xml")) and marshalToString(container) are as follows: Output to file <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:container xmlns:ns2="project/schema"> <number>1</number> <word>stackoverflow</word> <data value="This is internal"></data> </ns2:container> and Output to String <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:container xmlns:ns2="project/schema"> <number>1</number> <word>stackoverflow</word> <data value="This is internal"/> </ns2:container>

    Read the article

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • WPF Tree doesn't work

    - by phenevo
    Could you tell me why I can't see subItems? I've got winforms apps and I added my wpfusercontrol:ObjectsAndZonesTree ServiceProvider is my webservice. Adn method to get listofcountires with subitems works properly (i get countires, regions from this countires, provinces etc...) ElementHost elementHost = new ElementHost { Width = 150, Height = 50, Dock = DockStyle.Fill, Child = new ObjectsAndZonesTree() }; this.splitContainer3.Panel1.Controls.Add(elementHost); XAML: <TreeView Name="GroupView" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type ServiceProvider:Country }" ItemsSource="{Binding Items}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type ServiceProvider:Region}" > <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> <DataTemplate DataType="{x:Type ServiceProvider:Province}" > <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> </TreeView.Resources> </TreeView> XAML.CS public ObjectsAndZonesTree() { InitializeComponent(); LoadView(); } private void LoadView() { GroupView.ItemsSource = new ServiceProvider().GetListOfObjectsAndZones(); } class Country: public class Country { string _name; [XmlAttribute] public string Name { get { return _name; } set { _name = value; } } string _code; [XmlAttribute] public string Code { get { return _code; } set { _code = value; } } string _continentCode; [XmlAttribute] public string ContinentCode { get { return _continentCode; } set { _continentCode = value; } } public Region[] ListOfRegions { get { return _listOfRegions; } set { _listOfRegions = value; } } private Region[] _listOfRegions; public IList<object> Items { get { IList<object> childNodes = new List<object>(); foreach (var group in this.ListOfRegions) childNodes.Add(group); return childNodes; } } } Class Region: public class Region { private Province[] _listOfProvinces; private string _name; private string _code; public Province[] ListOfProvinces { get { return _listOfProvinces; } set { _listOfProvinces = value; } } public string Name { get { return _name; } set { _name = value; } } public string Code { get { return _code; } set { _code = value; } } public string CountryCode { get { return _countryCode; } set { _countryCode = value; } } private string _countryCode; public IList<object> Items { get { IList<object> childNodes = new List<object>(); foreach (var group in this.ListOfProvinces) childNodes.Add(group); return childNodes; } } } It displays me only list of countires.

    Read the article

  • not able to Deserialize xml into object

    - by Ravisha
    I am having following peice of code ,where in i am trying to serialize and deserailize object of StringResource class. Please note Resource1.stringXml = its coming from resource file.If i pass strelemet.outerXMl i get the object from Deserialize object ,but if i pass Resource1.stringXml i am getting following exception {"< STRING xmlns='' was not expected."} System.Exception {System.InvalidOperationException} class Program { static void Main(string[] args) { StringResource str = new StringResource(); str.DELETE = "CanDelete"; str.ID= "23342"; XmlElement strelemet = SerializeObjectToXmlNode (str); StringResource strResourceObject = DeSerializeXmlNodeToObject<StringResource>(Resource1.stringXml); Console.ReadLine(); } public static T DeSerializeXmlNodeToObject<T>(string objectNodeOuterXml) { try { TextReader objStringsTextReader = new StringReader(objectNodeOuterXml); XmlSerializer stringResourceSerializer = new XmlSerializer(typeof(T),string.Empty); return (T)stringResourceSerializer.Deserialize(objStringsTextReader); } catch (Exception excep) { return default(T); } } public static XmlElement SerializeObjectToXmlNode(object obj) { using (MemoryStream memoryStream = new MemoryStream()) { try { XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces(); xmlNameSpace.Add(string.Empty, string.Empty); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; writerSettings.Encoding = System.Text.Encoding.UTF8; writerSettings.Indent = false; writerSettings.OmitXmlDeclaration = true; XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings); XmlSerializer xmlserializer = new XmlSerializer(obj.GetType()); xmlserializer.Serialize(writer, obj, xmlNameSpace); writer.Close(); memoryStream.Position = 0; XmlDocument serializeObjectDoc = new XmlDocument(); serializeObjectDoc.Load(memoryStream); return serializeObjectDoc.DocumentElement; } catch (Exception excep) { return null; } } } } public class StringResource { [XmlAttribute] public string DELETE; [XmlAttribute] public string ID; } < STRING ID="1" DELETE="True" /

    Read the article

  • XML deserialization doubling up on entities

    - by Nathan Loding
    I have an XML file that I am attempting to deserialize into it's respective objects. It works great on most of these objects, except for one item that is being doubled up on. Here's the relevant portion of the XML: <Clients> <Client Name="My Company" SiteID="1" GUID="xxx-xxx-xxx-xxx"> <Reports> <Report Name="First Report" Path="/Custom/FirstReport"> <Generate>true</Generate> </Report> </Reports> </Client> </Clients> "Clients" is a List<Client> object. Each Client object has a List<Report> object within it. The issue is that when this XML is deserialized, the List<Report> object has a count of 2 -- the "First Report" Report object is in there twice. Why? Here's the C#: public class Client { [System.Xml.Serialization.XmlArray("Reports"), System.Xml.Serialization.XmlArrayItem(typeof(Report))] public List<Report> Reports; } public class Report { [System.Xml.Serialization.XmlAttribute("Name")] public string Name; public bool Generate; [System.Xml.Serialization.XmlAttribute("Path")] public string Path; } class Program { static void Main(string[] args) { List<Client> _clients = new List<Client>(); string xmlFile = "myxmlfile.xml"; System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Client>), new System.Xml.Serialization.XmlRootAttribute("Clients")); using (FileStream stream = new FileStream(xmlFile, FileMode.Open)) { _clients = xmlSerializer.Deserialize(stream) as List<Client>; } foreach(Client _client in _clients) { Console.WriteLine("Count: " + _client.Reports.Count); // This write "2" foreach(Report _report in _client.Reports) { Console.WriteLine("Name: " + _report.Name); // Writes "First Report" twice } } } }

    Read the article

  • XML serialization of a collection in C#

    - by Archana R
    I have two classes as follows: public class Info { [XmlAttribute] public string language; public int version; public Book book; public Info() { } public Info(string l, int v, string author, int quantity, int price) { this.language = l; this.version = v; book = new Book(author, quantity, price); } } public class Book { [XmlAttribute] public string author; public int quantity; public int price; [XmlIgnore]public int total; public NameValueCollection nvcollection = new NameValueCollection(); public Book() { } public Book(string author, int quantity, int price) { this.author = author; this.quantity = quantity; this.price = price; total = quantity * price; nvcollection.Add(author, price.ToString()); } } I have created an ArrayList which adds the two instances of Info class as follows: FileStream fs = new FileStream("SerializedInfo.XML", FileMode.Create); List<Info> arrList = new List<Info>(); XmlSerializer xs = new XmlSerializer(typeof(List<Info>)); Info pObj = new Info("ABC", 3, "DEF", 2, 6); Info pObj1 = new Info("GHI", 4, "JKL", 2, 8); arrList.Add(pObj); arrList.Add(pObj1); xs.Serialize(fs, arrList); fs.Close(); But when I try to serialize, I get an exception as "There was an error reflecting type 'System.Collections.Generic.List`1[ConsoleApplicationSerialization.Info]'." Can anyone help me with it? Also, instead of namevaluecollection, which type of structure can i use?

    Read the article

  • Virtual properties duplicated during serialization when XmlElement attribute used

    - by Laramie
    The Goal: XML serialize an object that contains a list of objects of that and its derived types. The resulting XML should not use the xsi:type attribute to describe the type, to wit the names of the serialized XML elements would be an assigned name specific to the derived type, not always that of the base class, which is the default behavior. The Attempt: After exploring IXmlSerializable and IXmlSerializable with eerie XmlSchemaProvider methods and voodoo reflection to return specialized schemas and an XmlQualifiedName over the course of days, I found I was able to use the simple [XmlElement] attribute to accomplish the goal... almost. The Problem: Overridden properties appear twice when serializing. The exception reads "The XML element 'overriddenProperty' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element." I attempted using a *Specified property (see code), but it didn't work. Sample Code: Class Declaration using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlInclude(typeof(DerivedClass))] public class BaseClass { public BaseClass() { } [XmlAttribute("virt")] public virtual string Virtual { get; set; } [XmlIgnore] public bool VirtualSpecified { get { return (this is BaseClass); } set { } } [XmlElement(ElementName = "B", Type = typeof(BaseClass), IsNullable = false)] [XmlElement(ElementName = "D", Type = typeof(DerivedClass), IsNullable = false)] public List<BaseClass> Children { get; set; } } public class DerivedClass : BaseClass { public DerivedClass() { } [XmlAttribute("virt")] public override string Virtual { get { return "always return spackle"; } set { } } } Driver: BaseClass baseClass = new BaseClass() { Children = new List<BaseClass>() }; BaseClass baseClass2 = new BaseClass(){}; DerivedClass derivedClass1 = new DerivedClass() { Children = new List<BaseClass>() }; DerivedClass derivedClass2 = new DerivedClass() { Children = new List<BaseClass>() }; baseClass.Children.Add(derivedClass1); baseClass.Children.Add(derivedClass2); derivedClass1.Children.Add(baseClass2); I've been wrestling with this on and off for weeks and can't find the answer anywhere.

    Read the article

  • not able to Deserialize object

    - by Ravisha
    I am having following peice of code ,where in i am trying to serialize and deserailize object of StringResource class. Please note Resource1.stringXml = its coming from resource file.If i pass strelemet.outerXMl i get the object from Deserialize object ,but if i pass Resource1.stringXml i am getting following exception {"< STRING xmlns='' was not expected."} System.Exception {System.InvalidOperationException} class Program { static void Main(string[] args) { StringResource str = new StringResource(); str.DELETE = "CanDelete"; str.ID= "23342"; XmlElement strelemet = SerializeObjectToXmlNode (str); StringResource strResourceObject = DeSerializeXmlNodeToObject<StringResource>(Resource1.stringXml); Console.ReadLine(); } public static T DeSerializeXmlNodeToObject<T>(string objectNodeOuterXml) { try { TextReader objStringsTextReader = new StringReader(objectNodeOuterXml); XmlSerializer stringResourceSerializer = new XmlSerializer(typeof(T),string.Empty); return (T)stringResourceSerializer.Deserialize(objStringsTextReader); } catch (Exception excep) { return default(T); } } public static XmlElement SerializeObjectToXmlNode(object obj) { using (MemoryStream memoryStream = new MemoryStream()) { try { XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces(); xmlNameSpace.Add(string.Empty, string.Empty); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; writerSettings.Encoding = System.Text.Encoding.UTF8; writerSettings.Indent = false; writerSettings.OmitXmlDeclaration = true; XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings); XmlSerializer xmlserializer = new XmlSerializer(obj.GetType()); xmlserializer.Serialize(writer, obj, xmlNameSpace); writer.Close(); memoryStream.Position = 0; XmlDocument serializeObjectDoc = new XmlDocument(); serializeObjectDoc.Load(memoryStream); return serializeObjectDoc.DocumentElement; } catch (Exception excep) { return null; } } } } public class StringResource { [XmlAttribute] public string DELETE; [XmlAttribute] public string ID; }

    Read the article

  • Why does the OnDeserialization not fire for XML Deserialization?

    - by Jonathan
    I have a problem which I have been bashing my head against for the better part of three hours. I am almost certain that I've missed something blindingly obvious... I have a simple XML file: <?xml version="1.0" encoding="utf-8"?> <WeightStore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Records> <Record actual="150" date="2010-05-01T00:00:00" /> <Record actual="155" date="2010-05-02T00:00:00" /> </Records> </WeightStore> I have a simple class structure: [Serializable] public class Record { [XmlAttribute("actual")] public double weight { get; set; } [XmlAttribute("date")] public DateTime date { get; set; } [XmlIgnore] public double trend { get; set; } } [Serializable] [XmlRoot("WeightStore")] public class SimpleWeightStore { [XmlArrayAttribute("Records")] private List<Record> records = new List<Record>(); public List<Record> Records { get { return records; } } [OnDeserialized()] public void OnDeserialized_Method(StreamingContext context) { // This code never gets called Console.WriteLine("OnDeserialized"); } } I am using these in both calling code and in the class files: using System.Xml.Serialization; using System.Runtime.Serialization; I have some calling code: SimpleWeightStore weight_store_reload = new SimpleWeightStore(); TextReader reader = new StringReader(xml); XmlSerializer deserializer = new XmlSerializer(weight_store.GetType()); weight_store_reload = (SimpleWeightStore)deserializer.Deserialize(reader); The problem is that I am expecting OnDeserialized_Method to get called, and it isn't. I suspect it might have something to do with the fact that it's XML deserialization rather than Runtime deserialization, and perhaps I am using the wrong attribute name, but I can't find out what it might be. Any ideas, folks?

    Read the article

  • JAXB Unable To Handle Attribute with Colon (:) in name?

    - by Intellectual Tortoise
    I am attempting to use JAXB to unmarshall an XML files whose schema is defined by a DTD (ugh!). The external provider of the DTD has specified one of the element attributes as xml:lang: <!ATTLIST langSet id ID #IMPLIED xml:lang CDATA #REQUIRED > This comes into the xjc-generated class (standard generation; no *.xjb magic) as: @XmlAttribute(name = "xml:lang", required = true) @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String xmlLang; However, when unmarshalling valid XML files with JAXB, the xmlLang attribute is always null. When I edited the XML file, replacing xml:lang with lang and changed the @XmlAttribute to match, unmarshalling was successful (i.e. attributes were non-null). I did find this http://old.nabble.com/unmarshalling-ignores-element-attribute-%27xml%27-td22558466.html. But, the resolution there was to convert to XML Schema, etc. My strong preference is to go straight from an un-altered DTD (since it is externally provided and defined by an ISO standard). Is this a JAXB bug? Am I missing something about "namespaces" in attribute names? FWIW, java -version = "build 1.6.0_20-b02" and xjc -version = "xjc version "JAXB 2.1.10 in JDK 6""

    Read the article

  • Is there any way that an export-to-Excel function can be scalable?

    - by MusiGenesis
    Summary: ASP.Net website with a couple hundred users. Data is exported to Excel files which can be relatively large (~5 MB). In the pilot phase (just a few users), we are already seeing occasional errors on the server in the exporting method. Here's the stack trace: System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. --- System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.MemoryStream.set_Capacity(Int32 value) at System.IO.MemoryStream.EnsureCapacity(Int32 value) at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.TrackingMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.SparseMemoryStream.WriteAndCollapseBlocks(Byte[ ] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.SparseMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Packaging.CompressStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[] buffer, Int32 offset, Int32 count) at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32 offset, Int32 count) at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Write(String value) at System.Xml.XmlTextEncoder.Write(String text) at System.Xml.XmlTextWriter.WriteString(String text) at System.Xml.XmlText.WriteTo(XmlWriter w) at System.Xml.XmlAttribute.WriteContentTo(XmlWriter w) at System.Xml.XmlAttribute.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw) at System.Xml.XmlDocument.WriteTo(XmlWriter w) at System.Xml.XmlDocument.Save(Stream outStream) at OfficeOpenXml.ExcelWorksheet.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelWorksheet.cs:line 605 at OfficeOpenXml.ExcelWorkbook.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelWorkbook.cs:line 439 at OfficeOpenXml.ExcelPackage.Save() in C:\temp\XXXXXXXXXX\ExcelPackage\ExcelPackage.cs:line 348 at Framework.Exporting.Business.ExcelExport.BuildReport(HttpContext context) at WebUserControl.BtnXLS_Click(Object sender, EventArgs e) in C:\TEMP\XXXXXXXXXX\XXXXXXXXXX\OneList\UserControls\TicketReportExporter. ascx.cs:line 108 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.Rai sePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.XXXXXXXXXXX_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\XXXX\cdf32a52\d1a5eabd\App_Web_enxdwlks.1.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpAppli cation.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Even aside from this particular problem, in general exporting to Excel requires the instantiation of huge Excel objects on the server for each request, which I've always assumed to mean disqualifies Excel for "serious" work on a highly-loaded server. Is there any general way to export to Excel in a "light-weight" manner? Would simply streaming the data into a CSV file work for this?

    Read the article

  • Dynamic class annotation

    - by jlanza
    Hi, I want to annotate a class dynamically to make it the more generic as possible: public class Test<T> { @XmlAttribute(name = dynamicvalue) T[] data; public Test(String dynamicvalue) { } } Is there any way to achieve something like this. TA

    Read the article

  • protobuf-net: Issues deserializing DataMember fields in lieu of read-only property

    - by Paul Smith
    I'm having issues deserializing certain properties of ORM-generated entities using protobuf-net. I suspect something in the way the ORM manages serialization attributes on read-only properties (uses public backing fields with DataMember attributes & [de]serializes) those instead of the corresponding read-only property, which has an IgnoreDataMember attribute). Guid properties might have issues of their own, but the field vs. property thing is my working theory now. Here's a simplified example of the code. Say I have a class, Account with an AccountID read-only guid, and an AccountName read-write string. I serialize & immediately deserialize a clone. In this scenario I get one of two results (depending on the entity, haven't isolated the specific commonality yet). The deserialized clone either: ...has a different AccountID from the original, or ...throws an Incorrect wire-type deserializing Guid exception while deserializing. Here's example usage... Account acct = new Account() { AccountName = "Bob's Checking" }; Debug.WriteLine(acct.AccountID.ToString()); using (MemoryStream ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize<Account>(ms, acct); Debug.WriteLine(Encoding.UTF8.GetString(ms.GetBuffer())); ms.Position = 0; Account clone = ProtoBuf.Serializer.Deserialize<Account>(ms); Debug.WriteLine(clone.AccountID.ToString()); } And here's an example ORM'd class (simplified; hopefully haven't removed the cause of the issue in the process). Uses a shell game to deserialize read-only properties by exposing the backing field ("can't write" essentially becomes "shouldn't write," but we can scan code for instances of assigning to these fields, so the hack works for our purposes): [DataContract()] [Serializable()] public partial class Account { public Account() { _accountID = Guid.NewGuid(); } [XmlAttribute("AccountID")] [DataMember(Name = "AccountID", Order = 0)] public Guid _accountID; /// <summary> /// A read-only property; XML, JSON and DataContract serializers all seem /// to correctly recognize the public backing field when deserializing: /// </summary> [IgnoreDataMember] [XmlIgnore] public Guid AccountID { get { return this._accountID; } } [IgnoreDataMember] protected string _accountName; [DataMember(Name = "AccountName", Order = 1)] [XmlAttribute] public string AccountName { get { return this._accountName; } set { this._accountName = value; } } } XML, JSON and DataContract serializers all seem to serialize / deserialize matching object graphs here, so this attribute arrangement apparently causes those serializers to correctly assign to the public backing field when deserializing. I've tried protobuf-net with lists vs. single instances, different prefix styles, etc., but always either get the 'incorrect wire type ... Guid' exception, or the Guid property (field) not deserializing correctly. So the specific questions are, is there a quick workaround for this, and/or is there an explanation for both of outcomes 1 & 2 above, and/or can protobuf-net somehow be corralled into behaving like WCF in cases like this (i.e. follow the same DataMember/IgnoreDataMember semantics)? We hope not to have to create a protobuf dependency directly in the entity layer; if that's the case, we'll probably create proxy DTO entities with all public properties having protobuf attributes. (This is a subjective issue I have with all declarative serialization models; it's a ubiquitous pattern, but IMO, "normal" should be to have objects and serialization contracts decoupled.) Thanks!

    Read the article

  • protobuf-net: incorrect wire-type exception deserializing Guid properties

    - by Paul Smith
    I'm having issues deserializing certain Guid properties of ORM-generated entities using protobuf-net. Here's a simplified example of the code (reproduces most elements of the scenario, but doesn't reproduce the behavior; I can't expose our internal entities, so I'm looking for clues to account for the exception). Say I have a class, Account with an AccountID read-only guid, and an AccountName read-write string. I serialize & immediately deserialize a clone. Deserializing throws an Incorrect wire-type deserializing Guid exception while deserializing. Here's example usage... Account acct = new Account() { AccountName = "Bob's Checking" }; Debug.WriteLine(acct.AccountID.ToString()); using (MemoryStream ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize<Account>(ms, acct); Debug.WriteLine(Encoding.UTF8.GetString(ms.GetBuffer())); ms.Position = 0; Account clone = ProtoBuf.Serializer.Deserialize<Account>(ms); Debug.WriteLine(clone.AccountID.ToString()); } And here's an example ORM'd class (simplified, but demonstrates the relevant semantics I can think of). Uses a shell game to deserialize read-only properties by exposing the backing field ("can't write" essentially becomes "shouldn't write," but we can scan code for instances of assigning to these fields, so the hack works for our purposes). Again, this does not reproduce the exception behavior; I'm looking for clues as to what could: [DataContract()] [Serializable()] public partial class Account { public Account() { _accountID = Guid.NewGuid(); } [XmlAttribute("AccountID")] [DataMember(Name = "AccountID", Order = 1)] public Guid _accountID; /// <summary> /// A read-only property; XML, JSON and DataContract serializers all seem /// to correctly recognize the public backing field when deserializing: /// </summary> [IgnoreDataMember] [XmlIgnore] public Guid AccountID { get { return this._accountID; } } [IgnoreDataMember] protected string _accountName; [DataMember(Name = "AccountName", Order = 2)] [XmlAttribute] public string AccountName { get { return this._accountName; } set { this._accountName = value; } } } XML, JSON and DataContract serializers all seem to serialize / deserialize these object graphs just fine, so the attribute arrangement basically works. I've tried protobuf-net with lists vs. single instances, different prefix styles, etc., but still always get the 'incorrect wire-type ... Guid' exception when deserializing. So the specific questions is, is there any known explanation / workaround for this? I'm at a loss trying to trace what circumstances (in the real code but not the example) could be causing it. We hope not to have to create a protobuf dependency directly in the entity layer; if that's the case, we'll probably create proxy DTO entities with all public properties having protobuf attributes. (This is a subjective issue I have with all declarative serialization models; it's a ubiquitous pattern & I understand why it arose, but IMO, if we can put a man on the moon, then "normal" should be to have objects and serialization contracts decoupled. ;-) ) Thanks!

    Read the article

  • Parse an XML file

    - by karan@dotnet
    The following code shows a simple method of parsing through an XML file/string. We can get the parent name, child name, attributes etc from the XML. The namespace System.Xml would be the only additional namespace that we would be using. string myXMl = "<Employees>" + "<Employee ID='1' Name='John Mayer'" + "Address='12th Street'" + "City='New York' Zip='10004'>" + "</Employee>" + "</Employees>"; XmlDocument xDoc = new XmlDocument();xDoc.LoadXml(myXMl);XmlNodeList xNodeList = xDoc.SelectNodes("Employees/child::node()");foreach (XmlNode xNode in xNodeList){ if (xNode.Name == "Employee") { string ID = xNode.Attributes["ID"].Value; //Outputs: 1 string Name = xNode.Attributes["Name"].Value;//Outputs: John Mayer string Address = xNode.Attributes["Address"].Value;//Outputs: 12th Street string City = xNode.Attributes["City"].Value;//Outputs: New York string Zip = xNode.Attributes["Zip"].Value; //Outputs: 10004 }} Lets look at another XML: string myXMl = "<root>" + "<parent1>..some data</parent1>" + "<parent2>" + "<Child1 id='1' name='Adam'>data1</Child1>" + "<Child2 id='2' name='Stanley'>data2</Child2>" + "</parent2>" + "</root>"; XmlDocument xDoc = new XmlDocument();xDoc.LoadXml(myXMl);XmlNodeList xNodeList = xDoc.SelectNodes("root/child::node()"); //Traverse the entire XML nodes.foreach (XmlNode xNode in xNodeList) { //Looks for any particular nodes if (xNode.Name == "parent1") { //some traversing.... } if (xNode.Name == "parent2") { //If the parent node has child nodes then //traverse the child nodes foreach (XmlNode xNode1 in xNode.ChildNodes) { string childNodeName = xNode1.Name; //Ouputs: Child1 string childNodeData = xNode1.InnerText; //Outputs: data1 //Loop through each attribute of the child nodes foreach (XmlAttribute xAtt in xNode1.Attributes) { string attrName = xAtt.Name; //Outputs: id string attrValue = xAtt.Value; //Outputs: 1 } } }}  

    Read the article

1 2  | Next Page >