I'm trying to serialize an object with an attribute on the root element (which is a collection).  [XmlType("Person")] public class Person {     public id Id { get; set; }     public string Name { get; set; } }  [XmlType("Persons")] public class Persons : Collection&lt;Person&gt; {     [XmlAttribute("Nb")]     public int Nb         get {             return this.Count;         }         set { }     } }  var persons = new Persons(); var person = new Person(); person.Id = 42; person.Name = "Toto"; persons.Add(person);  return persons;   The serialized output is the following:  &lt;Persons&gt;     &lt;Person&gt;         &lt;Id&gt;42&lt;/Id&gt;         &lt;Name&gt;Toto&lt;/Name&gt;     &lt;/Person&gt; &lt;/Persons&gt;   I'm expecting  &lt;Persons Nb="1"&gt;     &lt;Person&gt;         &lt;Id&gt;42&lt;/Id&gt;         &lt;Name&gt;Toto&lt;/Name&gt;     &lt;/Person&gt; &lt;/Persons&gt;   How can I bring the Nb attribute in ?
123254
I've got a simple class that inherits from Collection and adds a couple of properties. I need to serialize this class to XML, but the XMLSerializer ignores my additional properties.  I assume this is because of the special treatment that XMLSerializer gives ICollection and IEnumerable objects. What's the best way around this?  Here's some sample code:  using System.Collections.ObjectModel; using System.IO; using System.Xml.Serialization;  namespace SerialiseCollection {     class Program     {         static void Main(string[] args)         {             var c = new MyCollection();             c.Add("Hello");             c.Add("Goodbye");              var serializer = new XmlSerializer(typeof(MyCollection));             using (var writer = new StreamWriter("test.xml"))                 serializer.Serialize(writer, c);         }     }      [XmlRoot("MyCollection")]     public class MyCollection : Collection&lt;string&gt;     {         [XmlAttribute()]         public string MyAttribute { get; set; }          public MyCollection()         {             this.MyAttribute = "SerializeThis";         }     } }   This outputs the following XML (note MyAttribute is missing in the MyCollection element):  &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;     &lt;string&gt;Hello&lt;/string&gt;     &lt;string&gt;Goodbye&lt;/string&gt; &lt;/MyCollection&gt;   What I want is  &lt;MyCollection MyAttribute="SerializeThis"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;     &lt;string&gt;Hello&lt;/string&gt;     &lt;string&gt;Goodbye&lt;/string&gt; &lt;/MyCollection&gt;   Any ideas? The simpler the better. Thanks.
45757
I have a Category entity which has a Nullable ParentId field. When the method below is executing and the categoryId is null, the result seems null however there are categories which has null ParentId value.  What is the problem in here, what am I missing?  public IEnumerable&lt;ICategory&gt; GetSubCategories(long? categoryId) {     var subCategories = this.Repository.Categories.Where(c =&gt; c.ParentId == categoryId)         .ToList().Cast&lt;ICategory&gt;();      return subCategories; }   By the way, when I change the condition to (c.ParentId == null),  result seems normal.
18961
I have the following code:   DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);   How can I get it to parse XML contained within a String instead of a file?
71357
System.Drawing.Color objects apparently won't serialize with XmlSerializer. What is the best way to xml serialize colors?
120955
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string.  I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?  Very specifically, what would the method "SomeMethod" have to be that would produce the output below?  string unformattedXml; string formattedXml;  unformattedXml = "&lt;?xml version=\"1.0\"?&gt;&lt;book&gt;&lt;author&gt;Lewis, C.S.&lt;/author&gt;&lt;title&gt;The Four Loves&lt;/title&gt;&lt;/book&gt;" formattedXml = SomeMethod(unformattedXml);  Console.WriteLine(formattedXml);   Output:  &lt;?xml version="1.0"?&gt;   &lt;book id="123"&gt;     &lt;author&gt;Lewis, C.S.&lt;/author&gt;     &lt;title&gt;The Four Loves&lt;/title&gt;   &lt;/book&gt;
27319
I want to use a collection initializer for the next bit of code:  public Dictionary&lt;int, string&gt; GetNames() {     Dictionary&lt;int, string&gt; names = new Dictionary&lt;int, string&gt;();     names.Add(1, "Adam");     names.Add(2, "Bart");     names.Add(3, "Charlie");     return names; }   So typically it should be something like:  return new Dictionary&lt;int, string&gt; {     1, "Adam",    2, "Bart"    ...   But what is the correct syntax for this?
71398
I am using XmlSerializer to write and read an object to xml in C#.  I currently use the attributes XmlElement and XmlIgnore to manipulate the serialization of the object.  If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine.   How do I indicate (preferably via Attributes) that a certain field is "required"?  Here is a sample method of what I am using currently:  [XmlElement(ElementName="numberOfWidgets")] public int NumberThatIsRequired {     set ...;     get ...; }   My ideal solution would be to add something like an XmlRequired attribute.     Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?
29175
What are attributes in .NET, what are they good for, and how do I create my own attributes?
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
9161
I'm having difficulty searching for this. How would I define an element in an XML schema file for XML that looks like this:  &lt;option value="test"&gt;sometext&lt;/option&gt;   I can't figure out how to define an element that is of type xs:string and also has an attribute.   Here's what I've got so far:  &lt;xs:element name="option"&gt;     &lt;xs:complexType&gt;         &lt;xs:attribute name="value" type="xs:string" /&gt;     &lt;/xs:complexType&gt; &lt;/xs:element&gt;
112233
To communicate with a REST interface on a private system, I need to send a JSON message from a trigger. I have a message object that has some fields, lists and a child object:  public class MerchantConfig {  public class MIDConfig {     public String mid;     public String currencyCode;     public String cardTemplateName;     public String paymentPanelRestriction;     public List&lt;String&gt; restrictedCountries;      public String paymentPanelRestrictionForCountries; }  public String merchantName; public String sopgTemplateName; public Integer dispositionTimeWindowInMinutes; public List&lt;String&gt; features; public Boolean activateImmediately; public List&lt;MIDConfig&gt; midConfiguration; }   I can serialize it to JSON using the built-in serializer:  String body = JSON.serializePretty([MerchantConfig instance]);   The result:  {   "sopgTemplateName" : null,   "midConfiguration" : [ {     "restrictionCountries" : [ "DE", "AT" ],     "paymentPanelRestrictionForCountries" : "MANDATORY",     "paymentPanelRestriction" : "OPTIONAL",     "mid" : "1000000001",     "currencyCode" : "EUR",     "cardTemplateName" : null   }, {     "restrictionCountries" : [ ],     "paymentPanelRestrictionForCountries" : "",     "paymentPanelRestriction" : "OPTIONAL",     "mid" : "1000000002",     "currencyCode" : "USD",     "cardTemplateName" : null   }, {     "restrictionCountries" : [ ],     "paymentPanelRestrictionForCountries" : "",     "paymentPanelRestriction" : "PROHIBITED",     "mid" : "1000000003",     "currencyCode" : "AUD",     "cardTemplateName" : null   } ],   "merchantName" : "Test Merchant",   "features" : [ XYZ ],   "dispositionTimeWindowInMinutes" : 10,   "activateImmediately" : true }   How can I serialize this object so that all properties that are null don't show up in the JSON string?   In this example, "sopgTemplateName" and all "cardTemplateName" properties are null and should not appear in the JSON string. The empty list "restrictionCountries" should still appear as an empty list, though.
90873
I have an Enumerable&lt;T&gt; and am looking for a method that allows me to execute an action for each element, kind of like Select but then for side-effects. Something like:  string[] Names = ...; Names.each(s =&gt; Console.Writeline(s));   or   Names.each(s =&gt; GenHTMLOutput(s));    // (where GenHTMLOutput cannot for some reason receive the enumerable itself as a parameter)   I did try Select(s=&gt; { Console.WriteLine(s); return s; }), but it wasn't printing anything.
2350
i have this attribute in my component:  &lt;aura:attribute name="currentRecordDuns" type="String" /&gt;    im trying to send it to the apex controller.  this is the javascript controller:  ({ doInit : function(component, event, helper) {         helper.getAccounts(component); },})     this is the helper:  ({ getAccounts: function(component) {             var action = component.get("c.getAccounts");     action.setParams({         "currentDuns": component.get("v.currentRecordDuns"),         "freeTextFilter": component.find("freeTextFilter").get("v.value")                 });     //Set up the callback     var self = this;     action.setCallback(this, function(actionResult) {         component.set("v.Accounts", actionResult.getReturnValue());                 });             $A.enqueueAction(action);                 },})   this is the apex code:  public class AccConListController {     @AuraEnabled     public static List&lt;Account&gt; getAccounts(String currentDuns,String freeTextFilter) {         String q = 'SELECT Id, Name,DunsNumber, (select name, Phone, Email FROM Contacts where Name like \'%' + freeTextFilter +  '%\' or Phone like \'%' + freeTextFilter +  '%\' or Email like  \'%' + freeTextFilter +  '%\') FROM Account  where DunsNumber=:currentDuns';         //q+= ' and Name like \'%' + freeTextFilter +  '%\'';         List&lt;Account&gt; accounts= Database.query(q);         return accounts;     } }   i didnt get the results i wanted, so i looked at the debug log and saw:     12:13:25:003 VARIABLE_ASSIGNMENT [19]|currentDuns|null   i have no idea why, please advise  EDIT: how do i assign a value to the currentRecordDuns: in my component i call:  &lt;aura:handler name="init" value="{!this}" action="{!c.doInit}" /&gt;   this is doInit in the controller:  ({ doInit : function(component, event, helper) {         helper.getDuns(component);     helper.getLeads(component);     helper.getAccounts(component);      component.set("v.showContacts", component.find("checkboxContacts").get("v.value"));     component.set("v.showLeads", component.find("checkboxLeads").get("v.value")); },  })   the function the retrieves the currentRecordDuns:      helper.getDuns(component);   this is the function in the helper:  getDuns:  function(component) {       var action = component.get("c.getDunsByRecordId");     action.setParams({         "currentRecordID": component.get("v.recordId")             });     //Set up the callback     var self = this;     action.setCallback(this, function(actionResult) {         component.set("v.currentRecordDuns", actionResult.getReturnValue());                 });             $A.enqueueAction(action);  },   and this is the function in the apex controller:      @AuraEnabled public static string getDunsByRecordId(id currentRecordID) {      String q = 'SELECT DunsNumber FROM Account  where Id=:currentRecordID limit 1';     List&lt;Account&gt; accounts = Database.query(q);     return (!accounts.isEmpty()) ? accounts[0].DunsNumber : ''; }
11465
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.  However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:  [System.Web.Script.Services.ScriptService] public class _default : System.Web.Services.WebService {     [WebMethod]     [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]     public string[] UserDetails()     {         return new string[] { "abc", "def" };     } }
91839
I am having trouble constructing a single XPath statement to return two different sets of attributes.    For example take the following XML document:  &lt;root&gt;  &lt;line name="one" alpha="a1" beta="b1"/&gt;  &lt;line name="two" alpha="a2" beta="b2"/&gt;  &lt;line name="three" alpha="a3" beta="b3"/&gt; &lt;/root&gt;   If I use the following XPath statement:  //@alpha   It yields the following attribute set:  alpha="a1" alpha="a2" alpha="a3"   What statement do I use to yield the following attribute set:  alpha="a1" alpha="a2" alpha="a3" beta="b1" beta="b2" beta="b3"
112618
This causes a compile-time exception:  public sealed class ValidatesAttribute&lt;T&gt; : Attribute {  }  [Validates&lt;string&gt;] public static class StringValidation {  }   I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.  Does anyone know why generic types cannot derive from Attribute? Any theories?
9600
How do I Deserialize this XML document:  &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Cars&gt;   &lt;Car&gt;     &lt;StockNumber&gt;1020&lt;/StockNumber&gt;     &lt;Make&gt;Nissan&lt;/Make&gt;     &lt;Model&gt;Sentra&lt;/Model&gt;   &lt;/Car&gt;   &lt;Car&gt;     &lt;StockNumber&gt;1010&lt;/StockNumber&gt;     &lt;Make&gt;Toyota&lt;/Make&gt;     &lt;Model&gt;Corolla&lt;/Model&gt;   &lt;/Car&gt;   &lt;Car&gt;     &lt;StockNumber&gt;1111&lt;/StockNumber&gt;     &lt;Make&gt;Honda&lt;/Make&gt;     &lt;Model&gt;Accord&lt;/Model&gt;   &lt;/Car&gt; &lt;/Cars&gt;   I have this:  [Serializable()] public class Car {     [System.Xml.Serialization.XmlElementAttribute("StockNumber")]     public string StockNumber{ get; set; }      [System.Xml.Serialization.XmlElementAttribute("Make")]     public string Make{ get; set; }      [System.Xml.Serialization.XmlElementAttribute("Model")]     public string Model{ get; set; } }   .  [System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)] public class Cars {     [XmlArrayItem(typeof(Car))]     public Car[] Car { get; set; }  }   .  public class CarSerializer {     public Cars Deserialize()     {         Cars[] cars = null;         string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml";          XmlSerializer serializer = new XmlSerializer(typeof(Cars[]));          StreamReader reader = new StreamReader(path);         reader.ReadToEnd();         cars = (Cars[])serializer.Deserialize(reader);         reader.Close();          return cars;     } }   that don't seem to work :-(