Here is the Context :  I try to code a mapper for converting my DomainModel Objects to ViewModel Ojects dynamically. The problem I get, it's when I try to invoke a method of generic class by reflection I get this error :  System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.  Can someone help-me to figure out where is the fault ? It would be greatly appreciated  Here is the Code (I tried to simplified it) :  public class MapClass&lt;SourceType, DestinationType&gt; {      public string Test()     {         return test     }      public void MapClassReflection(SourceType source, ref DestinationType destination)     {         Type sourceType = source.GetType();         Type destinationType = destination.GetType();          foreach (PropertyInfo sourceProperty in sourceType.GetProperties())         {             string destinationPropertyName = LookupForPropertyInDestinationType(sourceProperty.Name, destinationType);              if (destinationPropertyName != null)             {                 PropertyInfo destinationProperty = destinationType.GetProperty(destinationPropertyName);                 if (destinationProperty.PropertyType == sourceProperty.PropertyType)                 {                     destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);                 }                 else                 {                         Type d1 = typeof(MapClass&lt;,&gt;);                         Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() };                         Type constructed = d1.MakeGenericType(typeArgs);                          object o = Activator.CreateInstance(constructed, null);                          MethodInfo theMethod = d1.GetMethod("Test");                          string toto = (string)theMethod.Invoke(o,null);                  }                 }             }         }       private string LookupForPropertyInDestinationType(string sourcePropertyName, Type destinationType)     {         foreach (PropertyInfo property in destinationType.GetProperties())         {             if (property.Name == sourcePropertyName)             {                 return sourcePropertyName;             }         }         return null;     } }
1947
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?  Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod&lt;T&gt;() using the Type stored in the myType variable?  public class Sample {     public void Example(string typeName)     {         Type myType = FindType(typeName);          // What goes here to call GenericMethod&lt;T&gt;()?         GenericMethod&lt;myType&gt;(); // This doesn't work          // What changes to call StaticMethod&lt;T&gt;()?         Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work     }      public void GenericMethod&lt;T&gt;()     {         // ...     }      public static void StaticMethod&lt;T&gt;()     {         //...     } }
33563
More specifically, when the exception contains custom objects which may or may not themselves be serializable.  Take this example:  public class MyException : Exception {     private readonly string resourceName;     private readonly IList&lt;string&gt; validationErrors;      public MyException(string resourceName, IList&lt;string&gt; validationErrors)     {         this.resourceName = resourceName;         this.validationErrors = validationErrors;     }      public string ResourceName     {         get { return this.resourceName; }     }      public IList&lt;string&gt; ValidationErrors     {         get { return this.validationErrors; }     } }   If this Exception is serialized and de-serialized, the two custom properties (ResourceName and ValidationErrors) will not be preserved. The properties will return null.  Is there a common code pattern for implementing serialization for custom exception?
23872
I have a custom type that I created, which should be persisted in a database (in this case, SQL server) as a guid (though this question is just as valid for an object that could be stored as a string, integer, etc).   When I pass this type as a parameter to a DbCommand object, I get an exception:     ArgumentException: No mapping exists from object type [...] to a known managed provider native type.   I have CType operators on the class that allow implicit conversion to a string, or a guid, but .NET doesn't use these since it doesn't know it should convert the type.  Is there a way to add a type to the internal mapping, or otherwise tell .NET how to store my custom type in the database?  I obviously can convert the type myself when passing it to the .NET stuff, but I'd like this to happen automatically, like it does for most of the built-in types.    I've tried to implement a TypeConverter class for my type (inherits from TypeConverter, overrides CanConvertFrom, CanConvertTo, ConvertFrom, ConvertTo, IsValid, and added the System.ComponentModel.TypeConverter attribute to my class), but this still doesn't work.   I'm assuming it's missing a piece telling .NET what type to convert to when storing the value in the database.     My workaround for this, for now, is that I intercept the list of parameters, before I pass them to SQL server, and have a method that changes my custom type into a guid. This is dirty, but it does work for now, but I still think this question is unanswered.
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
28494
I have an apex class which fetches and upserts data from external source to Salesforce. Below is the batch class: global class PolicyCalloutBatchClass implements Database.Batchable&lt;Integer&gt;,Database.AllowsCallouts, Database.Stateful {     global Iterable&lt;Integer&gt; start(Database.BatchableContext context) {         Integer[] values = new Integer[0];         while(values.size() &lt; 2999 || Test.isRunningTest()) values.add(values.size());         return values;     }     global void execute(Database.BatchableContext context, Integer[] values) {                  HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();         JsonParser objJsonParser = (JsonParser) JSON.deserialize(policyresponse, JsonParser.class);                    JsonParser.cls_value clsValue = objJsonParser.value;         Map&lt;String, JsonParser.cls_data&gt; clsDataMap = new Map&lt;String, JsonParser.cls_data&gt;();         for(JsonParser.cls_data objClsData: clsValue.data){             clsDataMap.put(objClsData.id, objClsData);         }         list&lt;Policy__c&gt; updatelist = new list&lt;Policy__c&gt;();         for (String eachIdFromMap : clsDataMap.keySet()){                          Policy__c policy = new Policy__c(                 unique_id__c = clsDataMap.get(eachIdFromMap).id,                 agent_id__c = clsDataMap.get(eachIdFromMap).agentId);             updatelist.add(policy);           }         try{             upsert updatelist unique_id__c;             }         catch(DmlException e){             system.debug('This class didnt compile');         }     }     global void finish(Database.BatchableContext context) {              } }  Below is my Mock test class: @isTest global class MockHttpResponseGenerator implements HttpCalloutMock {     // Implement this interface method     global HTTPResponse respond(HTTPRequest req) {           HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();                         return policyres;     } }  Below is my test class: @isTest  private class PolicyUpdateController_Test {     static testMethod void testPostCallout() {         Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());                    Test.startTest();       Database.executeBatch(new PolicyCalloutBatchClass(), 50);          Test.stopTest();              } }  Now, when I run the above test class, either the test class runs forever without any output or I could see the error as  System.LimitException: Too many callouts: 101  Can anyone please let me know if there is any way to get this done? Thanks!
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
11253
When you have code like the following:   static T GenericConstruct&lt;T&gt;() where T : new() {     return new T(); }   The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor.   I have the following workaround:  public static class ParameterlessConstructor&lt;T&gt;     where T : new() {     public static T Create()     {         return _func();     }      private static Func&lt;T&gt; CreateFunc()     {         return Expression.Lambda&lt;Func&lt;T&gt;&gt;( Expression.New( typeof( T ) ) ).Compile();     }      private static Func&lt;T&gt; _func = CreateFunc(); }  // Example: // Foo foo = ParameterlessConstructor&lt;Foo&gt;.Create();   But it doesn't make sense to me why this workaround should be necessary.
12485
I would like to do the equivalent of:  object result = Eval("1 + 3"); string now    = Eval("System.DateTime.Now().ToString()") as string   Following Biri s , I got this snippet (modified to remove obsolete method ICodeCompiler.CreateCompiler():  private object Eval(string sExpression) {     CSharpCodeProvider c = new CSharpCodeProvider();     CompilerParameters cp = new CompilerParameters();      cp.ReferencedAssemblies.Add("system.dll");      cp.CompilerOptions = "/t:library";     cp.GenerateInMemory = true;      StringBuilder sb = new StringBuilder("");     sb.Append("using System;\n");      sb.Append("namespace CSCodeEvaler{ \n");     sb.Append("public class CSCodeEvaler{ \n");     sb.Append("public object EvalCode(){\n");     sb.Append("return " + sExpression + "; \n");     sb.Append("} \n");     sb.Append("} \n");     sb.Append("}\n");      CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());     if (cr.Errors.Count &gt; 0)     {         throw new InvalidExpressionException(             string.Format("Error ({0}) evaluating: {1}",              cr.Errors[0].ErrorText, sExpression));     }      System.Reflection.Assembly a = cr.CompiledAssembly;     object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");      Type t = o.GetType();     MethodInfo mi = t.GetMethod("EvalCode");      object s = mi.Invoke(o, null);     return s;  }
103793
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:  T createDefault() {     if(typeof(T).IsValueType)     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:  T createDefault() {     if(typeof(T).IsValueType || typeof(T).FullName == "System.String")     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   But this feels like a kludge. Is there a nicer way to handle the string case?
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
24567
I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas.   // see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3 class NonSerializableSurrogate : ISerializationSurrogate {     public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             info.AddValue(f.Name, f.GetValue(obj));     }      public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,                                 ISurrogateSelector selector)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             f.SetValue(obj, info.GetValue(f.Name, f.FieldType));         return obj;     } }     Listing 1 adapted from   The main issue I can think of that might be a problem is that the anonymous class is an internal compiler detail and it's structure is not guaranteed to remain constant between revisions to the .NET Framework. I'm fairly certain this is the case based on my research into the similar problem with iterators.  Background  I am investigating the serialization of anonymous functions. I was expecting this not to work, but found it did for some cases. As long as the lambda did *not&amp; force the compiler to generate an anonymous class everything works fine.   A SerializationException is thrown if the compiler requires a generated class to implement the anonymous function. This is because the compiler generated class is not marked as serializable.  Example  namespace Example {     [Serializable]     class Other     {         public int Value;     }      [Serializable]     class Program     {         static void Main(string[] args)         {             MemoryStream m = new MemoryStream();             BinaryFormatter f = new BinaryFormatter();              // Example 1             Func&lt;int&gt; succeeds = () =&gt; 5;             f.Serialize(m, succeeds);              // Example 2             Other o = new Other();             Func&lt;int&gt; fails = () =&gt; o.Value;             f.Serialize(m, fails); // throws SerializationException - Type 'Example.Program+&lt;&gt;c__DisplayClass3' in Assembly 'Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.         }     }   Listing 2  This is similar to the issue of trying to serialize iterators and I had found the following code in a previous search (see ) Using the code from Listing 1 and an ISurrogateSelector I was able to successfully serialize and deserialize the second failing example.  Objective  I have a system that is exposed via a web service. The system has a complex but small state (many objects, not a lot of properties per object). The state is saved in the ASP.NET Cache, but is also serialized to a BLOB in SQL in case of cache expiration. Some objects need to execute arbitrary "events" upon reaching some condition. Hence they have properties accepting Action/Func objects. Contrived example:      class Command     {         public Command(Action action, Func&lt;bool&gt; condition);     }   Somewhere else      void DoSomethingWithThing(Thing thing)     {         state = Store.GetCurrentState();          Command cmd = new Command(() =&gt; thing.Foo(), () =&gt; thing.IsReady())         state.Add(cmd);          Store.Save(state);     }
13551
UPDATE   I have combined various answers from here into a 'definitive' answer on a .  Original question  In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):  public class Publisher {     //ValueEventArgs&lt;T&gt; inherits from EventArgs     public event EventHandler&lt;ValueEventArgs&lt;bool&gt;&gt; EnabledChanged;  }   Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:  public static class Linker {     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged += (s, e) =&gt; subscriber.Enabled = e.Value;     }      //(Non-lambda version, if you're not comfortable with lambdas)     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged +=              delegate(object sender, ValueEventArgs&lt;bool&gt; e)              {                   subscriber.Enabled = e.Value;              };     } }   It worked fine, until we started using it on smaller machines, when I started getting the occasional:  System.ComponentModel.Win32Exception Not enough storage is available to process this command   As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.  I've fiddled around a while with , but it doesn't work with anonymous delegates (not for me anyway).  Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.  (Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...)  (PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the ?)  (PPS: Good , but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...)  EDIT I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links  (tried this - seems to be a bit too weak - GC clears delegates even if target is still alive, same problem with  below),  (forces you to modify publisher, and doesn't really work with anonymous delegates) and  (cited-as-incomplete by Dustin Campbell).   It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'.   I've found another workaround, so I'll stick with that, pending a .
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
100125
The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().  public Boolean TryGetValue(TKey key, out TValue value) {     Boolean got = false;     WithReaderLock(delegate     {         got = dictionary.TryGetValue(key, out value);     });     return got; }   What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
44272
EDIT:  I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type.  Why do I need to do this?  EDIT #2:  The "Values" property is a .NET dictionary of type &lt;TMetadata, TData&gt;.  I have this generic method:  private void FillMetadata&lt;TMetadata, TData&gt;     (Metadata&lt;TMetadata, TData&gt; oMetadata) where TMetadata : IMetadataType {     IMetadataType o;     oMetadata.Values.Add(o, (TData)(object)GetValue()); }   I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).  My question is, why doesn't this compile?  The compile error is on the Add() method:  "cannot convert from 'IMetadataType' to 'TMetadata'."  Isn't that what the "where" clause on the method is for?  What am I missing?