I am using SP.RequestExecutor to add attachments to a list item.  I followed   I need to wait the completation of the asynch call of executeAsync method. How can I achieve this?   Thanks,Nk
122637
I'm working on a SharePoint app where I need to run SP.RequestExecutor.executeAsync() in order to grab some information from one of the Host Web's lists. Depending on what method is calling the oData call I want to do something different.   Unfortuntely, executor.executeAsync() isn't playing as nice as $.ajax() does in terms of using $.when().done() and executing code after an async call is made. Below is some code if you'd like to see:      load = function (){         $.when(getEntries()).done(function () {             ViewModels.Calendar.addEventSource(ko.utils.unwrapObservable(eventList));         });     }      getEntries = function () {         return executor.executeAsync({             url: appweburl                 + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + LIST + "')/items?@target='" + hostweburl                 + "'&amp;$select=Title,OData__x006e_ot5,qnlu,OData__x0066_x20"                 + "&amp;$filter=OData__x0066_x20 eq '" + ViewModels.Person.user.userName() + "' "                 + "and qnlu ge DateTime'" + startDate().toString("yyyy-MM-dd") + "T00:00:00' "                 + "and qnlu le DateTime'" + endDate().toString("yyyy-MM-dd") + "T00:00:00' ",             method: "GET",             headers: { "Accept": "application/json; odata=verbose" },             success: onGetEntriesSuccess,             error: onoDataCallFailure          });     },      onGetEntriesSuccess = function (data) {         var jsonObject = JSON.parse(data.body);         $.each(jsonObject.d.results, function (index, item) {             eventList.push(new Event(item.qnlu, item.OData__x006e_ot5));         });     },      onoDataCallFailure = function (data, errorCode, errorMessage) {         alert('Failed to get host site. Error:' + errorMessage);     };   Any ideas/suggestions would be appreciated.
7478
I would like to upload a file asynchronously with jQuery.     $(document).ready(function () {     $("#uploadbutton").click(function () {         var filename = $("#file").val();          $.ajax({             type: "POST",             url: "addFile.do",             enctype: 'multipart/form-data',             data: {                 file: filename             },             success: function () {                 alert("Data Uploaded: ");             }         });     }); }); &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"&gt;&lt;/script&gt; &lt;span&gt;File&lt;/span&gt; &lt;input type="file" id="file" name="file" size="10"/&gt; &lt;input id="uploadbutton" type="button" value="Upload"/&gt;     Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
33868
Hi i have written trigger in which SC_Problem_Management__c is parent object and SC_Problem_Case_Link__c is child object having master detail relationship. I want to update status field of parent object to awaiting deployment when all child records status having value as 'Tested'.  trigger updatestatus on SC_Problem_Case_Link__c(after update) {     List&lt;SC_Problem_Management__c&gt; parentObjList = new List&lt;SC_Problem_Management__c&gt;();     List&lt;SC_Problem_Management__c&gt; parentObjListToBeUpdated = new List&lt;SC_Problem_Management__c&gt;();     public List&lt;Id&gt; listIds = new List&lt;Id&gt;();     for (SC_Problem_Case_Link__c childObj : Trigger.new) {         listIds.add(childObj.SC_Problem_Management__c);     }     parentObjList = [SELECT Id,Status__c, (SELECT ID, Status__c FROM SC_Problem_Case_Link__r) FROM SC_Problem_Management__c WHERE ID IN :listIds];     Boolean checkApproval = TRUE;     for (SC_Problem_Management__c bid : parentObjList) {         for (SC_Problem_Case_Link__c bsaa : bid.SC_Problem_Case_Link__r) {             if (bsaa.Status__c == 'Tested') {                 checkApproval = TRUE;             } else {                 checkApproval = FALSE;             }         }         if (checkApproval == TRUE) {             bid.Status__c = 'Awaiting Deployment';         }         parentObjListToBeUpdated.add(bid);     }     if (parentObjListToBeUpdated.size() &gt; 0) {         update parentObjListToBeUpdated;     } }   I am getting error while saving the trigger. "Error    Error: Compile Error: Status__c,(SELECT ID, Status__c FROM SC_Problem_Case_Link__r) FROM SC_Problem_Management__c ^ ERROR at Row:1:Column:48 Didn't understand relationship 'SC_Problem_Case_Link__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 9 column 21"  Please guide on this issue.
27583
documentation says that      Maximum execution time for each Apex transaction is 10 minutes for   both Synchronous and Asynchronous   To understand this I executed the below code in anonymous apex window :  Long startTime = System.now().getTime(); Long maxLimit = 9*60*1000; //I am taking max limit as 9 mins. while(System.now().getTime() - startTime &lt;= maxLimit ){   }   I get this error :    What is one use case where we don't run into CPU time limit(or other limits) but reach execution time limit?
106673
What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?  I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the file created event fires before the other process has finished writing the file.  The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.  Edit: After trying out some of the solutions below, I ended up changing the system so that all files wrote to Path.GetTempFileName(), then performed a File.Move() to the final location. As soon as the FileSystemWatcher event fired, the file was already complete.
52925
I built a custom form that saves the data to multiple lists with on click; it works pretty well for its intended use (keeping the data related). Thing is I am totally new at jQuery and SPServices, but am learning.   I would like to know if SPService/jQuery will allow me to use the aspx control to upload a single document to a library? I have seen plugins out there for multiple file uploads so I assume this is possible, but all of these seem way to much for what I am trying to do, and I would like to learn how to do it.  Does anyone know if this is possible? Could provide simple example or explanation or reference?  Appreciate it as always!
24399
Working on a future method to post values to external web service. But since there is a limit of 50 callouts per invocation, I am getting error "Too many future calls : 51". Cases are loaded into salesforce from external ETL in bulk. So is there a way to workaround this error.   Class  public with sharing class caseTrigger {      //method invoked by trigger after insert     public void CaseInsert(List&lt;Case&gt; caseIns){           list&lt;Id&gt; caseIds = new list&lt;id&gt;();             List&lt;Case&gt; caseList = [Select id from case WHERE Id IN :caseIds];                 for(Case c : caseList){                     if(c.Status != 'closed'){                         caseIds.add(c.id);                     }                          if(f.caseId_User.size()&gt;0){PostCases(caseIds);}      }     //postCases (future method)     @future(callout = true)     public static void PostCases(List&lt;Id&gt; Ids){         //prepare Json to post to webservice    } }
116911
Currently we are using informatica data loader which loads a bunch of contacts in salesforce using bulk api. The underlying trigger on contact would create account, contact and other related objects. When we use the bulk api on the data load , we get apex cpu time limit exceeded. This happens only if we use the bulk api and if we use regular upload, it works. Is there anything which we need to do for bulk api or how can we get past the cputime limit exceeded error?     CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:EnrollmentrxRx.ContactCustomerPortal:   execution of BeforeUpdate caused by: System.LimitException: Apex CPU   time limit exceeded Class.ApplicationTriggerHandler.applicationAfter:   line 116, column 1 Class.ApplicationTriggerHandler.afterUpdate: line   51, column 1 Class.TriggerFactory.execute: line 71, column 1   Class.TriggerFactory.createHandler: line 32, column 1   Trigger.ApplicationTrigger: line 13, column 1:—
113129
Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?
24776
I need to spawn a child process that is a console application, and capture its output.  I wrote up the following code for a method:  string retMessage = String.Empty; ProcessStartInfo startInfo = new ProcessStartInfo(); Process p = new Process();  startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardInput = true;  startInfo.UseShellExecute = false; startInfo.Arguments = command; startInfo.FileName = exec;  p.StartInfo = startInfo; p.Start();  p.OutputDataReceived += new DataReceivedEventHandler (     delegate(object sender, DataReceivedEventArgs e)     {         using (StreamReader output = p.StandardOutput)         {             retMessage = output.ReadToEnd();         }     } );  p.WaitForExit();  return retMessage;   However, this does not return anything. I don't believe the OutputDataReceived event is being called back, or the WaitForExit() command may be blocking the thread so it will never callback.  Any advice?  EDIT: Looks like I was trying too hard with the callback. Doing:  return p.StandardOutput.ReadToEnd();    Appears to work fine.
18864
Is there any way other than looping through the Files to check whether the folder or files exist in document library using clientcontext - client object model..  Can someone confirm me whether the below code will work or not. Or will it create any exception??  using(var clientContext = new ClientContext(site))  {  Web web = clientContext.Web;  Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl("/site/doclib/folder/filename.ext");  bool bExists = false;  try { clientContext.Load(file);  clientContext.ExecuteQuery();   bExists = file.Exists;  } catch{ }  if (bExists ) { . .  }
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);         }     } }
104629
I am querying a list to return only items matching a certain title, but the query returns all items. It seems I built or execute the query the wrong way:  /* SP is an alias for Microsoft.SharePoint.Client SP = using Microsoft.SharePoint.Client */ var list = clientContext.Web.Lists.GetByTitle(listTitle);   SP.CamlQuery query = new SP.CamlQuery();  string qs = String.Format("&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name=\"Title\"&gt;&lt;/FieldRef&gt;&lt;Value Type=\"Text\"&gt;{0}&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;", listItemTitle);  query.ViewXml = qs;   SP.ListItemCollection oCol = list.GetItems(query);  clientContext.Load(oCol);  clientContext.ExecuteQuery();  SP.ListItem item = oCol[0];   clientContext.Load(item, i =&gt; i.File);  clientContext.ExecuteQuery();   Based on the query oCol should only contain 1 Item, since the titles are definitly unique, but it returns 58 results (all items) and therefor the item at oCol[0] is not the correct one.  Please note: I was getting the Item and file by Id before, but the client wants a way to enter an error-prone string, so I need to use CAML.  How can I correct this?
17130
I have the need to synchronize the data in certain Salesforce tables (user, account, opportunity, lead, task, contact, etc.) to a local database. For reasons that I won't go into here, I can't use the streaming API. I want to kick off a local process every X minutes that will:   Go through each of the tables on my list Insert any new records Update any existing records that were updated Delete any records locally that were deleted on the server (either deleted directly or indirectly (e.g. through a foreign key relationship, like when an account is deleted its associated tasks are deleted as well).   Can you please offer advice on what API's might be good to use here, and whether one stands out more than the others? Are there any specific design recommendations that might be useful for achieving this goal? Or is there really no practical difference between what REST vs SOAP can do?  It comes down to what is the easiest to maintain/implement? Is there some other route that might be beneficial to use (example: bulk data load to start out followed by outbound messaging tied to all of the objects in question to get updates/inserts/deletes)?   I am using C#/.net.
30114
I have a business logic as follows.   1. A web service class parses XML file containing case data and loads the case to SF. 2. Trigger that on update of case email field make a call to future method to generate attachment ,send email and update case owner field.  trigger CaseUpdate on Case (After update)  {  for(case c : trigger.old)  {     for(case ca : trigger.new)     {         if((c.Email__c != ca.Email__c) &amp;&amp; (c.CS_ID__c != null) &amp;&amp; (c.Count__c == 1))         {           UtilsClass.generateReport_Future(c.id);         }     }  } }    @Future(callout=true)  public static void generateReport_future(String caseId)  { String result = ''; result = generateReport(caseId); if(result == '')  {     result = emailReport(caseId); } UtilsClass.ChangeOwner(caseId);  }   The issue i am facing is,  System.LimitException: Too many future calls: 11, even though single case record is loaded.  Multiple records may be loaded at the same time, but they are sequential(One By One).  Are the records coming in a single batch even though they are being loaded individually..?
51168
I have an LWC template like this: &lt;input list=&quot;counties&quot;&gt; &lt;datalist id=&quot;counties&quot;&gt;   &lt;template for:each={counties} for:item=&quot;county&quot;&gt;     &lt;option key={county.Id}&gt;{county.Name}&lt;/option&gt;   &lt;/template&gt; &lt;/datalist&gt;  I load the county records from the server. There are about 3,000 of them. When the counties are loaded and the template updates, it hangs the entire page for 10-20 seconds. This is a fairly small amount of elements to insert into the DOM.  Why are LWCs so slow when updating the DOM? What about them under the hood makes this such an inefficient operation? How can I speed this up, so that my autocomplete input can be populated by accurate information without hanging the entire page for 20 seconds?
79275
I have an after insert trigger that invokes queueable Apex which makes a callout.  The trigger and callout work fine in the UI and I don't get any errors in normal operation.  However, my unit test keeps failing with the "uncommitted work pending" error despite all my attempts to separate the callout.  I've used a testVisible variable to disable the callout from the trigger so that I can invoke the queueable job explicitly in a startTest/stopTest block after the DML that fires the trigger.  I've pored over the callout class to make sure it's not doing any DML beforehand.  Anyway, if it was doing DML, I should get the uncommitted work pending errors in the UI, right?  I've tried API version 37 and version 41 but the unit test still fails.   I've had a case open with Salesforce premier support for 6 weeks now but haven't made any progress.  Any suggestions?  The unit test:  @isTest static void testCallout() {     // Disable the callout while setting up data.     CCx_EHR_CMCT_Services.isQueueSendEnabled = false;      // Set up the data and execute the DML.     / ...     insert act;      // Set up the http mock     // ...      // Now enable and execute the callout     Test.startTest();     CCx_EHR_CMCT_Services.isQueueSendEnabled = true;     Test.setMock(HttpCalloutMock.class, mock);     System.enqueueJob(new QueueSendToRedox(new List&lt;ActivityHL__c&gt;{act}, desk)));     Test.stopTest();  }   Trigger:  trigger HL_ActivityHL_c on ActivityHL__c (before insert, before update, after insert) {     if (Trigger.isAfter) {         if (Trigger.isInsert) {             CCx_ClientDataDomain.sendEHRClinicalComm(Trigger.new);         }     } }   Trigger handler class:  public without sharing class CCx_ClientDataDomain {     public static void sendEHRClinicalComm(List&lt;ActivityHL__c&gt; triggerNew) {     // do some processing here.     // ...     // then queue the callout job.     System.enqueueJob(new CCx_EHR_CMCT_Services.QueueSendToRedox(             deskActivities.get((Id) desk.getDeskId()), desk));     } }   Queueable job class with callout method:  public with sharing class CCx_EHR_CMCT_Services {     // isQueueSendEnabled is an attempted workaround for unit tests     @testVisible     private static Boolean isQueueSendEnabled = true;      public class QueueSendToRedox implements Queueable, Database.AllowsCallouts {         private List&lt;ActivityHL__c&gt; activities;         private CCx_DeskHierarchySelector.Desk desk;         private Boolean isEnabled;          public QueueSendToRedox(List&lt;ActivityHL__c&gt; activities, CCx_DeskHierarchySelector.Desk desk) {             this.activities = activities;             this.desk = desk;             this.isEnabled = isQueueSendEnabled;         }          public void execute (QueueableContext context) {             if(this.isEnabled) sendClinicalCommToRedox(activities, desk);         }     }      public static void sendClinicalCommToRedox(List&lt;ActivityHL__c&gt; activities, CCx_DeskHierarchySelector.Desk desk) {         // Set up data for the callout.  No DML actions are executed before the callout.         HttpRequest req = buildRequest();         // ...          // Callout         Http http = new Http();         HttpResponse resp = http.send(req);     } }