The following is in C#.  I'm trying to do something very simple (I think). I have a method that loads an XML document  XDocument  doc = XDocument.Load(uri);   , but I don't want to tie up pc resources if there are issues (connectivity, document size, etc.).  So I'd like to be able to add a timeout variable that will cut the method off after a given number of seconds. I'm a newbie when it comes to asynchronous programming and find it confusing that there are so many examples written so many different ways . . . and none of them appear simple. I'd like a simple solution, if possible.  Here's my thoughts so far on possible solution paths:  1) A method that wraps the existing load  public XDocument LoadXDocument(string uri, int timeout){ //code }   2) A wrapper, but as an extension method  XDocument doc = XDocument.LoadWithTimeout(string uri, int timeout);   3) A generic extension method.  Object obj = SomeStaticClass.LoadWithTimeout(??? method, int timeout);   3), on its face seems really nice, because it would mean being able to generically add timeouts to many different method calls and not specifically tied to one type of object, but I suspect that it is either i)impossible or ii) very difficult.  Please assist. Thanks.
44387
I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.  TemperamentalClass tc = new TemperamentalClass(); tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min   I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).  In addition, I would like to have the offending "timed out" code stopped from executing further if possible.
120145
I am currently trying to write a Dynamics CRM 2011 plugin that creates a new SharePoint 2010 site (within an existing site collection) for every account that is created. I have the code for creating a library, which uses the following methods:          private static ClientContext CreateSharePointConnection()         {             try             {                 Uri spSiteUrl = new Uri(Constants.SharePointSiteName);                 using (ClientContext spcontext = new ClientContext(spSiteUrl))                 {                     spcontext.Credentials                         = new System.Net.NetworkCredential(Constants.UserName                             , Constants.Password, Constants.DomainName);                     return spcontext;                 }             }             catch (Exception ex)             {                 throw new Exception("SharePointMethods.CreateSharePointConnection (General Exception: "                     + ex.Message + ")");             }         }  private static void CreateDocumentLibrary(ClientContext _clientContext             , string _documentLibraryName, string _documentLibraryDescription)         {             try             {                 Web web = _clientContext.Web;                 _clientContext.Load(web);                 _clientContext.ExecuteQuery();                 ListCreationInformation lci = new ListCreationInformation();                 lci.Title = _documentLibraryName;                 lci.Description = _documentLibraryDescription;                 lci.TemplateType = 101;                 List newDocumentLibrary = web.Lists.Add(lci);                 newDocumentLibrary.ContentTypesEnabled = true;                 newDocumentLibrary.Update();                 _clientContext.ExecuteQuery();             }             catch (Exception ex)             {                 throw new Exception("SharePointMethods.CreateDocumentLibrary('" + _documentLibraryName                     + "') (General Exception: " + ex.Message + ")");             }         }   So I would like to write a method CreateSite instead of CreateDocumentLibrary. However, all examples I can find on the web for programmatically creating a Site are using SPSite, SPWeb, etc. Something like this:  private static void CreateSite(string _siteName, string _siteDescription) {     try     {         SPSite site = new SPSite(Constants.SharePointSiteName);         SPWeb web = site.OpenWeb();         SPWebCollection wc = web.Webs;         string siteTemplate = web.WebTemplate;         wc.Add(Constants.SharePointSiteName, _siteName, _siteDescription, 1043, siteTemplate, true, false);     }     catch (Exception ex)     {         throw new Exception("SharePointMethods.CreateSite('" + _siteName             + "') (General Exception: " + ex.Message + ")");     } }   However this is NOT a solution for my problem, because the SPSite, SPWeb, etc. only work on the local machine and I want to create a Site from a remote (in my case CRM) server. Anyone got an idea how to solve this.  PS: Code might still contain memory leaks, so please be carful when you use it for production purposes!
22560
I'm writing code to do Xml serialization. With below function.  public static string SerializeToXml(object obj) {     XmlSerializer serializer = new XmlSerializer(obj.GetType());     using (StringWriter writer = new StringWriter())     {         serializer.Serialize(writer, obj);         return writer.ToString();     } }   If the argument is a instance of class without parameterless constructor, it will throw a exception.     Unhandled Exception:   System.InvalidOperationException:   CSharpConsole.Foo cannot be serialized   because it does not have a   parameterless constructor.    at   System.Xml.Serialization.TypeDesc.CheckSupported()   at   System.Xml.Serialization.TypeScope.GetTypeDesc(Type   type, MemberInfo sourc e, Boolean   directReference, Boolean throwOnError)   at   System.Xml.Serialization.ModelScope.GetTypeModel(Type   type, Boolean direct Reference)    at   System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type   type , XmlRootAttribute root, String   defaultNamespace)    at   System.Xml.Serialization.XmlSerializer..ctor(Type   type, String defaultName space)    at   System.Xml.Serialization.XmlSerializer..ctor(Type   type)   Why must there be a parameterless constructor in order to allow xml serialization to succeed?  EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.
8886
I've seen this done in Borland's  environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?
3258
Given a method DoSomething that takes a (parameterless) function and handles it in some way. Is there a better way to create the "overloads" for functions with parameters than the snippet below?  public static TResult DoSomething&lt;TResult&gt;(Func&lt;TResult&gt; func) {     //call func() and do something else }  public static TResult DoSomething&lt;T0, TResult&gt;(     Func&lt;T0, TResult&gt; func,     T0 arg0) {     return DoSomething(() =&gt; func(arg0)); }  public static TResult DoSomething&lt;T0, T1, TResult&gt;(     Func&lt;T0, T1, TResult&gt; func,     T0 arg0, T1 arg1) {     return DoSomething(arg =&gt; func(arg, arg1), arg0); }  public static TResult DoSomething&lt;T0, T1, T2, TResult&gt;(     Func&lt;T0, T1, T2, TResult&gt; func,     T0 arg0, T1 arg1, T2 arg2) {     return DoSomething(arg =&gt; func(arg, arg1, arg2), arg0); }
103765
I have a content management application in the root of my website, and I'm trying to use a different app (a billing application) under a sub-folder. Unfortunately, the web.config of the root site is interfering with the sub-app.  Is there a way to just disable web.config inheritance for a sub-folder?  Update: As linked by , using the &lt;location&gt; tag can prevent inheritance for part of the web config, as follows:  &lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;configSections&gt;     .... &lt;/configSections&gt; &lt;location path="." inheritInChildApplications="false"&gt;     &lt;appSettings&gt;         ....     &lt;/appSettings&gt;     &lt;connectionStrings/&gt;     &lt;system.web&gt;         ....     &lt;/system.web&gt;     &lt;system.codedom&gt;         ....     &lt;/system.codedom&gt;     &lt;system.webServer&gt;         ....     &lt;/system.webServer&gt; &lt;/location&gt; &lt;runtime&gt;     .... &lt;/runtime&gt; &lt;/configuration&gt;   The &lt;configSections&gt; and &lt;runtime&gt; sections will not accept being enclosed in the  tag...so I guess this only does most of the job. Anybody know how to do it better?
118537
In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.  I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.
35156
I have an XDocument object. I want to query for elements with a particular name at any depth using LINQ. When I use Descendants(&quot;element_name&quot;), I only get elements that are direct children of the current level. I'm looking for the equivalent of &quot;//element_name&quot; in XPath...should I just use XPath, or is there a way to do it using LINQ methods?
15838
Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:  class GenericClass&lt;T&gt;  {     public event EventHandler&lt;EventData&gt; MyEvent;     public class EventData : EventArgs { /* snip */ }     // ... snip }   Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:  GenericClass&lt;int&gt; gcInt = new GenericClass&lt;int&gt;; gcInt.MyEvent += new EventHandler&lt;GenericClass&lt;int&gt;.EventData&gt;(gcInt_MyEvent); // ...  private void gcInt_MyEvent(object sender, GenericClass&lt;int&gt;.EventData e) {     throw new NotImplementedException(); }   Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...  Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.
41562
I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection.  I tried two methods but both of these methods are going through boxing and unboxing to get the value.  Does anyone know a way to avoid the boxing?  If you saw this in production would you not like it, how bad is it for performance?  Usuage:  var id = Request.QueryString.Parse&lt;int&gt;("id");   Attempt #1:  public static T Parse&lt;T&gt;(this NameValueCollection col, string key) {     string value = col[key];      if (string.IsNullOrEmpty(value))         return default(T);      if (typeof(T) == typeof(int))     {         //return int.Parse(value); // cannot convert int to T         //return (T)int.Parse(value); // cannot convert int to T         return (T)(object)int.Parse(value); // works but boxes     }     if (typeof(T) == typeof(long))     {         return (T)(object)long.Parse(value); // works but boxes     }     ...      return default(T); }   Attempt #2 (using reflection):  public static T Parse&lt;T&gt;(this NameValueCollection col, string key) {     string value = col[key];      if (string.IsNullOrEmpty(value))         return default(T);      try     {         var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });          if (parseMethod == null)             return default(T);          // still boxing because invoke returns an object         var parsedVal = parseMethod.Invoke(null, new object[] { value });         return (T)parsedVal;     }     // No Proper Parse Method found     catch(AmbiguousMatchException)      {     }      return default(T); }
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?
25655
Do out parameters in C# have any performance implications I should know about? (Like exceptions)  I mean, is it a good idea to have a method with an out parameter in a loop that will run a couple of million times a second?  I know it's ugly but I am using it the same way as Int32.TryParse is using them - returning a bool to tell if some validation was successful and having an out parameter containing some additional data if it was successful.
111415
I have a Generic class like that :  public class Repository&lt;T&gt; {...}   And I need to instance that with a string ... Example :  string _sample = "TypeRepository"; var _rep = new Repository&lt;sample&gt;();   How can I do that? Is that even possible?  Thanks!
117326
I have created multiple ESRI addins, where the same code is used. I have created a class library, which I can reference rather than duplicating code. I have the following in my ESRI addin code which works fine  IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;   However if the same code is used in the class library, I am unable to build the dll. As the  class library does not know about ArcMap,   I have tried   ESRI.ArcGIS.ArcMap.Application arcmapApp = new ESRI.ArcGIS.ArcMap.Application(); IMxDocument mxdoc = arcmapApp.Document as IMxDocument;   However when I run the code in my addin (that references my Class Library), i get the following error    What is the correct way of referencing ArcMap in a class library?
43302
I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)  Solution Thanks to , I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.)  public static org.w3c.dom.Document loadXMLFrom(String xml)     throws org.xml.sax.SAXException, java.io.IOException {     return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }  public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)      throws org.xml.sax.SAXException, java.io.IOException {     javax.xml.parsers.DocumentBuilderFactory factory =         javax.xml.parsers.DocumentBuilderFactory.newInstance();     factory.setNamespaceAware(true);     javax.xml.parsers.DocumentBuilder builder = null;     try {         builder = factory.newDocumentBuilder();     }     catch (javax.xml.parsers.ParserConfigurationException ex) {     }       org.w3c.dom.Document doc = builder.parse(is);     is.close();     return doc; }
3278
So, I understand that the following doesn't work, but why doesn't it work?  interface Adapter&lt;E&gt; {}  class Adaptulator&lt;I&gt; {     &lt;E, A extends I &amp; Adapter&lt;E&gt;&gt; void add(Class&lt;E&gt; extl, Class&lt;A&gt; intl) {         addAdapterFactory(new AdapterFactory&lt;E, A&gt;(extl, intl));     } }   The add() method gives me a compile error, "Cannot specify any additional bound Adapter&lt;E&gt; when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.  Clearly you're just Not Allowed to use the type parameter I there, before the &amp;, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that I isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.  Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one add() method, so it's not like there's any ambiguity...  Can someone demonstrate the problem for me?
16158
Consider this example (typical in OOP books):    I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.  Here's the Animal class:  public class Animal {     private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;();      public void addFriend(String name, Animal animal){         friends.put(name,animal);     }      public Animal callFriend(String name){         return friends.get(name);     } }   And here's some code snippet with lots of typecasting:  Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck());  ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();   Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say      jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack();   Here's some initial code with return type conveyed to the method as a parameter that's never used.   public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){     return (T)friends.get(name);         }   Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this?