Search Results

Search found 259 results on 11 pages for 'xmlserializer'.

Page 2/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • WCF XmlSerializer assembly not speeding up first request

    - by Matt Dearing
    I am generating proxy classes to a clients java webservice wsdls and xsd files with svcutil. The first call made to each service proxy class takes a very long time. I was hoping to speed this up by generating the XmlSerializers assembly myself (based on the article How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer), but when I do the first call to each service still takes the same amount of time. Here are the steps I am following: //generate strong name key file sn -k Blah.snk //generate the proxy class file svcutil blah.wsdl blah2.wsdl blah3.wsdl ... base.xsd blah.xsd ... /UseSerializerForFaults /ser:XmlSerializer /n:*,SomeNamespace /out:Blah.cs //compile the class into an assembly signing it with the strong name key file csc /target:library /keyfile:Blah.snk /out:Blah.dll Blah.cs //generate the XmlSerializer code this will give us Blah.XmlSerializers.dll.cs svcutil /t:xmlSerializer Blah.dll //compile the xmlserializer code into its own dll using the same key to sign it and referencing the original dll csc /target:library /keyfile:Blah.snk /out:Blah.XmlSerializers.dll Blah.XmlSerializers.dll.cs /r:Blah.dll I then create a standard Console application that references both Blah.dll and Blah.XmlSerializers.dll. I will then try something like: //BlahProxy is one of the generated service proxy classes BlahProxy p = new BlahProxy(); //this call takes 30ish seconds p.SomeMethod(); BlahProxy p2 = new BlahProxy(); //this call takes < 1 second p2.SomeMethod(); //BlahProx2y is one of the generated service proxy classes BlahProxy2 p3 = new BlahProxy2(); //this call takes 30ish seconds p3.SomeMethod(); BlahProxy2 p4 = new BlahProxy2(); //this call takes < 1 second p4.SomeMethod(); I know that the problem is not server side because I don't see the request made in Fiddler until around 29 seconds. Subsequent calls to each service take < 1 second, so thats why I was hoping the main slow down was the .net runtime generating the xmlserializer code itself, compiling it and loading the assembly. I figured this would be the reason the first call to each service is slow and the rest are fast. Unfortunatley, me generating the code myself is not speeding anything up. Does anyone see what I am doing wrong?

    Read the article

  • Serializing a DataType="time" field using XmlSerializer

    - by CraftyFella
    Hi, I'm getting an odd result when serializing a DateTime field using XmlSerializer. I have the following class: public class RecordExample { [XmlElement("TheTime", DataType = "time")] public DateTime TheTime { get; set; } [XmlElement("TheDate", DataType = "date")] public DateTime TheDate { get; set; } public static bool Serialize(Stream stream, object obj, Type objType, Encoding encoding) { try { using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { Encoding = encoding })) { var xmlSerializer = new XmlSerializer(objType); if (writer != null) xmlSerializer.Serialize(writer, obj); } return true; } catch (Exception) { return false; } } } When i call the use the XmlSerializer with the following testing code: var obj = new RecordExample {TheDate = DateTime.Now.Date, TheTime = new DateTime(0001, 1, 1, 12, 00, 00)}; var ms = new MemoryStream(); RecordExample.Serialize(ms, obj, typeof (RecordExample), Encoding.UTF8); txtSource2.Text = Encoding.UTF8.GetString(ms.ToArray()); I get some strange results, here's the xml that is produced: <?xml version="1.0" encoding="utf-8"?> <RecordExample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <TheTime>12:00:00.0000000+00:00</TheTime> <TheDate>2010-03-08</TheDate> </RecordExample> Any idea's how i can get the "TheTime" element to contain a time which looks more like this: <TheTime>12:00:00.0Z</TheTime> ...as that's what i was expecting? Thanks Dave

    Read the article

  • Unknown attribute xsi:type in XmlSerializer

    - by vanccoon
    I am learning XML Serialization and meet an issue, I have two claess [System.Xml.Serialization.XmlInclude(typeof(SubClass))] public class BaseClass { } public class SubClass : BaseClass { } I am trying to serialize a SubClass object into XML file, I use blow code XmlSerializer xs = new XmlSerializer(typeof(Base)); xs.Serialize(fs, SubClassObject); I noticed Serialization succeed, but the XML file is kind of like ... If I use XmlSerializer xs = new XmlSerializer(typeof(Base)); SubClassObject = xs.Deserialize(fs) as SubClass; I noticed it will complain xsi:type is unknown attribute(I registered an event), although all information embedded in the XML was parsed successfully and members in SubClassObject was restored correctly. Anyone has any idea why there is error in parsing xsi:type and anything I did wrong? Thanks

    Read the article

  • C# XMLSerializer fails with List<T>

    - by Redshirt
    Help... I'm using a singleton class to save all my settings info. It's first utilized by calling Settings.ValidateSettings(@"C:\MyApp") The problem I'm having is that 'List Contacts' is causing the xmlserializer to fail to write the settings file, or to load said settings. If I comment out the List then I have no problems saving/loading the xml file. What am I doing wrong... Thanks in advance // The actual settings to save public class MyAppSettings { public bool FirstLoad { get; set; } public string VehicleFolderName { get; set; } public string ContactFolderName { get; set; } public List<ContactInfo> Contacts { get { if (contacts == null) contacts = new List<ContactInfo>(); return contacts; } set { contacts = value; } } private List<ContactInfo> contacts; } // The class in which the settings are manipulated public static class Settings { public static string SettingPath; private static MyAppSettings instance; public static MyAppSettings Instance { get { if (instance == null) instance = new MyAppSettings(); return instance; } set { instance = value; } } public static void InitializeSettings(string path) { SettingPath = Path.GetFullPath(path + "\\MyApp.xml"); if (File.Exists(SettingPath)) { LoadSettings(); } else { Instance.FirstLoad = true; Instance.VehicleFolderName = "Cars"; Instance.ContactFolderName = "Contacts"; SaveSettingsFile(); } } // load the settings from the xml file private static void LoadSettings() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextReader reader = new StreamReader(SettingPath); Instance = (MyAppSettings)ser.Deserialize(reader); reader.Close(); } // Save the settings to the xml file public static void SaveSettingsFile() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextWriter writer = new StreamWriter(SettingPath); ser.Serialize(writer, Settings.Instance); writer.Close(); } public static bool ValidateSettings(string initialFolder) { try { Settings.InitializeSettings(initialFolder); } catch (Exception e) { return false; } // Do some validation logic here return true; } } // A utility class to contain each contact detail public class ContactInfo { public string ContactID; public string Name; public string PhoneNumber; public string Details; public bool Active; public int SortOrder; } }

    Read the article

  • .NET XmlSerializer fails with List<T>

    - by Redshirt
    I'm using a singleton class to save all my settings info. It's first utilized by calling Settings.ValidateSettings(@"C:\MyApp"). The problem I'm having is that 'List Contacts' is causing the xmlserializer to fail to write the settings file, or to load said settings. If I comment out the List<T> then I have no problems saving/loading the xml file. What am I doing wrong? // The actual settings to save public class MyAppSettings { public bool FirstLoad { get; set; } public string VehicleFolderName { get; set; } public string ContactFolderName { get; set; } public List<ContactInfo> Contacts { get { if (contacts == null) contacts = new List<ContactInfo>(); return contacts; } set { contacts = value; } } private List<ContactInfo> contacts; } // The class in which the settings are manipulated public static class Settings { public static string SettingPath; private static MyAppSettings instance; public static MyAppSettings Instance { get { if (instance == null) instance = new MyAppSettings(); return instance; } set { instance = value; } } public static void InitializeSettings(string path) { SettingPath = Path.GetFullPath(path + "\\MyApp.xml"); if (File.Exists(SettingPath)) { LoadSettings(); } else { Instance.FirstLoad = true; Instance.VehicleFolderName = "Cars"; Instance.ContactFolderName = "Contacts"; SaveSettingsFile(); } } // load the settings from the xml file private static void LoadSettings() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextReader reader = new StreamReader(SettingPath); Instance = (MyAppSettings)ser.Deserialize(reader); reader.Close(); } // Save the settings to the xml file public static void SaveSettingsFile() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextWriter writer = new StreamWriter(SettingPath); ser.Serialize(writer, Settings.Instance); writer.Close(); } public static bool ValidateSettings(string initialFolder) { try { Settings.InitializeSettings(initialFolder); } catch (Exception e) { return false; } // Do some validation logic here return true; } } // A utility class to contain each contact detail public class ContactInfo { public string ContactID; public string Name; public string PhoneNumber; public string Details; public bool Active; public int SortOrder; }

    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

  • XmlSerializer construction with same named extra types

    - by NoizWaves
    Hey, I am hitting trouble constructing an XmlSerializer where the extra types contains types with the same Name (but unique Fullname). Below is an example that illustrated my scenario. Type definitions in external assembly I cannot manipulate: public static class Wheel { public enum Status { Stopped, Spinning } } public static class Engine { public enum Status { Idle, Full } } Class I have written and have control over: public class Car { public Wheel.Status WheelStatus; public Engine.Status EngineStatus; public static string Serialize(Car car) { var xs = new XmlSerializer(typeof(Car), new[] {typeof(Wheel.Status),typeof(Engine.Status)}); var output = new StringBuilder(); using (var sw = new StringWriter(output)) xs.Serialize(sw, car); return output.ToString(); } } The XmlSerializer constructor throws a System.InvalidOperationException with Message "There was an error reflecting type 'Engine.Status'" This exception has an InnerException of type System.InvalidOperationException and with Message "Types 'Wheel.Status' and 'Engine.Status' both use the XML type name, 'Status', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type." Given that I am unable to alter the enum types, how can I construct an XmlSerializer that will serialize Car successfully?

    Read the article

  • XmlSerializer - There was an error reflecting type

    - by oo
    Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor: XmlSerializer serializer = new XmlSerializer(typeof(DataClass)); I am getting an exception saying: There was an error reflecting type. Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute or by having it on the top object does it recursively apply it to all objects inside? Any thoughts?

    Read the article

  • XmlSerializer throws exception when serializing dynamically loaded type

    - by Dr. Sbaitso
    Hi I'm trying to use the System.Xml.Serialization.XmlSerializer to serialize a dynamically loaded (and compiled class). If I build the class in question into the main assembly, everything works as expected. But if I compile and load the class from an dynamically loaded assembly, the XmlSerializer throws an exception. What am I doing wrong? I've created the following .NET 3.5 C# application to reproduce the issue: using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; public class StaticallyBuiltClass { public class Item { public string Name { get; set; } public int Value { get; set; } } private List<Item> values = new List<Item>(); public List<Item> Values { get { return values; } set { values = value; } } } static class Program { static void Main() { RunStaticTest(); RunDynamicTest(); } static void RunStaticTest() { Console.WriteLine("-------------------------------------"); Console.WriteLine(" Serializing StaticallyBuiltClass..."); Console.WriteLine("-------------------------------------"); var stat = new StaticallyBuiltClass(); Serialize(stat.GetType(), stat); Console.WriteLine(); } static void RunDynamicTest() { Console.WriteLine("-------------------------------------"); Console.WriteLine(" Serializing DynamicallyBuiltClass..."); Console.WriteLine("-------------------------------------"); CSharpCodeProvider csProvider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } }); CompilerParameters csParams = new System.CodeDom.Compiler.CompilerParameters(); csParams.GenerateInMemory = true; csParams.GenerateExecutable = false; csParams.ReferencedAssemblies.Add("System.dll"); csParams.CompilerOptions = "/target:library"; StringBuilder classDef = new StringBuilder(); classDef.AppendLine("using System;"); classDef.AppendLine("using System.Collections.Generic;"); classDef.AppendLine(""); classDef.AppendLine("public class DynamicallyBuiltClass"); classDef.AppendLine("{"); classDef.AppendLine(" public class Item"); classDef.AppendLine(" {"); classDef.AppendLine(" public string Name { get; set; }"); classDef.AppendLine(" public int Value { get; set; }"); classDef.AppendLine(" }"); classDef.AppendLine(" private List<Item> values = new List<Item>();"); classDef.AppendLine(" public List<Item> Values { get { return values; } set { values = value; } }"); classDef.AppendLine("}"); CompilerResults res = csProvider.CompileAssemblyFromSource(csParams, new string[] { classDef.ToString() }); foreach (var line in res.Output) { Console.WriteLine(line); } Assembly asm = res.CompiledAssembly; if (asm != null) { Type t = asm.GetType("DynamicallyBuiltClass"); object o = t.InvokeMember("", BindingFlags.CreateInstance, null, null, null); Serialize(t, o); } Console.WriteLine(); } static void Serialize(Type type, object o) { var serializer = new XmlSerializer(type); try { serializer.Serialize(Console.Out, o); } catch(Exception ex) { Console.WriteLine("Exception caught while serializing " + type.ToString()); Exception e = ex; while (e != null) { Console.WriteLine(e.Message); e = e.InnerException; Console.Write("Inner: "); } Console.WriteLine("null"); Console.WriteLine(); Console.WriteLine("Stack trace:"); Console.WriteLine(ex.StackTrace); } } } which generates the following output: ------------------------------------- Serializing StaticallyBuiltClass... ------------------------------------- <?xml version="1.0" encoding="IBM437"?> <StaticallyBuiltClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Values /> </StaticallyBuiltClass> ------------------------------------- Serializing DynamicallyBuiltClass... ------------------------------------- Exception caught while serializing DynamicallyBuiltClass There was an error generating the XML document. Inner: The type initializer for 'Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterDynamicallyBuiltClass' threw an exception. Inner: Object reference not set to an instance of an object. Inner: null Stack trace: at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o) at Program.Serialize(Type type, Object o) in c:\dev\SerTest\SerTest\Program.cs:line 100 Edit: Removed some extraneous referenced assemblies

    Read the article

  • Combining XmlSerializer and XmlWriter?

    - by num3ric
    In addition to a list of objects I am serializing to an xml file using C#'s XmlSerializer, I would like to store a few more independent elements (mainly strings from textboxes) in the same xml. public static void SaveBehaviors(ObservableCollection<Param> listParams) { XmlSerializer _paramsSerializer = new XmlSerializer(listParams.GetType()); string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); path += "\\test.xml"; using (TextWriter writeFileStream = new StreamWriter(path)) { _paramsSerializer.Serialize(writeFileStream, listParams); using (XmlWriter writer = XmlWriter.Create(writeFileStream)) { writer.WriteStartElement("Foo"); //test entry... writer.WriteAttributeString("Bar", "Some & value"); writer.WriteElementString("Nested", "data"); writer.WriteEndElement(); } } } However, deserializing "test.xml" results in an error because of the added element. I suppose writing in the serialized xml file is prohibited and should be avoided?

    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

  • Using .NET XmlSerializer with get properties and setter functions

    - by brone
    I'm trying to use XmlSerializer from C# to save out a class that has some values that are read by properties (the code being just a simple retrieval of field value) but set by setter functions (since there is a delegate called if the value changes). What I'm currently doing is this sort of thing. The intended use is to use the InT property to read the value, and use SetInT to set it. Setting it has side-effects, so a method is more appropriate than a property here. XmlSerializationOnly_InT exists solely for the benefit of the XmlSerializer (hence the name), and shouldn't be used by normal code. class X { public double InT { get { return _inT; } } public void SetInT(double newInT) { if (newInT != _inT) { _inT = newInT; Changed();//includes delegate call; potentially expensive } } private double _inT; // not called by normal code, as the property set is not just a simple // field set or two. [XmlElement(ElementName = "InT")] public double XmlSerializationOnly_InT { get { return InT; } set { SetInT(value); } } } This works, it's easy enough to do, and the XML file looks like you'd expect. It's manual labour though, and a bit ugly, so I'm only somewhat satisfied. What I'd really like is to be able to tell the XML serialization to read the value using the property, and set it using the setter function. Then I wouldn't need XmlSerializationOnly_InT at all. I seem to be following standard practise by distinguishing between property sets and setter functions in this way, so I'm sure I'm not the only person to have encountered this (though google suggests I might be). What have others done in this situation? Is there some easy way to persuade the XmlSerializer to handle this sort of thing better? If not, is there perhaps some other easy way to do it?

    Read the article

  • MyMessage<T> throws an exception when calling XmlSerializer

    - by Arthis
    I am very new to nservicebus. I am using version 3.0.1, the last one up to date. And I wonder if my case is a normal limitation of NSB, I am not aware of. I have an asp.net MVC application, I am trying to setup and in my global.asax, I have the following : var configure = Configure.WithWeb() .DefaultBuilder() .ForMvc() .XmlSerializer(); But I have an error with the XmlSerializer when dealing with one of my object: [Serializable] public class MyMessage<T> : IMessage { public T myobject { get; set; } } I pass trough : XmlSerializer() instance.Initialize(types); this.InitType(type, moduleBuilder); this.InitType(info2.PropertyType, moduleBuilder); and then when dealing With T, string typeName = GetTypeName(t); typename is null and the following instruction : if (!nameToType.ContainsKey(typeName)) ends in error. null value not allowed. Is this some limitations to Nservicebus, or am I messing something up?

    Read the article

  • XmlSerializer Performance Issue when Specifying XmlRootAttribute

    - by Dougc
    I'm currently having a really weird issue and I can't seem to figure out how to resolve it. I've got a fairly complex type which I'm trying to serialize using the XmlSerializer class. This actually functions fine and the type serializes properly, but seems to take a very long time in doing so; around 5 seconds depending on the data in the object. After a bit of profiling I've narrowed the issue down - bizarrely - to specifying an XmlRootAttribute when calling XmlSerializer.Serialize. I do this to change the name of a collection being serialized from ArrayOf to something a bit more meaningful. Once I remove the parameter the operation is almost instant! Any thoughts or suggestions would be excellent as I'm entirely stumped on this one!

    Read the article

  • xmlserializer throwing InvalidOperationException

    - by AndyC
    I have an XmlSerializer object, and I have added 2 event handlers to the UnknownElement and UnknownAttribute events, as below: XmlSerializer xs = new XmlSerialiser(typeof(MyClass)); xs.UnknownAttribute += new XmlAttributeEventHandler(xs_UnknownAttribute); xs.UnknownElement += new XmlElementEventHandler(xs_UnknownAttribute); Each of these event handlers basically do the same thing, they print out the node name or the attribute name causing the issue. But for some reason, an InvalidOperationException is getting thrown saying there is an error in the xml document with . I thought these errors would be caught by my events?

    Read the article

  • How does DataContractSerializer write to private fields?

    - by Eric
    I understand how XMLSerializer could work by using reflection to figure out what public read/write fields or properties it should be using to serialize or de-serialize XML. Yet XMLSerializer requires that the fields be public and read/write. However, DataContractSerializer is able to read or write to or from completely private fields in a class. So I'm wondering how this is even possible with out explicitly giving DataContractSerializer additional access rights to my class(es).

    Read the article

  • XmlSerializer 'forgetting' my namespace

    - by Michel
    Hi, i have to create an XML file with all the elements prefixed, like this: <ps:Request num="123" xmlns:ps="www.ladieda.com"> <ps:ClientId>5566</ps:ClientId> <ps:Request> When i serialize my object, c# is smart and does this: <Request num="123" xmlns="www.ladieda.com"> <ClientId>5566</ClientId> <Request> That is good, because the ps: is not necessary. But is there a way to force C# to serialize all the prefixes? My serialize code is this (for incoming object pObject): String XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(pObject.GetType()); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return XmlizedString; private String UTF8ByteArrayToString(Byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); String constructedString = encoding.GetString(characters); return (constructedString); }

    Read the article

  • JavaScript: Replacement for XMLSerializer.seralizeToString()?

    - by NRaf
    I'm developing a website using the Seam framework and the RichFaces AJAX library (these isn't really all that important to the problem at hand - just some background). I seem to have uncovered a bug, however, in RichFaces which, in certain instances, will cause AJAX-based updating to fail in IE8 (see here for more info: http://community.jboss.org/message/585737). The following is the code where the exception is occurring: var anchor = oldnode.parentNode; if(!window.opera && !A4J.AJAX.isWebkitBreakingAmps() && oldnode.outerHTML && !oldnode.tagName.match( /(tbody|thead|tfoot|tr|th|td)/i ) ){ LOG.debug("Replace content of node by outerHTML()"); if (!Sarissa._SARISSA_IS_IE || oldnode.tagName.toLowerCase()!="table") { try { oldnode.innerHTML = ""; } catch(e){ LOG.error("Error to clear node content by innerHTML "+e.message); Sarissa.clearChildNodes(oldnode); } } oldnode.outerHTML = new XMLSerializer().serializeToString(newnode); } The last line (the one with XMLSerializer) is where the exception is occurring in IE. I was wondering if anyone knows of any replacement method / library / etc I could use there (only on IE is fine). Thanks.

    Read the article

  • Sorting the output from XmlSerializer in C#

    - by prosseek
    In this post, I could get an XML file generated based on C# class. Can I reorder the XML elements based on its element? My code uses var ser = new XmlSerializer(typeof(Module)); ser.Serialize(WriteFileStream, report, ns); WriteFileStream.Close(); to get the XML file, but I need to have the XML file sorted based on a BlocksCovered variable. public class ClassInfo { public string ClassName; public int BlocksCovered; public int BlocksNotCovered; public double CoverageRate; public ClassInfo() {} public ClassInfo(string ClassName, int BlocksCovered, int BlocksNotCovered, double CoverageRate) { this.ClassName = ClassName; this.BlocksCovered = BlocksCovered; this.BlocksNotCovered = BlocksNotCovered; this.CoverageRate = CoverageRate; } } [XmlRoot("Module")] public class Module { [XmlElement("Class")] public List<ClassInfo> ClassInfoList; public int BlocksCovered; public int BlocksNotCovered; public string moduleName; public Module() { ClassInfoList = new List<ClassInfo>(); BlocksCovered = 0; BlocksNotCovered = 0; moduleName = ""; } } Module report = new Module(); ... TextWriter WriteFileStream = new StreamWriter(xmlFileName); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); var ser = new XmlSerializer(typeof(Module)); ser.Serialize(WriteFileStream, report, ns); WriteFileStream.Close();

    Read the article

  • how to: re-assemble machine generated classes from xsd files to their original nested state.

    - by Paul Connolly
    Hi everyone, I'm working in Visual Studio 2008 using c#. Let's say I have 2 xsd files e.g "Envelope.xsd" and "Body.xsd" I create 2 sets of classes by running xsd.exe, creating something like "Envelope.cs" and "Body.cs", so far so good. I can't figure out how to link the two classes to serialize (using XmlSerializer) into the proper nested xml, i.e: I want: <Envelope><DocumentTitle>Title</DocumentTitle><Body>Body Info</Body></Envelope> But I get: <Envelope><DocumentTitle>Title</DocumentTitle></Envelope><Body>Body Info</Body> Could someone perhaps show me how the two .cs classes should look to enable XmlSerializer to runt the desired nested result? Thanks a million Paul

    Read the article

  • XmlSerializer giving FileNotFoundException at constructor

    - by Irwin
    An application I've been working with is failing when i try to serialize types. A statement like this: XmlSerialzer lizer = new XmlSerializer(typeof(MyType)); Produces: System.IO.FileNotFoundException occurred Message="Could not load file or assembly '[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified." Source="mscorlib" FileName="[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" FusionLog="" StackTrace: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) I don't define any special serializers for my class.

    Read the article

  • XmlSerializer and Mark-up (Xml or Html)

    - by Kieron
    Hi, I've a requirement to serialize any class provided (decorated with the appropriate XmlElement/ XmlAttribute etc), but some of the properties may contain some sort of mark-up...usually HTML, but it could as easily be XML in the future. When trying to serialize the class the XmlSerializer crashes. I'd hope to be able to apply no more than an attribute to the property (currently set to XmlText) in the hope that it would wrap the content in CDATA[...], but that doesn't seem to work. I've seen several 'workarounds' like the one here, but I'd hoped for something a little less impactful for the developing consumer. Does anyone know of any 'nicer' less invasive solution...? Thanks, Kieron

    Read the article

  • svcutil, XmlSerializer and xsd:list

    - by Dmitry Ornatsky
    I'm using svcutil to generate classes from service metadata. This XML schema <xsd:complexType name="FindRequest"> ... <xsd:attribute name="Significance" type="Significance" use="optional" /> </xsd:complexType> <xsd:simpleType name="Significance"> <xsd:list> <xsd:simpleType> <xsd:restriction base="xsd:int"> <xsd:enumeration value="1" /> <xsd:enumeration value="2" /> <xsd:enumeration value="3" /> </xsd:restriction> </xsd:simpleType> </xsd:list> produces following code: public partial class FindRequest { ... private int significanceField; private bool significanceFieldSpecified; [System.Xml.Serialization.XmlAttributeAttribute()] public int Significance { get { return this.significanceField; } set { this.significanceField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool SignificanceSpecified { get { return this.significanceFieldSpecified; } set { this.significanceFieldSpecified = value; } } } My questions are: Is it possible to make XmlSerializer understand this type of list: <FindRequest Significance="1 2 3"/> For example by using some kind of a flags-style enum: public enum EmployeeStatus { [XmlEnum(Name = "1")] One = 1, [XmlEnum(Name = "2")] Two = 2, [XmlEnum(Name = "3")] Three = 4 } If the answer is yes, Is it possible to make svcutil/xsd.exe generate classes that are serialized that way without changing the schema?

    Read the article

  • XmlSerializer.Deserialize blocks over NetworkStream

    - by Luca
    I'm trying to sends XML serializable objects over a network stream. I've already used this on an UDP broadcast server, where it receive UDP messages from the local network. Here a snippet of the server side: while (mServiceStopFlag == false) { if (mSocket.Available > 0) { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, DiscoveryPort); byte[] bData; // Receive discovery message bData = mSocket.Receive(ref ipEndPoint); // Handle discovery message HandleDiscoveryMessage(ipEndPoint.Address, bData); ... Instead this is the client side: IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, DiscoveryPort); MemoryStream mStream = new MemoryStream(); byte[] bData; // Create broadcast UDP server mSocket = new UdpClient(); mSocket.EnableBroadcast = true; // Create datagram data foreach (NetService s in ctx.Services) XmlHelper.SerializeClass<NetService>(mStream, s); bData = mStream.GetBuffer(); // Notify the services while (mServiceStopFlag == false) { mSocket.Send(bData, (int)mStream.Length, ipEndPoint); Thread.Sleep(DefaultServiceLatency); } It works very fine. But now i'me trying to get the same result, but on a TcpClient socket, but the using directly an XMLSerializer instance: On server side: TcpClient sSocket = k.Key; ServiceContext sContext = k.Value; Message msg = new Message(); while (sSocket.Connected == true) { if (sSocket.Available > 0) { StreamReader tr = new StreamReader(sSocket.GetStream()); msg = (Message)mXmlSerialize.Deserialize(tr); // Handle message msg = sContext.Handler(msg); // Reply with another message if (msg != null) mXmlSerialize.Serialize(sSocket.GetStream(), msg); } else Thread.Sleep(40); } And on client side: NetworkStream mSocketStream; Message rMessage; // Network stream mSocketStream = mSocket.GetStream(); // Send the message mXmlSerialize.Serialize(mSocketStream, msg); // Receive the answer rMessage = (Message)mXmlSerialize.Deserialize(mSocketStream); return (rMessage); The data is sent (Available property is greater then 0), but the method XmlSerialize.Deserialize (which should deserialize the Message class) blocks. What am I missing?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >