Search Results

Search found 26 results on 2 pages for 'xmlignore'.

Page 1/2 | 1 2  | Next Page >

  • C# Attribute XmlIgnore and XamlWriter class - XmlIgnore not working

    - by Horst Walter
    I have a class, containing a property Brush MyBrush marked as [XmlIgnore]. Nevertheless it is serialized in the stream causing trouble when trying to read via XamlReader. I did some tests, e.g. when changing the visibility (to internal) of the Property it is gone in the stream. Unfortunately I cannot do this in my particular scenario. Did anybody have the same issue and? Do you see any way to work around this? Remark: C# 4.0 as far I can tell This is a method from my Unit Test where I do test the XamlSerialization: // buffer to a StringBuilder StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer) {XamlWriterMode = XamlWriterMode.Expression}; XamlWriter.Save(testObject, manager); xml = sb.ToString(); Assert.IsTrue(!String.IsNullOrEmpty(xml) && !String.IsNullOrEmpty(xml), "Xaml Serialization failed for " + testObject.GetType() + " no xml string available"); xml = sb.ToString(); MemoryStream ms = xml.StringToStream(); object root = XamlReader.Load(ms); Assert.IsTrue(root != null, "After reading from MemoryStream no result for Xaml Serialization"); In one of my classes I use the Property Brush. In the above code this Unit Tests fails because of a Brush object not serializable is the value. When I remove the Setter (as below, the Unit Test passes. Using the XmlWriter (basically same test as above) it works. In the StringBuffer sb I can see that Property Brush is serialized when the Setter is there and not when removed (most likely another check ignoring the Property because of no setter). Other Properties with [XmlIgnore] are ignored as intended. [XmlIgnore] public Brush MyBrush { get { ..... } // removed because of problem with Serialization // set { ... } }

    Read the article

  • NHibernate FetchMode.Lazy

    - by RyanFetz
    I have an object which has a property on it that has then has collections which i would like to not load in a couple situations. 98% of the time i want those collections fetched but in the one instance i do not. Here is the code I have... Why does it not set the fetch mode on the properties collections? [DataContract(Name = "ThemingJob", Namespace = "")] [Serializable] public class ThemingJob : ServiceJob { [DataMember] public virtual Query Query { get; set; } [DataMember] public string Results { get; set; } } [DataContract(Name = "Query", Namespace = "")] [Serializable] public class Query : LookupEntity<Query>, DAC.US.Search.Models.IQueryEntity { [DataMember] public string QueryResult { get; set; } private IList<Asset> _Assets = new List<Asset>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Asset> Assets { get { return _Assets; } set { _Assets = value; } } private IList<Theme> _Themes = new List<Theme>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Theme> Themes { get { return _Themes; } set { _Themes = value; } } private IList<Affinity> _Affinity = new List<Affinity>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Affinity> Affinity { get { return _Affinity; } set { _Affinity = value; } } private IList<Word> _Words = new List<Word>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Word> Words { get { return _Words; } set { _Words = value; } } } using (global::NHibernate.ISession session = NHibernateApplication.GetCurrentSession()) { global::NHibernate.ICriteria criteria = session.CreateCriteria(typeof(ThemingJob)); global::NHibernate.ICriteria countCriteria = session.CreateCriteria(typeof(ThemingJob)); criteria.AddOrder(global::NHibernate.Criterion.Order.Desc("Id")); var qc = criteria.CreateCriteria("Query"); qc.SetFetchMode("Assets", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Themes", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Affinity", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Words", global::NHibernate.FetchMode.Lazy); pageIndex = Convert.ToInt32(pageIndex) - 1; // convert to 0 based paging index criteria.SetMaxResults(pageSize); criteria.SetFirstResult(pageIndex * pageSize); countCriteria.SetProjection(global::NHibernate.Criterion.Projections.RowCount()); int totalRecords = (int)countCriteria.List()[0]; return criteria.List<ThemingJob>().ToPagedList<ThemingJob>(pageIndex, pageSize, totalRecords); }

    Read the article

  • Font serialization in vb.net

    - by jovany
    Hello all, as the title says , I need to serialize my font. I have tried the following approach unfortunately to no avail. This is what I have and what happens; I have a drawing application and certain variables and properties need to be serialized. (So , Xml.Serialization has been used.) Now this has already been done in a huge portion and I've created some other attributes which needed to be serialized and it works. There is one base class and classes such as drawablestar, drawableeclipse ,etc. all inherit from this class. As does my drawabletextboxclass. The base class is Serializable as can be seen in the sample below. It looks like this... Imports System.Xml.Serialization <Serializable()> _ Public MustInherit Class Drawable ' Drawing characteristics. 'Font characteristics <XmlIgnore()> Public FontFamily As String <XmlIgnore()> Public FontSize As Integer <XmlIgnore()> Public FontType As Integer <XmlIgnore()> Public ForeColor As Color <XmlIgnore()> Public FillColor As Color <XmlAttributeAttribute()> Public LineWidth As Integer = 0 <XmlAttributeAttribute()> Public X1 As Integer <XmlAttributeAttribute()> Public Y1 As Integer <XmlAttributeAttribute()> Public X2 As Integer <XmlAttributeAttribute()> Public Y2 As Integer ' attributes for size textbox <XmlAttributeAttribute()> Public widthLabel As Integer <XmlAttributeAttribute()> Public heightLabel As Integer '<XmlTextAttribute()> Public FontFamily As String '<XmlAttributeAttribute()> Public FontSize As Integer 'this should actually not be here.. <XmlAttributeAttribute()> Public s_InsertLabel As String ' Indicates whether we should draw as selected. <XmlIgnore()> Public IsSelected As Boolean = False ' Constructors. Public Sub New() ForeColor = Color.Black FillColor = Color.White 'FontFamily = "Impact" 'FontSize = 12 End Sub Friend WriteOnly Property _Label() As String Set(ByVal Value As String) s_InsertLabel = Value End Set End Property Public Sub New(ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0) LineWidth = line_width ForeColor = fore_color FillColor = fill_color ' FontFamily = Font_Family ' FontSize = Font_Size End Sub ' Property procedures to serialize and ' deserialize ForeColor and FillColor. <XmlAttributeAttribute("ForeColor")> _ Public Property ForeColorArgb() As Integer Get Return ForeColor.ToArgb() End Get Set(ByVal Value As Integer) ForeColor = Color.FromArgb(Value) End Set End Property <XmlAttributeAttribute("BackColor")> _ Public Property FillColorArgb() As Integer Get Return FillColor.ToArgb() End Get Set(ByVal Value As Integer) FillColor = Color.FromArgb(Value) End Set End Property 'Property procedures to serialize and 'deserialize Font <XmlAttributeAttribute("InsertLabel")> _ Public Property InsertLabel_() As String Get Return s_InsertLabel End Get Set(ByVal value As String) s_InsertLabel = value End Set End Property <XmlAttributeAttribute("FontSize")> _ Public Property FontSizeGet() As Integer Get Return FontSize End Get Set(ByVal value As Integer) FontSize = value End Set End Property <XmlAttributeAttribute("FontFamily")> _ Public Property FontFamilyGet() As String Get Return FontFamily End Get Set(ByVal value As String) FontFamily = value End Set End Property <XmlAttributeAttribute("FontType")> _ Public Property FontType_() As Integer Get Return FontType End Get Set(ByVal value As Integer) FontType = value End Set End Property #Region "Methods to override" Public MustOverride Sub Draw(ByVal gr As Graphics) ' Return the object's bounding rectangle. Public MustOverride Function GetBounds() As Rectangle ...... ........ ..... End Class [/code] My textbox class which looks like this , is the one that needs to save it's font. Imports System.Math Imports System.Xml.Serialization Imports System.Windows.Forms <Serializable()> _ Public Class DrawableTextBox Inherits Drawable Private i_StringLength As Integer Private i_StringWidth As Integer Private drawFont As Font = New Font(FontFamily, 12, FontStyle.Regular) Private brsTextColor As Brush = Brushes.Black Private s_insertLabelTextbox As String = "label" ' Constructors. Public Sub New() End Sub Public Sub New(ByVal objCanvas As PictureBox, ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0, Optional ByVal new_x1 As Integer = 0, Optional ByVal new_y1 As Integer = 0, Optional ByVal new_x2 As Integer = 1, Optional ByVal new_y2 As Integer = 1) MyBase.New(fore_color, fill_color, line_width) Dim objGraphics As Graphics = objCanvas.CreateGraphics() X1 = new_x1 Y1 = new_y1 'Only rectangles ,circles and stars can resize for now b_Movement b_Movement = True Dim frm As New frmTextbox frm.MyFont = drawFont frm.ShowDialog() If frm.DialogResult = DialogResult.OK Then FontFamily = frm.MyFont.FontFamily.Name FontSize = frm.MyFont.Size FontType = frm.MyFont.Style 'drawFont = frm.MyFont drawFont = New Font(FontFamily, FontSize) drawFont = FontAttributes() brsTextColor = New SolidBrush(frm.txtLabel.ForeColor) s_InsertLabel = frm.txtLabel.Text i_StringLength = s_InsertLabel.Length 'gefixtf Dim objSizeF As SizeF = objGraphics.MeasureString(s_InsertLabel, drawFont, New PointF(X2 - X1, Y2 - Y1), New StringFormat(StringFormatFlags.NoClip)) Dim objPoint As Point = objCanvas.PointToClient(New Point(X1 + objSizeF.Width, Y1 + objSizeF.Height)) widthLabel = objSizeF.Width heightLabel = objSizeF.Height X2 = X1 + widthLabel Y2 = Y1 + heightLabel Else Throw New ApplicationException() End If End Sub ' Draw the object on this Graphics surface. Public Overrides Sub Draw(ByVal gr As System.Drawing.Graphics) ' Make a Rectangle representing this rectangle. Dim rectString As Rectangle rectString = New Rectangle(X1, Y1, widthLabel, heightLabel) rectString = GetBounds() ' See if we're selected. If IsSelected Then gr.DrawString(s_InsertLabel, drawFont, brsTextColor, X1, Y1) 'gr.DrawRectangle(Pens.Black, rect) ' Pens.Transparent gr.DrawRectangle(Pens.Black, rectString) ' Draw grab handles. DrawGrabHandle(gr, X1, Y1) DrawGrabHandle(gr, X1, Y2) DrawGrabHandle(gr, X2, Y2) DrawGrabHandle(gr, X2, Y1) Else gr.DrawString(s_InsertLabel, drawFont, brsTextColor, X1, Y1) 'gr.DrawRectangle(Pens.Black, rect) ' Pens.Transparent gr.DrawRectangle(Pens.Black, rectString) End If End Sub 'get fontattributes Public Function FontAttributes() As Font Return New Font(FontFamily, 12, FontStyle.Regular) End Function ' Return the object's bounding rectangle. Public Overrides Function GetBounds() As System.Drawing.Rectangle Return New Rectangle( _ Min(X1, X1), _ Min(Y1, Y1), _ Abs(widthLabel), _ Abs(heightLabel)) End Function ' Return True if this point is on the object. Public Overrides Function IsAt(ByVal x As Integer, ByVal y As Integer) As Boolean Return (x >= Min(X1, X2)) AndAlso _ (x <= Max(X1, X2)) AndAlso _ (y >= Min(Y1, Y2)) AndAlso _ (y <= Max(Y1, Y2)) End Function ' Move the second point. Public Overrides Sub NewPoint(ByVal x As Integer, ByVal y As Integer) X2 = x Y2 = y End Sub ' Return True if the object is empty (e.g. a zero-length line). Public Overrides Function IsEmpty() As Boolean Return (X1 = X2) AndAlso (Y1 = Y2) End Function End Class The coordinates ( X1 ,X2,Y1, Y2 ) are needed to draw a circle , rectangle etc. ( in the other classes ).This all works. If I load my saved file it shows me the correct location and correct size of drawn objects. If I open my xml file I can see all values are correctly saved ( including my FontFamily ). Also the color which can be adjusted is saved and then properly displayed when I load a previously saved drawing. Of course because the coordinates work, if I insert a textField ,the location where it is being displayed is correct. However here comes the problem , my fontSize and fontfamily don't work. As you can see I created them in the base class, However this does not work. Is my approach completely off? What can I do ? Before saving img14.imageshack.us/i/beforeos.jpg/ After loading the Font jumps back to Sans serif and size 12. I could really use some help here.. Edit: I've been using the sample from this website http://www.vb-helper.com/howto_net_drawing_framework.html

    Read the article

  • DataContractSerializer: preserve string member that happens to be raw xml?

    - by bwerks
    I'm a little inexperienced with the DataContract paradigm, and I'm running into a deserialization problem. I have a field that's a string, but it contains xml and it's not being deserialized correctly. I have a feeling that it's because the DCS is treating it as input to the serializer and not as an opaque string object. Is there some way to mark a DataMember in code to say "This thing is a string, don't treat its contents as xml" similar to XmlIgnore? Thanks!

    Read the article

  • Serialize .Net object to json, controlled using xml attributes

    - by sprocketonline
    I have a .Net object which I've been serializing to Xml and is decorated with Xml attributes. I would now like to serialize the same object to Json, preferably using the Newtonsoft Json.Net library. I'd like to go directly from the .Net object in memory to a Json string (without serializing to Xml first). I do not wish to add any Json attributes to the class, but instead would like for the Json serializer use the existing Xml attributes. [XmlRoot("hello")] public class world{ [XmlIgnore] public int ignoreMe{ get; } [XmlElement("foo")] public int bar{ get; } [XmlElement("marco")] public int polo{ get; } } becomes "hello":{ "foo":0, "marco":0 }

    Read the article

  • How to seralize only some properties in .Net?

    - by Beta033
    This is for a web project so i have several classes that inherit from Web.UI. I only want to serialize very particular properties (basically, only local properties) I'm aware of the XMLIgnore property that can be placed on a property to ignore items, but this won't work in my context since that would require modifying a bunch of stuff that i really don't want to modify (and probably can't). So how do i tell the xml serializer to ignore everything except for X and Y or tell it to seralize just X and Y? i could just create my own xml in a string builder or something and if that's the only way, so be it. however i'm looking for a method that will employ the built in XML stuff. Thanks

    Read the article

  • Why can't I expose an interface in a .NET asmx web service?

    - by mcliedtk
    I have a .NET web service (using asmx...have not upgraded to WCF yet) that exposes the following: public class WidgetVersion1 : IWidget {} public class WidgetVersion2 : IWidget {} When I attempt to bind to the web service, I get the following serialization error: Cannot serialize member WidgetVersion1 of type IWidget because it is an interface. I have tried adding various attributes to the IWidget interface (XmlIgnore, SoapIgnore, NonSerialized), but they are not valid on an interface. Does anyone know why I am unable to expose the interface? I assume WSDL does not support interfaces, but couldn't .NET get around this by simply not serializing the interface? Are there any ways around this apart from removing the IWidget interface from the WidgetVersion1 and WidgetVersion2 class definitions?

    Read the article

  • .NET XML Serialization, possibly to use a different method name than PropertySpecified for ignoring

    - by Lasse V. Karlsen
    I have a bunch of classes that I intend to serialize in order to transport over a webservice call. These classes already have properties that return whether a given "real" property has a value or not, that is ingrained in a lot of code of our product. Is it possible, for instance through attributes, for me to specify that each "real" property should be included if a specified other property returns true, but not one that is called RealPropertyNameSpecified? ie. for instance if I have this class: [XmlType("test")] public class TestClass { [XmlIgnore] public bool NameHasGotAValue { get; set; } [XmlElement("name")] public string Name { get; set; } } Is it possible for me to use the NameHasGotAValue as the "*Specified" method for the Name property, or is my only option to either rename NameHasGotAValue, add a NameSpecified method, or implement IXmlSerializable?

    Read the article

  • Need to ignore property in XmlSerialization because of circular reference

    - by NestorArturo
    Have an object with a property I don't need to serialize. The type of this property generates a circular reference which I expected, so I decorated this property with everything comes to my mind: private clsDeclaracion _Declaracion; [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [System.Xml.Serialization.XmlIgnore] public clsDeclaracion Declaracion { get { return _Declaracion; } set { _Declaracion = value; } } However, the circular reference keeps firing. Tried using a public field with no luck. This is my serialization code: System.Xml.Serialization.XmlSerializer Serializador = new System.Xml.Serialization.XmlSerializer(objeto.GetType()); using (StreamWriter SW = System.IO.File.CreateText(ArchivoTemp)) { Serializador.Serialize(SW, objeto); }

    Read the article

  • Suppress Null Value Types from Being Emitted by XmlSerializer

    - by Ben Griswold
    Please consider the following Amount value type property which is marked as a nullable XmlElement: [XmlElement(IsNullable=true)] public double? Amount { get ; set ; } When a nullable value type is set to null, the C# XmlSerializer result looks like the following: <amount xsi:nil="true" /> Rather than emitting this element, I would like the XmlSerializer to suppress the element completely. Why? We're using Authorize.NET for online payments and Authorize.NET rejects the request if this null element exists. The current solution/workaround is to not serialize the Amount value type property at all. Instead we have created a complementary property, SerializableAmount, which is based on Amount and is serialized instead. Since SerializableAmount is of type String, which like reference types are suppressed by the XmlSerializer if null by default, everything works great. /// <summary> /// Gets or sets the amount. /// </summary> [XmlIgnore] public double? Amount { get; set; } /// <summary> /// Gets or sets the amount for serialization purposes only. /// This had to be done because setting value types to null /// does not prevent them from being included when a class /// is being serialized. When a nullable value type is set /// to null, such as with the Amount property, the result /// looks like: &gt;amount xsi:nil="true" /&lt; which will /// cause the Authorize.NET to reject the request. Strings /// when set to null will be removed as they are a /// reference type. /// </summary> [XmlElement("amount", IsNullable = false)] public string SerializableAmount { get { return this.Amount == null ? null : this.Amount.ToString(); } set { this.Amount = Convert.ToDouble(value); } } Of course, this is just a workaround. Is there a cleaner way to suppress null value type elements from being emitted?

    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

  • 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

  • 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

  • Creating XML problem using c#

    - by Pankaj
    I am searching a batter solution for creating xml through xml serialization. What i need, i have a given format like this <product Id="1"> <name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name> <notes> <note>!--note 1---</note> <note>!--note 2--</note> ...... </notes> </product> what i am doing here, i created a 2 classes like this public class product { [XmlElement("name")] public string Name { get; set; } [XmlArray("notes")] public List<notes> ListNotes { get; set; } } public class notes { [XmlIgnore] public string Note { get; set; } } when i am serializing this then i am getting xml in this formate <product Id="1"> <name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name> <notes> <notes> <note>!--note 1---</note> <note>!--note 2--</note> </notes> </notes> </product> i don't want extra . Any batter solution to solve this problem? Thanks

    Read the article

  • Problem creating XML using c#

    - by Pankaj
    I am searching a batter solution for creating xml through xml serialization. What i need, i have a given format like this <product Id="1"> <name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name> <notes> <note>!--note 1---</note> <note>!--note 2--</note> ...... </notes> </product> what i am doing here, i created a 2 classes like this public class product { [XmlElement("name")] public string Name { get; set; } [XmlArray("notes")] public List<notes> ListNotes { get; set; } } public class notes { [XmlIgnore] public string Note { get; set; } } when i am serializing this then i am getting xml in this formate <product Id="1"> <name>2 1/2 X 6 PVC NIPPLE TOE SCH 80</name> <notes> <notes> <note>!--note 1---</note> <note>!--note 2--</note> </notes> </notes> </product> i don't want extra <notes>. Any batter solution to solve this problem? Thanks

    Read the article

  • Setting minOccurs="0" (not required) on web service parameters of type int

    - by Alex Angas
    I have an ASP.NET 2.0 web method with the following signature: [WebMethod] public QueryResult[] GetListData( string url, string list, string query, int noOfItems, string titleField) I'm running the disco.exe tool to generate .wsdl and .disco files from this web service for use in SharePoint. The following WSDL for the parameters is being generated: <s:element minOccurs="0" maxOccurs="1" name="url" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="list" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="query" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="noOfItems" type="s:int" /> <s:element minOccurs="0" maxOccurs="1" name="titleField" type="s:string" /> Why does the int parameter have minOccurs set to 1 instead of 0 and how do I change it? I've tried the following without success: [XmlElementAttribute(IsNullable=false)] in the parameter declaration: makes no difference (as expected when you think about it) [XmlElementAttribute(IsNullable=true)] in the parameter declaration: gives error "IsNullable may not be 'true' for value type System.Int32. Please consider using Nullable instead." changing the parameter type to int? : keeps minOccurs="1" and adds nillable="true" [XmlIgnore] in the parameter declaration: the parameter is never output to the WSDL at all

    Read the article

  • Omit Properties from WebControl Serialization

    - by Laramie
    I have to serialize several objects inheriting from WebControl for database storage. These include several unecessary (to me) properties that I would prefer to omit from serialization. For example BackColor, BorderColor, etc. Here is an example of an XML serialization of one of my controls inheriting from WebControl. <Control xsi:type="SerializePanel"> <ID>grCont</ID> <Controls /> <BackColor /> <BorderColor /> <BorderWidth /> <CssClass>grActVid bwText</CssClass> <ForeColor /> <Height /> <Width /> ... </Control> I have been trying to create a common base class for my controls that inherits from WebControl and uses the "xxxSpecified" trick to selectively choose not to serialize certain properties. For example to ignore an empty BorderColor property, I'd expect [XmlIgnore] public bool BorderColorSpecified() { return !base.BorderColor.IsEmpty; } to work, but it's never called during serialization. I've also tried it in the class to be serialized as well as the base class. Since the classes themselves might change, I'd prefer not to have to create a custom serializer. Any ideas?

    Read the article

  • Properly obsoleting old members in an XML Serializable class in C# VB .NET

    - by George
    Hi! Some time ago I defined a class that was serialized using XML. That class contained a serializable propertyA of integer type. Now I have extended and updated this class, whereby a new propertyB was added, whose type is another class that also has several serializable properties. The new propertyB is now supposed to play the role of propertyA, that is since type of propertyB is another class, one of its members would contain the value that previously propertyA contained, thus making peroptyA obsolete. What I am trying to figure out is how do I make sure that when I desireliaze the OLD version of this class (without propertyB in it), I make sure that the desreializer would take the value of propertyA from the old calss and set it as a value of one of the members of propertyB in a new class? Private WithEvents _Position As Position = New Position(Alignment.MiddleMiddle, 0, True, 0, True) Public Property Position() As Position 'NEW composite property that holds the value of the obsolted property, i.e. Alignment Get Return _Position End Get Set(ByVal value As Position) _Position = value End Set End Property Private _Alignment As Alignment = Alignment.MiddleMiddle <Xml.Serialization.XmlIgnore(), Obsolete("Use Position property instead.")> _ Public Property Alignment() As Alignment'The old, obsoleted property that I guess must be left for compliance with deserializing the old version of this class Get Return _Alignment End Get Set(ByVal value As Alignment) _Alignment = value End Set End Property Can you help me, please?

    Read the article

  • Json.Net Issues: StackOverflowException is thrown when serialising circular dependent ISerializable object with ReferenceLoopHandling.Ignore

    - by keyr
    I have a legacy application that used binary serialisation to persist the data. Now we wanted to use Json.net 4.5 to serialise the data without much changes to the existing classes. Things were working nice till we hit a circular dependent class. Is there any workaround to solve this problem? Sample code as shown below [Serializable] class Department : ISerializable { public Employee Manager { get; set; } public string Name { get; set; } public Department() { } public Department( SerializationInfo info, StreamingContext context ) { Manager = ( Employee )info.GetValue( "Manager", typeof( Employee ) ); Name = ( string )info.GetValue( "Name", typeof( string ) ); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { info.AddValue( "Manager", Manager ); info.AddValue( "Name", Name ); } } [Serializable] class Employee : ISerializable { [NonSerialized] //This does not work [XmlIgnore]//This does not work private Department mDepartment; public Department Department { get { return mDepartment; } set { mDepartment = value; } } public string Name { get; set; } public Employee() { } public Employee( SerializationInfo info, StreamingContext context ) { Department = ( Department )info.GetValue( "Department", typeof( Department ) ); Name = ( string )info.GetValue( "Name", typeof( string ) ); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { info.AddValue( "Department", Department ); info.AddValue( "Name", Name ); } } And the test code Department department = new Department(); department.Name = "Dept1"; Employee emp1 = new Employee { Name = "Emp1", Department = department }; department.Manager = emp1; Employee emp2 = new Employee() { Name = "Emp2", Department = department }; IList<Employee> employees = new List<Employee>(); employees.Add( emp1 ); employees.Add( emp2 ); var memoryStream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize( memoryStream, employees ); memoryStream.Seek( 0, SeekOrigin.Begin ); IList<Employee> deserialisedEmployees = formatter.Deserialize( memoryStream ) as IList<Employee>; //Works nicely JsonSerializerSettings jsonSS= new JsonSerializerSettings(); jsonSS.TypeNameHandling = TypeNameHandling.Objects; jsonSS.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full; jsonSS.Formatting = Formatting.Indented; jsonSS.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //This is not working!! //jsonSS.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; //This is also not working!! jsonSS.PreserveReferencesHandling = PreserveReferencesHandling.All; string jsonAll = JsonConvert.SerializeObject( employees, jsonSS ); //Throws stackoverflow exception Edit1: The issue has been reported to Json (http://json.codeplex.com/workitem/23668)

    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

  • Control XML serialization of Dictionary<K, T>

    - by Luca
    I'm investigating about XML serialization, and since I use lot of dictionary, I would like to serialize them as well. I found the following solution for that (I'm quite proud of it! :) ). [XmlInclude(typeof(Foo))] public class XmlDictionary<TKey, TValue> { /// <summary> /// Key/value pair. /// </summary> public struct DictionaryItem { /// <summary> /// Dictionary item key. /// </summary> public TKey Key; /// <summary> /// Dictionary item value. /// </summary> public TValue Value; } /// <summary> /// Dictionary items. /// </summary> public DictionaryItem[] Items { get { List<DictionaryItem> items = new List<DictionaryItem>(ItemsDictionary.Count); foreach (KeyValuePair<TKey, TValue> pair in ItemsDictionary) { DictionaryItem item; item.Key = pair.Key; item.Value = pair.Value; items.Add(item); } return (items.ToArray()); } set { ItemsDictionary = new Dictionary<TKey,TValue>(); foreach (DictionaryItem item in value) ItemsDictionary.Add(item.Key, item.Value); } } /// <summary> /// Indexer base on dictionary key. /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue this[TKey key] { get { return (ItemsDictionary[key]); } set { Debug.Assert(value != null); ItemsDictionary[key] = value; } } /// <summary> /// Delegate for get key from a dictionary value. /// </summary> /// <param name="value"></param> /// <returns></returns> public delegate TKey GetItemKeyDelegate(TValue value); /// <summary> /// Add a range of values automatically determining the associated keys. /// </summary> /// <param name="values"></param> /// <param name="keygen"></param> public void AddRange(IEnumerable<TValue> values, GetItemKeyDelegate keygen) { foreach (TValue v in values) ItemsDictionary.Add(keygen(v), v); } /// <summary> /// Items dictionary. /// </summary> [XmlIgnore] public Dictionary<TKey, TValue> ItemsDictionary = new Dictionary<TKey,TValue>(); } The classes deriving from this class are serialized in the following way: <FooDictionary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Items> <DictionaryItemOfInt32Foo> <Key/> <Value/> </DictionaryItemOfInt32XmlProcess> <Items> This give me a good solution, but: How can I control the name of the element DictionaryItemOfInt32Foo What happens if I define a Dictionary<FooInt32, Int32> and I have the classes Foo and FooInt32? Is it possible to optimize the class above? THank you very much!

    Read the article

1 2  | Next Page >