I had this create method:  [HttpPost] [Route("")] /// &lt;summary&gt; /// Create a team /// &lt;/summary&gt; /// &lt;param name="model"&gt;The team model&lt;/param&gt; /// &lt;returns&gt;The modified team model&lt;/returns&gt; public async Task&lt;IHttpActionResult&gt; Create(TeamBindingViewModel model) {      // If our model is invalid, return the errors     if (!ModelState.IsValid)         return BadRequest(ModelState);      // Get all our colours     var colours = await this.colourService.GetAllAsync();      // Create our new model     var team = new Team()     {         Name = model.Name,         Sport = model.Sport     };      // For each colour, Add to our team     team.Colours = colours.Where(m =&gt; model.Colours.Any(c =&gt; c.Id == m.Id)).ToList();      // Create our team     this.service.Create(team);      // Save our changes     await this.unitOfWork.SaveChangesAsync();      // Assign our Id to our model     model.Id = team.Id;      // Return Ok     return Ok(model); }   As you can see, when a Team is created, I need to add the Colours to the lookup table. To do this, I get the Colours from the database and then filter them by the colours that were passed as part of the model.  That tells Entity Framework that these Colours are not new entities, so it just creates a reference in the lookup table rather than creating new Colours.  Now I want to do the same for the update method.  I tried this:  [HttpPut] [Route("")] /// &lt;summary&gt; /// Update a team /// &lt;/summary&gt; /// &lt;param name="model"&gt;The team model&lt;/param&gt; /// &lt;returns&gt;The modified team model&lt;/returns&gt; public async Task&lt;IHttpActionResult&gt; Update(TeamBindingViewModel model) {      // If our model is invalid, return the errors     if (!ModelState.IsValid)         return BadRequest(ModelState);      // Get our current team     var team = await this.service.GetAsync(model.Id, "Colours");      // Get all our colours     var colours = await this.colourService.GetAllAsync();      // Make changes to our team     team.Name = model.Name;     team.Sport = model.Sport;      // For each colour in our team colours but not in our model colours, remove     foreach (var colour in team.Colours)         if (!model.Colours.Any(c =&gt; c.Id == colour.Id))             team.Colours.Remove(colour);      // For each colour that has to be added, add to our team colours     if (model.Colours != null)         foreach (var colour in model.Colours)             if (!team.Colours.Any(c =&gt; c.Id == colour.Id))                 team.Colours.Add(colours.Where(m =&gt; m.Id == colour.Id).SingleOrDefault());      // Update the team     this.service.Update(team);      // Save our changes     await this.unitOfWork.SaveChangesAsync();      // Return Ok     return Ok(model); }   But it didn't work. I got an error stating:          Collection was modified; enumeration operation may not execute.      I know it is talking about the Colours but I have no idea how to get around it.  Perhaps someone has had a similar problem and managed to fix it?
3800
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.  Collection was modified; enumeration operation may not execute  Below is the code. This is a WCF server in a Windows service. The method NotifySubscribers() is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day). When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine. Do you see a problem with this code? Do I need to make the dictionary thread-safe? [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class SubscriptionServer : ISubscriptionServer {     private static IDictionary&lt;Guid, Subscriber&gt; subscribers;      public SubscriptionServer()     {                     subscribers = new Dictionary&lt;Guid, Subscriber&gt;();     }      public void NotifySubscribers(DataRecord sr)     {         foreach(Subscriber s in subscribers.Values)         {             try             {                 s.Callback.SignalData(sr);             }             catch (Exception e)             {                 DCS.WriteToApplicationLog(e.Message,                    System.Diagnostics.EventLogEntryType.Error);                  UnsubscribeEvent(s.ClientId);             }         }     }          public Guid SubscribeEvent(string clientDescription)     {         Subscriber subscriber = new Subscriber();         subscriber.Callback = OperationContext.Current.                 GetCallbackChannel&lt;IDCSCallback&gt;();          subscribers.Add(subscriber.ClientId, subscriber);                  return subscriber.ClientId;     }      public void UnsubscribeEvent(Guid clientId)     {         try         {             subscribers.Remove(clientId);         }         catch(Exception e)         {             System.Diagnostics.Debug.WriteLine(&quot;Unsubscribe Error &quot; +                      e.Message);         }     } }
69321
Unfortunately, I need to do this.  I'm using ELMAH for my error log.  Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception.  You used to be able to use   Elmah.ErrorLog.Default   However, this is now marked as obsolete.  The compiler directs me to use the method  Elmah.ErrorLog.GetDefault(HttpContext context)   MVC's context is of type HttpContextBase, which enables us to mock it (YAY!).  How can we deal with MVC-unaware libraries that require the old style HttpContext?
14635
private string? typeOfContract {   get { return (string?)ViewState["typeOfContract"]; }   set { ViewState["typeOfContract"] = value; } }   Later in the code I use it like this:  typeOfContract = Request.QueryString["type"];   I am getting the following error at the declaration of typeOfContract line stating:     The type 'string' must be a non-nullable value type in order to use   it as parameter 'T' in the generic type or method   'System.Nullable&lt;T>'   Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.
110676
How can I use the CreateUser method in the Membership class without having to assign a question and answer?  I have disabled it in the web.config with the following setting.  requiresQuestionAndAnswer="false"   I need the status output from the CreateUser method, but the overload requires a question and answer. Can anyone suggest how I can go about this?
112004
I have a Linq query that I want to call from multiple places:  var myData = from a in db.MyTable              where a.MyValue == "A"              select new  {                             a.Key,                             a.MyValue                           };   How can I create a method, put this code in it, and then call it?  public  ???  GetSomeData() {    // my Linq query }
65747
I'm running a REST API which is returning the below:  "id" : "fdgsdgsdsdgsdg",    "pageevents" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ],     "goals" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ] } ]   Im using the below code to de-serialize it, so i can display it as a pageblocktable on a visualforce page however im getting the error :      System.JSONException: Illegal value for primitive   public List&lt;maMoments&gt; getMomentsActivity() {     Id contactId;     if (contactId == null) {         contactId = '0030O00001sqXJr';     }      String contactIdString = String.valueOf(contactId);     String jsonResponse = this.AutomationDetailsMoments(contactIdString);     system.debug(jsonResponse);     List&lt;maMoments&gt; mAutomation = (List&lt;maMoments&gt;) JSON.deserialize(jsonResponse, List&lt;maMoments&gt;.class);     system.debug(mAutomation);     for(maMoments emailStructure : mAutomation){      }      return mAutomation; }  public string AutomationDetailsMoments(String contactId) {     contactId = '0030O00001sqXJr';     Http h = new Http();     HttpRequest req = new HttpRequest();     req.setEndpoint('https://virtserver.swaggerhub.com/mickjdavies/Example/1.0.0/interestingmoments');     req.setMethod('POST');     req.setBody(contactId);      // Send the request, and return a response     HttpResponse res = h.send(req);     system.debug(res.getBody());     return res.getBody(); }  private class maMoments {     public String contactId;     public String id;     public List&lt;String&gt; goals;     public String name;     public String homepage;     public String phone; }
5085
I´m having problems with url parameters (req.requestURI) in my test class.  This is my code.  REST CLASS:  @RestResource(urlMapping='/Accounts/*') global class StoreController {       @HttpGet     global static String getAccounts() {           integer pageNumber=integer.valueof(RestContext.request.params.get('page'));         string  ptime=RestContext.request.params.get('time');         string  hash=RestContext.request.params.get('hash');      }   REST TEST CLASS:  @isTest private class StoreControllerTest {      static testMethod void testGet() {       //do request     RestRequest req = new RestRequest();      RestResponse res = new RestResponse();      req.requestURI = 'https://dev-my-my.cs14.force.com/mine/services/apexrest/Accounts?page=0&amp;time=1390296387&amp;hash=1wer2547';         req.httpMethod = 'GET';     RestContext.request = req;     RestContext.response = res;          String results = StoreController.getAccounts();      } }   When i run test class i get the error:  System.NullPointerException: Argument 1 cannot be null    for line :  integer pageNumber=integer.valueof(RestContext.request.params.get('page'));   Looks like parameters are not taken from url ''  when i run the test class.Please can you help me with this?
86355
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments. eg.  /// &lt;summary&gt;Summary here&lt;/summary&gt; /// &lt;example&gt;Here is an example  &lt;code&gt;example code here&lt;/code&gt; &lt;/example&gt; public void SomeFunction()    We then use Sandcastle and build the help files we need (chm and an online website).  It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.  Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?
80540
I'm trying to do some treatement after creating an item but the treatement is done twice because in my code after creating the item, I'm updating it , so the event reciever get fired twice: first when I add the element and the second when I updated it. Here's the code :  if (Mode == OperationMode.New) {     item = ListeActions.AddItem();     item["Client"] = new SPFieldLookupValue(myClient.ID, myClient["Name"] as string).ToString();     //the Event Reciever ItemAdded is fired here } if (Mode == OperationMode.Edit) {     item = ListeActions.GetItemById(ActionItemID); } TextField ACObject = (TextField)Page.GetControlById("ACObjectID"); UserField ACAssignedTo = (UserField)Page.GetControlById("ACAssignedToID"); NoteField ACDetails = (NoteField)Page.GetControlById("ACDetailsID");  item["Object"] = ACObject.Value; item["AssignedTo"] = ACAssignedTo.Value; item["Details"] = ACDetails.Value;  item.Update();  //if we're in the case of adding new item then the event //reciever ItemAdded is fired here for the second time //while ItemUpdated is not fired   So how can I stop the second fire of itemAdded resulting on the item.Update() yet keep the first fire since I need to keep applying my treatement?  PS: in the case of updating an existing ListeActions.item the itemUpdated is fired twice too !!  BTW : This Code isn't written in the itemadded method nor in the itemupdated method, actually it's the code in a user control for a webpart development.
96142
I am working on a requirement to create an opportunity and opportunity products , when there is an update on the asset object.  The asset object has a filed called Refresh_Asset_To__c, this is a lookup to the product object.   Basically each time I change the product on the Refresh_Asset_To__c, a new opportunity should be generated with the Refresh_Asset_To__c being the opportunity product.  I have tested , and its generating the opportunity , but each time i try to insert the opportunity product I get the error :      Update failed. First exception on row 0 with id 02i3B000003TAk7QAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssetRefreshOpp: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId] Trigger.AssetRefreshOpp: line 56, column 1: []   This is my code:  trigger AssetRefreshOpp on Asset (after update) {      Pricebook2 ikmBook    = [SELECT Id,CurrencyIsoCode FROM Pricebook2 WHERE Id = '01s46000003K1zXAAS'];  List&lt;OpportunityLineItem&gt; oppLiList = new List&lt;OpportunityLineItem&gt;(); Opportunity opp; OpportunityLineItem oli; string refeshed;     List&lt;asset&gt; refreshedAss = [select Id,Contract__r.EndDate,OwnerId,quantity,Name,Refresh_Asset_To__c,Refresh_Asset_To__r.Id,AccountId,account.name from asset                                      where Id IN : Trigger.new                                      And Refresh_Asset__c = True];          for(asset myAss:refreshedAss){             // Create New Opportunity              Opportunity newopp =new Opportunity();   newopp.Name=myAss.account.name + ' ' + 'refreshed'; newOpp.AccountId = myAss.AccountId; newOpp.CloseDate = myAss.Contract__r.EndDate; newOpp.StageName = 'Create'; newOpp.RecordTypeID = '01246000000TfMZAA0'; newOpp.OwnerId = myAss.OwnerId; newOpp.Amount = 0; newOpp.Type= 'Existing Business'; newOpp.OM_Order_Type__c = 'Regular'; newOpp.CurrencyIsoCode = ikmBook.CurrencyIsoCode; newOpp.Pricebook2Id = ikmBook.Id;  insert newOpp;          List&lt;PriceBookEntry&gt; priceBookList = [SELECT Id, Product2Id,CurrencyIsoCode, Product2.Id, Product2.Name FROM PriceBookEntry WHERE  PriceBook2.isStandard=true LIMIT 1];               for(asset myAssets:refreshedAss){               OpportunityLineItem oli = new OpportunityLineItem();                oli.OpportunityId = newOpp.Id;                oli.Product2Id = myAssets.Refresh_Asset_To__r.Id;                oli.PriceBookEntryId = priceBookList[0].Id;                oli.UnitPrice = 0;               oli.Quantity = myAssets.Quantity;               oppLiList.add(oli);           }           insert oppLiList;               } }
73694
I have used the following code to add new picklist values to the picklist field called "Tags__c" in contact object. The code works and the new picklist values are getting created successfully but they are not added to any record types and hence i have to manually add them to the record types to view the new values in UI. I need to do assign the existing record types for the new picklist values created through apex metadataservice code.  public static void updatePicklist() {     MetadataService.MetadataPort service = new MetadataService.MetadataPort();                  service.SessionHeader = new MetadataService.SessionHeader_element();     service.SessionHeader.sessionId = UserInfo.getSessionId();     MetadataService.CustomField customField = (MetadataService.CustomField) service.readMetadata('CustomField', new String[] { 'Contact.Tags__c' }).getRecords()[0];     metadataservice.PicklistValue two = new metadataservice.PicklistValue();     two.fullName= 'Sample 1';     two.default_x=false;     metadataservice.PicklistValue three = new metadataservice.PicklistValue();     three.fullName= 'Sample 2';     three.default_x=false;     customField.picklist.picklistValues.add(two);     customField.picklist.picklistValues.add(three);   handleSaveResults(     service.updateMetadata(         new MetadataService.Metadata[] { customField })[0]);    }   Can someone suggest me a solution for this?
116377
I'm trying to populate the Contact lookup when a User creates a new related list object from the Contact page.  I am storing the Contact parameter in a Custom Setting so it can be changed when deploying to Production.  For some reason, whenever I try to bind this custom setting to the URL I get a leading '#' and none of the bindings work correctly.  This is despite using the URLENCODE function in the Visualforce  So when I put this (contactParameterId is != null)  &lt;apex:outputLink value="/{!relList.keyPrefixObject}/e?{!IF(relList.contactParameterId != null, 'CF{!URLENCODE(relList.contactParameterId)}={!URLENCODE(contact.Id)}&amp;', '')}retURL=/{!contact.Id}&amp;saveURL=/{!contact.Id}"&gt;&lt;/apex:outputLink&gt;   I get the URL      {URLENCODE(relList.contactParameterId)}={!URLENCODE(contact.Id)}&amp;retURL=/003U000000PL9LNIA1&amp;saveURL=/003U000000PL9LNIA1   What am I doing wrong?
79479
Background: I'm creating a WPF app using MVVM, and using a DI container to build my ViewModels  My App.xaml looks like this:  &lt;Application x:Class="WpfApp.App"     ...xmlns etc...     StartupUri="MainWindow.xaml"&gt;     &lt;Application.Resources&gt;         &lt;app:ServiceLocator x:Key="serviceLocator" /&gt;     &lt;/Application.Resources&gt; &lt;/Application&gt;   MainWindow.xaml looks like this:  &lt;Window x:Class="CompositeMefWpfApp.MainWindow"     ...xmlns etc... &gt;     &lt;Control.DataContext&gt;         &lt;Binding Path="MainWindowViewModel" Source="{StaticResource serviceLocator}" /&gt;     &lt;/Control.DataContext&gt;   Now, this all works fine, but the StartupUri is hardcoded into the XAML, which I don't want. Following guidance of several blogposts and articles I found, I removed the StartupUri, and tried to create the MainWindow by hooking OnStartup in App.xaml.cs, like this:  protected override void OnStartup( StartupEventArgs e ) {     base.OnStartup(e);     new MainWindow().Show(); }   The problem is, the app crashes when trying to show the window, with this exception:     Cannot find resource named '{serviceLocator}'. Resource names are case sensitive.  Error at object 'System.Windows.Data.Binding' in markup file 'WpfApp;component/mainwindow.xaml' Line 8 Position 45.   As far as I can tell, the &lt;Application.Resources&gt; section is simply not being read out of the xaml file. I can put some code in the OnStartup to add the resource programatically like this:  Resources.BeginInit(); Resources.Add("serviceLocator", new ServiceLocator()); Resources.EndInit();   However that's an ugly hack, and doesn't help me if I wanted to put something else in the app.xaml file later on :-(  Should I be hooking some other event? Is there a way around this?
97745
I have a database setup with the following schema:   CREATE TABLE siteInfo (     siteID             SERIAL  NOT NULL,     siteName           TEXT    NOT NULL,     siteHost           TEXT    NOT NULL,     notes              TEXT    NOT NULL,     allowableCountries TEXT    NOT NULL,     displayChance      INT     NOT NULL,     imagePath          TEXT    NOT NULL,     PRIMARY KEY (siteID) );  CREATE TABLE siteLinks (     siteID             SERIAL  NOT NULL,     URL                TEXT    NOT NULL,     FOREIGN KEY (siteID) REFERENCES siteInfo(siteID) ON DELETE CASCADE );  CREATE TABLE siteDemographicLinks (     siteID             SERIAL  NOT NULL,     URL                TEXT    NOT NULL,     country            TEXT    NOT NULL,     chance             INT     NOT NULL,     FOREIGN KEY (siteID) REFERENCES siteInfo(siteID) ON DELETE CASCADE );  CREATE TABLE linkVisits (     siteID             SERIAL  NOT NULL,     rawVisit           BIGINT  NOT NULL,     redirects          BIGINT  NOT NULL,     FOREIGN KEY (siteID) REFERENCES siteInfo(siteID) ON DELETE CASCADE );   Data from my form is in the following format:  array(7) { ["siteName"]=&gt;string(9) "Site Name" ["siteHost"]=&gt;string(9) "SIte Host" ["notes"]=&gt;string(5) "Notes" ["links"]=&gt;array(2) {[0]=&gt;string(6) "Link 1" [1]=&gt;string(6) "Link 2"} ["countries"]=&gt;string(4) "None" ["displayChance"]=&gt;string(2) "15" ["extraLink"]=&gt;array(2) {    [0]=&gt;array(3) {       ["url"]=&gt;string(7) "dSite 1"       ["countries"]=&gt;string(4) "NONE"       ["chance"]=&gt;string(2) "11"       }    [1]=&gt;array(3) {       ["url"]=&gt;string(6) "dSite2"       ["countries"]=&gt;string(4) "None"       ["chance"]=&gt;string(2) "13"       }    } }   How would I go abound inserting data into the many type tables so they reference tuples inserted into the one type table?  I have this query constructed:  INSERT INTO siteInfo (siteName, siteHost, notes, allowableCountries, displayChance, imagePath) VALUES ('Sample', 'sample.com', 'note', 'NONE', '50', '../var');   I would then need to insert data into the siteLinks table, which is related to the entry already in the siteInfo table.  INSERT INTO siteLinks (siteID, URL) VALUES ((SELECT siteid FROM siteinfo WHERE sitename='Sample'), 'test');   Is there a better way of doing this?
103246
I can't seem to call the objects out on the database and onto a visualforce page using this set up:   public with sharing class HarborEventController {  private final Event__c event; public HarborEventController(ApexPages.StandardController controller) {     this.eventlist = (Event__c)controller.getRecord(); }   public Integer eventcount{get;set;} public HarborEventController (){    eventcount = [SELECT COUNT() FROM Event__c];     }   public list&lt;Event__c&gt; mainlist {get;set;}   public list&lt;Event__c&gt; displayevents(){     mainlist = new list&lt;Event__c&gt;();     String mainsoql = 'SELECT Id, Name__C, Message__c, Display_Date__c, FROM Event__c';      mainsoql += 'ORDER BY Display_date__c LIMIT :5';     mainlist = Database.query(mainsoql);     return mainlist; }   and the visualforce page :           &lt;apex:composition template="eh_base"&gt;           &lt;apex:define name="heros-content"&gt;             &lt;/apex:define&gt;       &lt;apex:define name="content"&gt;        &lt;section id="services-sec"&gt;          &lt;div class="container"&gt;             &lt;div class="row" style="padding-top: 60px;"&gt;       &lt;apex:outputPanel layout="block" rendered="{!AND(NOT(ISNULL(mainlist)),mainlist.size&gt;0)}"&gt;         &lt;apex:form id="blockofeventtorepeat"&gt;             &lt;apex:repeat value="{!mainlist}" var="evententry" id="repeat"&gt;                 &lt;div class="col-md-9"&gt;                    &lt;h3&gt;&lt;apex:outputLink styleClass="evententry-header block" value="{!$Page.eh_eventdetails}?id={!evententry.id}"&gt;{!evententry.Name__c}&lt;/apex:outputLink&gt;&lt;/h3&gt;                     &lt;apex:outputPanel &gt;                      &lt;p&gt;                          &lt;img src="{!URLFOR($Action.Attachment.Download, evententry.Attachments[0].Id)}" class="pull-left img-responsive" alt="" style="max-width:180px;max-height:100px"/&gt;                         {!evententry.Message__c}                      &lt;/p&gt;                        &lt;apex:outputLink styleclass="btn btn-sm btn-default" value="{!$Page.eh_eventdetails}?id={!evententry.id}"&gt;Read More&lt;/apex:outputLink&gt;                      &lt;/apex:outputPanel&gt;                 &lt;/div&gt;                 &lt;/apex:repeat&gt;                 &lt;/apex:form&gt;                 &lt;/apex:outputPanel&gt;                   &lt;/div&gt;             &lt;/div&gt;                 &lt;/section&gt;           &lt;/apex:define&gt; &lt;/apex:composition&gt;     Can anyone suggest how I can able to get the event data from the query and display it on a visualforce page in a repeat tag? I've tried everything and it doesn't work.  I've already tried passing the query from an anonymous user and the results were as expected
38380
I have an overwritten edit page for my custom object, which have different record types with different fields.  The simplified desktop version of this VF page looks like this:  &lt;apex:page standardController="CustomObject__c" extensions="CustomObjectCtrlExt" &gt;      &lt;apex:form&gt;          &lt;apex:pageBlock&gt;                       &lt;apex:pageBlockButtons &gt;                 &lt;apex:commandButton value="Save" action="{!save}"/&gt;                 &lt;apex:commandButton value="Cancel" action="{!cancel}"/&gt;                             &lt;/apex:pageBlockButtons&gt;              &lt;!-- Record Type 1 --&gt;             &lt;apex:pageBlockSection rendered="{!recordtypename == 'RecordTypeName1'}" &gt;                 ...             &lt;/apex:pageBlockSection&gt;               &lt;!-- Record Type 2 --&gt;             &lt;apex:pageBlockSection rendered="{!recordtypename == 'RecordTypeName2'}" &gt;                 ...             &lt;/apex:pageBlockSection&gt;               &lt;!-- Record Type 3 --&gt;             &lt;apex:pageBlockSection rendered="{!recordtypename == 'RecordTypeName3}" &gt;                 ...             &lt;/apex:pageBlockSection&gt;                ...        &lt;/apex:form&gt;  &lt;/apex:page&gt;   Now I want to create a second VF page for my mobile users with HTML 5.  How do I implement the conditional rendering with HTML 5 ?  Of course, something like &lt;div rendered="{!recordtypename == Name1}"&gt; doesn't work.
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 ?