• Daniel Ballinger
  • SMARTIE
  • 1937 Points
  • Member since 2008
  • Developer
  • FuseIT | Salesforce MVP


Badges

  • Chatter
    Feed
  • 51
    Best Answers
  • 2
    Likes Received
  • 58
    Likes Given
  • 25
    Questions
  • 647
    Replies
I'm trying to limit the user when they use a botton to only be able to have one record if they don't have any other records in the status of "New". 


global with sharing class RetrieveNextUtils {
    webService static Id retrieveNextCase(String userId)
    {
        //Here I'm looking to see if the current user has any leads in Lead Status containing New
        
        
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
            //Find an open case that is assigned to one of those queues
            Case caseObj = [select c.Id,c.OwnerId from Case c where 
                                                        c.IsClosed=false 
                                                        and c.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (caseObj!=null) {        
                //If we found one, assign it to the current user
                caseObj.OwnerId = userId;
                update caseObj;
                
                return caseObj.Id;
            }
        }
        
        return null;
    }
    
    webService static Id retrieveNextLead(String userId)
    {
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
        
            
            //Find an open lead that is assigned to one of those queues
            List<Lead> leads = [select l.Id,l.OwnerId from Lead l where 
                                                        l.IsConverted=false 
                                                        and l.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (leads.size()>0) {       
                //If we found one, assign it to the current user
                leads[0].OwnerId = userId;
                update leads;
                
                return leads[0].Id;
            }
        }
        
        return null;
    }
    
    //Returns a list of ids of queues that this user is a member of
    public static List<Id> getQueuesForUser(String userId) 
    {
        List<Id> listGroupIds = new List<Id>();
        List<GroupMember> listGroupMembers = [Select g.GroupId From GroupMember g 
                                                where g.Group.Type='Queue'
                                                and g.UserOrGroupId=:userId];
                                                
        if (listGroupMembers!=null && listGroupMembers.size()>0) {      
            for (GroupMember gm:listGroupMembers) {
                listGroupIds.add(gm.GroupId);
            }
        }
        
        return listGroupIds;
    }
    
    
        
   
}
We have a .NET application that connects to salesforce via SOAP and uses the API for creating/updating objects.

We noticed the initial instantiation of a new Salesforce Service object for a new session takes approximately 15 seconds.  

Has anyone else come across this issue and/or found a way to reduce this time significantly?

We currently use the Enterprise WSDL and I'm looking into downloading the Partner WSDL to see if this is what we should be using, but I wanted to check with the forum in case others have come across this issue.

Any help would be appreciated.  Thanks.
Hello Friends,

Having 15 years of experience with All major Microsoft tools and techniques. 
Starting this year gone throught few knowledgebase related to Salesforce and I was impressed with those article. So I decided to dip more into this. First I purhcased 2-3 udemy courses and completed them. Then I started with trailhead Trails. Until now covered basic admin, dev, Intermediate admin. Also goen through Apex, Triggers, import export, chatters, etc... I have 29725 Points with 19 Badges as of now.

Can someone show me correct path for me now?

To explore further I want to work on some real projects (FOR FREE??? YES). My Microsoft knowledger might be helpfull for your projects. Also I am not completely new to Salesforce. Do you have any other option or suggestion for me?

If yes, please share

Thanks
Using the NPSP.
When i submit a donation from a web form to salesforce using a click and pledge integrated platform; it creates a correct account and contact but gives me error on the opportunity record creation.
User-added image
Guess sasesforce concatenates to the click and pledge id his own generated id. 
How can i overcome this error ? is there a workaround?
Hello - I'm new to Salesforce and I wanted to reach out/get answers on governance around Call Ins.

If I for example use "user1@practicefusion.com" as a login for Boomi to make calls to Salesforce (e.g. insert, update, upsert, etc.), how many threads (i.e. concurrency) can I utilize so that I can use that user multiple times in multiple simultaneous calls? E.g. If I have 2 processes in Boomi running simultaneously, 1 creating Opportunities, and the other updating Accounts, can I use the same user to make the call at the same time?

If no concurrency limit, what mechanism/governance does Salesforce enforce to make sure that I don't crash our instance?

Thanks in advance for your help!
Melissa

 
Hey Everyone, 
I'm a novice developer trying to set up an integration between the Salesforce REST API and our platform. Since we utilize OneLogin for SSO, this is the flow that I was using https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm . I've followed all the steps concerning appending the security token to the end of the password, relaxed IP restrictions on the connected app, and configured the permitted users to "admin approved users are pre-authorized" but I'm still receiving the following error:

"error": "invalid_grant",
"error_description": "authentication failure"
}
Which I believe refers to the credentials being incorrect from what I've googled thus far. But, I'm confident that the credentials are correct because I used them to successfully log in to the Apex dataloader. 


Here's a screenshot of the request I'm attemping with the error message (minus the user credentials): User-added image


Any help or advice would be much appreciated!
Hi,

Is there a way to view the raw REST API request sent from Salesforce?

Background:
I am making a GET request to an external system. I have properly formed the request and successfully connected using the HTTPRequester Firefox addon. The raw request in HTTPRequester looks like this:

GET https://apius.uniprix.com/2_0_1/service/account/?t=6f592bf589bdcb361c8c13224182e75103736e67331a7f4774fe97f577f1d743
Apikey: <apikey>
ip: <ip>
Content-Type: application/json
{"account":{"username":"<username>","token":"6f592bf589bdcb361c8c13224182e75103736e67331a7f4774fe97f577f1d743"}}

I have recreated this request in APEX, but I do not get the same response. My APEX code looks like this:

     HttpRequest req = new HttpRequest();
     req.setMethod('GET');
     req.setEndpoint('https://apius.uniprix.com/2_0_1/service/account/?t=' + <token>);
      
     String API_KEY = <apikey>;
     String API_ADDRESS = <ip>;
     req.setHeader('Apikey', API_KEY);  
     req.setHeader('ip', API_ADDRESS);  
     req.setHeader('Content-Type', 'application/json');  

     System.debug('{ "account":{"username":"'+ <username> +'","token":"'+ <token>+'"}}');
     req.setBody('{ "account":{"username":"'+ <username> +'","token":"'+ <token> +'"}}');
         
     Http http = new Http();
     System.debug(req);
     HTTPResponse res = http.send(req);

The request does provide a valid response (so the token seems valid). Instead of the 200 code that HTTPRequester returns though, I am getting a 417 code with the message: "Missing data : account->serviceId"

This leads me to think that the request is being processed as a "POST" instead of a "GET" so I would like to see the raw REST request being sent out from Salesforce.

Open to any ideas.

Thanks,

Ming

I have 2 org ad I want to provide making calls from one 1 org to another
I have allredy generated wsdl file for my soap webservice 
Original   class  simply looks like

global class SoapTest {
    webservice static String getGreeting() {
        return 'Hi, pal!';
    }
}

My external  call now loooks like:

soapTestParse.SoapTest sp = new soapTestParse.SoapTest();
String output = sp.getGreeting();
System.debug(output);

as a result I'mI getting 

System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session faultcode=sf:INVALID_SESSION_ID faultactor=


I have been reading bunch of posts with the same problem but I still don't know the proper way to solve it

I saw such snippets of code 

in developer guide:

stub.inputHttpHeaders_x.put('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
 

but How can I dynamically get this token? Even if I hard code session id of target org, error remains the same.

In another poste

partnerSoapSforceCom.LoginResult partnerLoginResult = myPartnerSoap.login('karnashiva@cognizant.com.dev', 'Password123'); 
soapSforceComSchemasClassAccountins.SessionHeader_element webserviceSessionHeader = new soapSforceComSchemasClassAccountins.SessionHeader_element(); 
webserviceSessionHeader.sessionId = partnerLoginResult.sessionId;

I don't have neither login method no loginresult class in my generated from wsdl apex class

In another poste

ws.inputHttpHeaders_x = new Map <String, String>(); 
String b64_string = EncodingUtil.base64Encode(Blob.valueOf('<user_name>:<password>')); ws.inputHttpHeaders_x.put('Authorization', 'Basic ' + b64_string);
it still doesn't work

Can someone help, or give some tips or proper examples of soap callouts?
Hi,
   I am using WSDL to get user information using salesforce session id. I have added below line in VB.net v4.5:- 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls

It's not working for Sandbox environment but it works for a production environment. Could you please help me? 
We have a force.com org that uses a "Lead" type object called an "Inquiry". I would like my web developer to be able to create new Inquiries directly from our web forms using the API. I have followed the steps for generating the SOAP WDSL file, and I have the Cheat Sheet for this as well.
My web developer says they think they need a URL. They say it might look like this:
http://companyname.force.com/ExternalWebForm

Can you tell me what this is and how I would generate it? This is probably so simple it's silly, but I just don't see what to do next.
Hello everyone,

I am having an issue performing a bulk query when PK Chunking is enabled. This is the exact error I receive: "InternalServerError : PKChunking failed. InvalidBatch : Wrong content-type for batch (text/csv), job is of type: application/xml".

Below I provided the sample C# .NET code I'm running where I receive the error. 

It should be noted that the job and batch are being created successfully but fails when salesforce runs the batch.
Also, I've found that this error only occurs when the PK Chunking header is enabled. When disabled, the batch will run successfully and return the results I requested. 

Additional notes. I'm performing a simple query in sandbox on a custom object.

Does anyone know what I may be doing wrong?

Thanks!




public static void performBulkQuery(String objectAPIName, String soqlQuery)
{
    //create new job
    JobWrapper job = createJob("query", objectAPIName, 500);

    //create new batch
    BatchWrapper batch = createBatch(job.Id, soqlQuery);
}

public static JobWrapper createJob(String operation, String objectName, int pkChunkingSize)
{
    String jobRequestXML =
        @"<?xml version=""1.0"" encoding=""UTF-8""?>
         <jobInfo xmlns=""http://www.force.com/2009/06/asyncapi/dataload"">
           <operation>{0}</operation>
           <object>{1}</object>
           <contentType>XML</contentType>
         </jobInfo>";

    jobRequestXML = String.Format(jobRequestXML, operation, objectName);

    String requestUrl = "https://" + MainProgram.SFInstance + ".salesforce.com/services/async/36.0/job";

    WebClient wc = new WebClient();
    wc.Encoding = Encoding.UTF8;
    wc.Headers.Add("X-SFDC-Session: " + MainProgram.loginResult.sessionId);
    wc.Headers.Add("Content-Type: application/xml");
    String chunkSize = pkChunkingSize.ToString();
    wc.Headers.Add("Sforce-Enable-PKChunking: chunkSize=" + chunkSize);

    String resultXML = invokeRestAPI(requestUrl, jobRequestXML, wc);

    return JobWrapper.parseJobResponse(resultXML);
}

public static BatchWrapper createBatch(String jobId, String batchRequestXML)
{
    String requestUrl = "https://" + MainProgram.SFInstance + ".salesforce.com/services/async/36.0/job/" + jobId + "/batch";

    WebClient wc = new WebClient();
    wc.Encoding = Encoding.UTF8;
    wc.Headers.Add("X-SFDC-Session: " + MainProgram.loginResult.sessionId);
    wc.Headers.Add("Content-Type: application/xml");

    String resultXML = invokeRestAPI(requestUrl, batchRequestXML, wc);

    return BatchWrapper.parseBatchResponse(resultXML);
}

private static String invokeRestAPI(String requestUrl, String requestXML, WebClient wc)
{
    try
    {
        return wc.UploadString(requestUrl, "Post", requestXML);
    }
    catch (WebException webEx)
    {
        String error = String.Empty;

        if (webEx.Response != null)
        {
            using (var errorResponse = (HttpWebResponse)webEx.Response)
            {
                using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                {
                    error = reader.ReadToEnd();
                }
            }
        }

        throw;
    }
}






 
My php app that has been working fine for months is down today. 

 try {
        $mylogin = $mySforceConnection->login($sfuser, $sfpass.$sftoken);    
    } catch (Exception $e){
         $result['exception'] = $e;
    }

$result is now returning:
"exception": {
    "faultstring": "Could not connect to host",
    "faultcode": "HTTP"
}

If I enter "http://soap.sforce.com/" in my browser I get host not found.  It's not just me, http://downforeveryone.com/soap.sforce.com/ says it's down for everyone.

Is the API really down?  Workbench works fine for me.

 
I am looking for a way to access the Notes and Attachments section on a custom object called Assets__c. I am using the Force.com REST API to access the platform, and on the UI, there is a notes and attachment section that lists the files that have been uploaded using Chatter. I want to know the URL and method by which I can access these files and how/if I will get a direct link to those attachments that I can then use client side.

Any help would be incredible! Thanks!
We recently increased the size of a table in our back end by about tenfold and it's causing me to hit CPU limits in a batch callout job. I have attempted to rewrite the code to make several calls, but ultimately I think the failure comes in assembling the large map. Is there any way around this without adding pagination to our back end API call and then making a bunch of classes? I'd love to contain this in a single class but it's so much data being processed that I don't know how to get around this. Could I more efficiently parse the JSON maybe? Store it to a separate table and have two batch classes running, one to populate that table with values mirroring our back end and another to do the sync?

Original Code:
global class AdminAPIAccountLookupSync_Batch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

	global Database.QueryLocator start(Database.BatchableContext bc) {
        return database.getQuerylocator([SELECT Id,Client_ID__c,Dash_Id__c FROM Account WHERE RecordType.Name = 'End User' OR RecordType.Name = 'Agency / Channel Partner']);
	}

    global void execute(Database.batchableContext info, List<Account> scope) {
        //Establish Lists and Maps for later
        Map<String,String> mapIdMatch = new Map<String,String>();
        List<Account> listAccountsToUpdate = new List<Account>();

        try {
            String endpointAddition = '/clients';

            // refer to helper class to complete callout
            HttpResponse res = APICalloutHelper.getResponse(APICalloutHelper.buildAdminAPIGetRequest(endpointAddition));

            // parse JSON to extract Icon URL
            JSONParser responseParser = JSON.createParser(res.getBody());

            String rowId;
            
            while (responseParser.nextToken() != null) {
                if (responseParser.getCurrentToken() == JSONToken.FIELD_NAME && responseParser.getText() == 'id') {
                    responseParser.nextToken();
                    rowId = responseParser.getText();
                } else if (responseParser.getCurrentToken() == JSONToken.FIELD_NAME && responseParser.getText() == 'salesforce_id') {
                    responseParser.nextToken();
                    if (responseParser.getText() != 'null') {
                        mapIdMatch.put(responseParser.getText(),rowId);
                    }
                }
            }
            
        } catch (Exception e) {
            System.debug(LoggingLevel.ERROR,'Error getting Admin response: ' + e.getMessage());
        }
        if (!mapIdMatch.isEmpty()) {
            for (Account acc : scope) {
                if (mapIdMatch.containsKey(acc.Client_ID__c)) {
                    acc.Dash_Id__c = mapIdMatch.get(acc.Client_ID__c);
                    listAccountsToUpdate.add(acc);
                }
            }
            update listAccountsToUpdate;
        }
    }

	global void finish(Database.batchableContext info){}
}


Rework Attempt (also hitting CPU limit, but maybe I'm on the right path?)
global class AdminAPIAccountLookupSync_Batch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

    public Map<String,String> mapIdMatch = new Map<String,String>();
    public List<Account> listAccounts = new List<Account>();

	global Database.QueryLocator start(Database.BatchableContext bc) {
        return database.getQuerylocator([SELECT Id,Client_ID__c,Dash_Id__c,API_Ref__c FROM Account WHERE RecordType.Name = 'End User' OR RecordType.Name = 'Agency / Channel Partner']);
	}

    global void execute(Database.batchableContext info, List<Account> scope) {
        for (Account acc : scope) {
            listAccounts.add(acc);
        }
    }

	global void finish(Database.batchableContext info) {
        Integer page = 1;
        while (page != null) {
            try {
                String endpointAddition = '/clients?rows_per_page=1000&page=' + String.valueOf(page);
                // refer to helper class to complete callout
                HttpResponse res = APICalloutHelper.getResponse(APICalloutHelper.buildAdminAPIGetRequest(endpointAddition));

                // parse JSON to extract Icon URL
                JSONParser responseParser = JSON.createParser(res.getBody());

                if (res.getBody() != null) {
                    String rowId;
                    
                    while (responseParser.nextToken() != null) {
                        if (responseParser.getCurrentToken() == JSONToken.FIELD_NAME && responseParser.getText() == 'id') {
                            responseParser.nextToken();
                            rowId = responseParser.getText();
                        } else if (responseParser.getCurrentToken() == JSONToken.FIELD_NAME && responseParser.getText() == 'salesforce_id') {
                            responseParser.nextToken();
                            if (responseParser.getText() != 'null') {
                                mapIdMatch.put(responseParser.getText(),rowId);
                            }
                        }
                    }
                    page++;
                } else {
                    page = null;
                }
            } catch (Exception e) {
                page = null;
                System.debug(LoggingLevel.ERROR,'Error getting Admin response: ' + e.getMessage());
            }
        }

        List<Account> listAccountsToUpdate = new List<Account>();
        if (!mapIdMatch.isEmpty()) {
            for (Account acc : listAccounts) {
                if (mapIdMatch.containsKey(acc.Client_ID__c) {
                    acc.Dash_Id__c = mapIdMatch.get(acc.Client_ID__c);
                    listAccountsToUpdate.add(acc);
                }
            }
            update listAccountsToUpdate;
        }
    }
}

 
Hi All,

Can you please help me how to hit 20 times third party server from salesforce.

My requirement is third party server contains 20000 records. I need to fetch those 20000 records into salesforce and then need to update those 20000 records in salesforce.

We have a third party url which pulls the 1000 records per one transaction. In this manner, we need to hit 20 times to fetch all records. 

Can any one provide me the best approach for this requirement. 
Hi,

  any one let me know how we will pass passord fileds(Text Encryptd) in Endpoint url and what is procedure
Hi,

I am trying to implement the integration of an external system with Salesforce and have exposed a WS using an apex class for this purpose. In order to access the WS Salesforce documentation (https://help.salesforce.com/apex/HTViewSolution?urlname=Updating-Hard-Coded-References-FAQ&language=en_US) states I should first consume a login WS (enterprise or partner). The response should contain a ServerURL and a Session ID. That ServerURL should be set as the target endpoint for a subsequent call to my WS. 

The issue is when I set the targent endpoint as the URL for my WS call in SOAP UI I am getting the following response:
No operation available for request {http://soap.sforce.com/schemas/class/ICL_GatewaySAP}QueryRequest

The login WSDL URL: 
https://test.salesforce.com/services/Soap/c/36.0/0DF8E00000000De

The ServerURL returned by the login method:
https://icl--Staging.cs87.my.salesforce.com/services/Soap/c/36.0/00D8E0000008itT/0DF8E00000000De

What I am doing wrong?
 
  • March 21, 2016
  • Like
  • 0
Hello,

In order to grab custom field IDs, I added a tooling API query. Any profile without "View All Data" gets the following response for HTTP Request.
The standard profile does have API enabled permission and full CRED access on any involved object. The Apex class has "Without Sharing" tag as well.

CALLOUT_RESPONSE|[58]|System.HttpResponse[Status=Bad Request, StatusCode=400]

Sample Code:
 
String query = 'SELECT Id From CustomObject Where DeveloperName = \'' + objectName + '\'';
        String endpoint = Url.getSalesforceBaseUrl().toExternalForm();
        endpoint += '/services/data/v29.0/tooling/query/?q=';
        endpoint += EncodingUtil.urlEncode(query, 'UTF-8');
        
        HttpRequest request = new HttpRequest();
        request.setMethod('GET');
        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

I need to either:

1. Adjust the non-system admin profile, so that its SessionId gets a proper response like a profile with "View All Data" e.g system admin.
2. Somehow use a sessionId that doesnt belong to current session's profile holder. Use a system admin's sessionid WITHOUT embedding their username and password anywhere.
3. Get further debugging information from the HTTP response. I am not really sure about the specifics of why its a "bad request".


Any guidance would be appreciated. Thanks
Hello,

I am able to set any product item "Active" by setting Product2 object's IsActive and IsActiveSpecified = true through Web Services.

Problem is; when I need to deactivate it (by setting Product2 object's IsActive and IsActiveSpecified flag = false). It returns "Successful" but it doesn't set IsActive = false, cannot deactivate, cannot disable same item.

One important thing I noticed;
-when I submit to set the Active flag true, I can see this line in the Request <q1:IsActive>true</q1:IsActive>
- but when submit same code to disable the Active flag, Request to server, doesn't contain     <q1:IsActive>true</q1:IsActive>


Web service runs under System Administrator rights.

Can anyone help to identify why it works when I need to set true but it doesn't work when I need to set it false?

Many thanks
 
Hi,

We are using Talend middleware to integrate and exchange data between our internal systems and SF using SF API. The SF CRM is acting as a 'slave' while our system database is a master.  So, almost every object in SF has an external ID that maches the record in our DB. 

All our 'upserts' works fine when matched on External ID. But in this case, we need to update - not upsert - the record in SF using External ID, which is marked as unique in SF. 

But, when runing the code this is the error: MISSING_ARGUMENT:Id not specified in an update call - for every single record regardles if the External ID already exist in SF or not.

So, my question is - can update be done on External ID or it must be the SF Id ?

Thanks


 
I'm attempting to retrain an evisting vision model using additional feedback. I've also tried creating a new model for the dataset.

In both cases I was using a trainParams of:
'{"withFeedback": true}'
The existing model has a SUCCEEDED status but shows no sign that the feedback was incoperated.

The new model ends up with the failureMsg:
"java.lang.IllegalArgumentException: The dataset example referenced examples/1010273-4e2abc4183fd732aae779a1a3a3cb088de02898ec2fce61aee921df31675a676 does not exist"
Has something got corrupted within my dataset? Should I just start again with a new dataset?
 
I'm working through Apex & .NET Basics - Understanding Execution Context

When validating the challenge I'm getting the error:
 
Challenge Not yet complete... here's what's wrong: 
The Trigger 'AccountTrigger' does not appear to be calling the AccountTriggerHandler class correctly or using isBefore or isInsert content variables.

The trigger I currently have is minimal:

trigger AccountTrigger on Account (before insert) {
    AccountTriggerHandler.CreateAccounts(Trigger.new);
}

Why would I need to check Trigger.isBefore and Trigger.isInsert if the trigger is only on before insert?

 
I was looking at doing the Data Management - Importing Data challenge.

I can't seem to get the data importer to accept the CSV file. It gives the error:
contacts_to_import.csv
There was a problem uploading the CSV file. Try again, or choose another file.
User-added image

Looking the the Chrome developer console the following error appears when pressing the Next button:

User-added image

Refused to connect to 'https://na5.salesforce.com/_ui/core/dataimporter/servlet/DataImporterUploadServlet?encoding=ISO-8859-1' because it violates the following Content Security Policy directive: "connect-src 'self'".

Do I need to use a specific browser for the data importer?
I recently encountered an org with Apex classes and triggers that had dependencies on a third party managed package (http://salesforce.stackexchange.com/q/76791/102).

The Apex Classes and triggers had -meta.xml files like:
<?xml version="1.0" encoding="UTF-8"?>
<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>29.0</apiVersion>
    <packageVersions>
        <majorNumber>1</majorNumber>
        <minorNumber>1785</minorNumber>
        <namespace>loan</namespace>
    </packageVersions>
    <status>Active</status>
</ApexTrigger>
Note that it requires v1.1785 of the managed package with the loan namespace. The other triggers and classes had a range of minor versions, such as 1783, 1794 and 1795.

All of these were lower than the First Installed Version Number in the package details under installed packages.
Managed package first installed version less than required version.

As such, none of the affected Apex classes/triggers can be deployed/updated via the Metadata API without encountering the error:
triggers/foo.trigger-meta.xml -- Error: The specified Package Version number does not exist for that Package: loan, 1.1783

The affected triggers and classes can be successfully updated with the Tooling API, and hence the developer console.

This leaves a couple of questions:
  1. How did the org get into a state where there are Apex classes and triggers deployed that require a managed package version that isn't installed.
  2. Why isn't the Tooling API enforcing the managed package dependencies in the same way the metadata API is?
The example test case in Making an Asynchronous Callout from an Imported WSDL (https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_continuation_callout_soap.htm) doesn't work in practice.

Attempting to run tests using the pattern defined under Testing WSDL-Based Asynchronous Callouts gives the error:

<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; background-color: rgb(218, 240, 249);">
Methods defined as TestMethod do not support Web service callouts, test skipped

Attempting to use Test.setMock(WebServiceMock.class, xyz); doesn't work as the respose Map<String, Object> parameter is null. Without populating the mock response you get a GACK:
 
Internal Salesforce Error: 104340792-768952 (-1841369010) (-1841369010)

There is a complete example using a basic WSDL in Asynchronous Callout from an Imported WSDL (http://salesforce.stackexchange.com/q/70259/102)
I'm working through the Using Apex in Components (https://developer.salesforce.com/trailhead/force_com_programmatic_beginner/lightning_components/lightning_components_apex) challenge.

When checking the challenge I'm getting the response:
Challenge not yet complete... here's what's wrong: 
The client side controller is not using the return value from the 'getCaseFromId' method

If I put the same lightning component in an app I can see it is retrieving the Case details via the Apex controller method via the client controller.
Testing working Apex Component
I can see the call going through to the Apex Controller in the logs.
User-added image

I can put a debugger; statement in the client controller within the actions setCallback method and hit that immediately after passing the return value back to the records view attribute.

So I'm fairly certain that the client side controller is using the return value from `getCaseFromId` in the Apex controller.

Any ideas on what the challenge is checking for here?
The WSDL generated for an Apex Class method using the webservice keyword may be missing required complex types.

Take the example:
global class RetrieveOpportunity {
  webservice static Opportunity retrieveOpportunity(Id opportunityId) {
    return new Opportunity();
  }
}

This will generate a WSDL with elements like:
 
<xsd:element name="BillingAddress" minOccurs="0" type="tns:address" nillable="true"/>

The issue is that there is no address complex type in the WSDL tns namespace (http://soap.sforce.com/schemas/class/DFB/RetrieveOpportunity in this case).

This results in errors like:
Error: type 'address@http://soap.sforce.com/schemas/class/RetrieveOpportunity' not found.
Source - WSDL generated from apex can't import to SoapUI (http://salesforce.stackexchange.com/q/56005/102)
and
Error 1 Unable to import binding 'getLeadInfoBinding' from namespace 'http://soap.sforce.com/schemas/class/getLeadInfo'. App_WebReferences/WebReference/

Source - Issue with Adding reference Webservice WSDL to VS2010 (http://salesforce.stackexchange.com/q/53329/102)

The currently solution is to manually add the missing complex types to the xsd:schema with the required targetNamespace.
 
<!-- Compound datatype: Address -->
        <complexType name="address">
            <complexContent>
                <extension base="tns:location">
                    <sequence>
                        <element name="city" type="xsd:string"  nillable="true" />
                        <element name="country" type="xsd:string"  nillable="true" />
                        <element name="countryCode" type="xsd:string"  nillable="true" />
                        <element name="postalCode" type="xsd:string"  nillable="true" />
                        <element name="state" type="xsd:string"  nillable="true" />
                        <element name="stateCode" type="xsd:string"  nillable="true" />
                        <element name="street" type="xsd:string"  nillable="true" />
                    </sequence>
                </extension>
            </complexContent>
        </complexType>

<!-- Compound datatype: Location -->
        <complexType name="location">
            <sequence>
                <element name="latitude" type="xsd:double"  nillable="true" />
                <element name="longitude" type="xsd:double"  nillable="true" />
            </sequence>
        </complexType>

Can this be raised as an Apex API bug?
The current v32.0 (Winter 15) WSDL for the Tooling API is missing the SessionHeader in the binding operation definition for the getServerTimestamp web method. As such, attempts to call it from .NET generated proxy classes will be missing the Session header. This results in the following message:
 
 INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session
 
<operation name="getServerTimestamp">
   <soap:operation soapAction=""/>
   <input>
    <!-- This is currently missing
    <soap:header use="literal" part="SessionHeader" message="tns:Header"/>
    -->
    <soap:body use="literal" parts="parameters"/>
   </input>
   <output>
    <soap:body use="literal"/>
   </output>
  </operation>

Current work around is to manually force the Session Header to be sent in the generated proxy code.

It is also missing for the following operations which I suspect also require the Session details:
  • describeWorkitemActions
  • getDeleted
  • getUpdated
  • getUserInfo
  • logout
  • queryAll
  • queryMore
  • setPassword
I'm trying to send a SOQL query to the Tooling API (Soap version) to bring back the ApexExecutionOverlayResult records.

If I send the query:
Select Id, HeapDump from ApexExecutionOverlayResult

I get the result:
UNKNOWN_EXCEPTION: An unexpected error occurred. Please include this ErrorId if you contact support: 1377859780-46461 (1693774395)

The same issue occurs if I include any of these fields (which are typically the most interesting fields in the checkpoint output):
  • HeapDump,
  • ApexResult,
  • SOQLResult
Running the same query in the developer console against the Tooling API gives the same errors.

When trying to install an update for a managed package that I created into a clients Org the install failed with the message:

 

The first validation error encountered was "{0}"

 

    Problem - Validation Errors While Saving Record(s)

    Detail - There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "{0}".

 

How can I determine what caused this validation error and subsequent install failure? The detail message doesn't provide many clues.

 

The changes between this newest version and the previous one where mostly around the addition of new Validation Rules on Opportunity. The "{0}" in the details looks like the part where I should see some useful information, but the substitution hasn't occured.

 

I have raised this as a support case, but there is a 2 day wait before I get past the first level of support.

Can someone please verify that the following code is returning an incorrect line reference in the NullPointerException.

 

boolean nullReferenceBoolean = null;
List<long> listOfLongs = new List<long>();
for(integer i = 0; listOfLongs != null && i < listOfLongs.size(); i++) {
	System.debug(LoggingLevel.Debug, 'i:' + i + ' testLong:' + listOfLongs[i] + ' listOfLongs.size():' + listOfLongs.size());
}
if(nullReferenceBoolean) {
	System.assert(false, 'Expected Null Pointer Exception');
}
System.assert(false, 'Expected Null Pointer Exception');

I get the fatal error:

18:48:47.040 (40006000)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object
AnonymousBlock: line 3, column 1

I'd expect the error to be on line 6 and not 3.

 

The incorrect line number caused me to waste some time trying to debug the for loop rather than the next statement after it. The above is a greatly simplified version of the code I was working on so it wasn't immediately obvious what the issue was.

I've encountered a customers sandbox where the standard "Save" and "Save & New" buttons have been replaced by a "Save & Add Brand" button on the standard new opportunity page. They have renamed Opportunity Line Items as Brands and have renamed the Products tab as such.

 

When pressed, the button saves the Opportunity (after validation of required fields etc...) and then redirects the user to a custom Visualforce page for entering the Brand details. The Visualforce Page they arrive on is configured as the override for Opportunity Product standard button AddProduct.

 

Salesforce New Opportunity Page with custom Save Button

 

How has the "Save & Add Brand" button been added to the New Opportunity page to replace the standard buttons?

 

I need to add some additional buttons but can't find where it has been configured.

 

Under Customize > Opportunities > Buttons and Links > Standard Buttons and Links New is not showing any override. Also, if I add ?nooveride=1 to the URL I get the same page with the custom button. Edit has been overridden but that Visualforce page isn't the one being displayed to new (as expected).

 

There is no Detail Page Button on Opportunity with a label corresponding to this button.

 

The same question appears on Stack Overflow.

A couple of days ago I encountered an issue after running the apex test cases via the Apex Test Execution UI. Essentially, after trying to run all the test cases via the async functionality the Salesforce Org would have the Organization Administration Lock on and there was no way I could clear it.

 

As a result, any attempt to run another test case via the Apex Class UI would result in the message:

Organization Administration Locked

The changes you requested require salesforce.com to temporarily lock your organization's administration setup. However, the administration setup has already been locked by another change. Please wait for the previous action to finish, then try again later.

Trying to save an Apex Class from Eclipse would result in the message:

Save error: Unable to perform save on all files: The changes you requested require > salesforce.com to temporarily lock your organization's administration setup. However, the administration setup has already been locked by another change. Please wait for > the previous action to finish, then try again later. (ALREADY_IN_PROCESS)

Initially I asked about it on Stack Overflow - Salesforce stuck in Organization Administration Locked state after using Apex Test Execution.

 

The response I got was that this is happening to other developers as well and that I should raise a support case, which I did (originally 07109567and then 07109712 was created separately by the support team for some reason unknown to me).

 

After about 30+ hours of not being able to develop or test in the locked sandbox orgs one of them was unlocked by support. I was told there was a known issue and to only run the test cases via the individual Apex Class UI. I should avoid running the tests via the Apex Test Execution UI or the Run All Tests button.

 

At this stage I guess I'd like to know:

  1. What exactly is the known issue and where can I find the status of it?
  2. In the event that one of the several orgs I work on experiences the known issue what can I tell/ask support that will help them unlock it faster?

Hi,

 

A number of my test methods need to setup records for the required test scenarios. I’ll typically need to create Account, Contact, Opportunity, Product2, PricebookEntry, OpportunityLineItem and custom sObject records before the test scenario can be executed. Some of these records are configuration and typically wouldn’t change much in production.

 

The setup process can be expensive in terms of the Apex governor limits on SOQL queries as I have to first check the existing production configuration data to determine if the test records need to be inserted or not.

 

I tried updating the test case classes to API version 24.0 so that the test methods wouldn’t run with live production data (http://developer.force.com/releases/release/Spring12/test+data+access). However, I ran into a STANDARD_PRICE_NOT_DEFINED Exception when setting up the OpportunityLineItems (http://stackoverflow.com/questions/9164986/how-do-i-avoid-standard-price-not-defined-when-unit-testing-an-opportunitylineit).

 

I’ve also looked at wrapping the actual test case code within a Test.startTest() and Test.stopTest() but is has no effect on the governor limits (I’m not doing any future or batch jobs).

 

Is there a way I can perform the expensive test setup without pushing the SOQL query governor limit up before the actual test has started?

 

In the ideal world I'd be able to break the test scenario down into some smaller units but I'm not sure how that would work considering the number of prerequisites and no mocking framework.

 

I've added an idea for test setup functionality to be added to apex: Test method setup code with separate governor limits to the core test itself

I've inherited an application that uses custom Visualforce pages to perform actions when a user presses a custom button.

 

E.g. There is a custom button on Opportunity that links to the Visualforce page and passes a query string parameter. When the users GET request arrives at the visual force page an action is fired in the custom controller to a method. The method calls out to some web services and ultimately updates the database.

 

This opens the user up to CSRF issues with the GET request ultimately updating the database.

 

CSRF and apex:page and Apex and Visualforce Applications suggest changing the visualforce page and custom controller to using a apex:form and button to trigger the database updating action though a POST. This allows the inbuilt com.salesforce.visualforce.ViewStateCSRF to ensure the user triggered the action and help avoid CSRF issues.

 

However, this requires the user to perform an extra button press.

 

Is there an alternative approach I can use to safely perform the action from the button on Opportunity without opening up CSRF issues?

 

The same question has been posted on StackOverflow: CSRF safe Custom button linked to Apex method

I'm aware that when a managed package is deployed into an Org it is not possible to see log messages generated by apex code in that managed package.

 

 

However, Ideas: Display managed package logs in subscriber orgs is marked as "Delivered (Archive)".I couldn't find any documentation or direct link to what was delivered or how the issue was resolved.

 

Is there some new functionality delivered from the above idea that would allow me as the managed packaged creator to access the log messages?

I'm calling a web service that will return a Fault and FaultMessage(s) if there is an issue with the request. E.g.

 

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode>s:Client</faultcode>
      <faultstring xml:lang="en-US">The creator of this fault did not specify a Reason.</faultstring>
      <detail>
        <DataAccessFault xmlns="http://www.example.com/api" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <FaultMessges xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
            <a:string>Validation Error(s) occurred during Save.</a:string>
            <a:string>Meaningful error message appears here</a:string>
          </FaultMessges>
          <FaultObjectType>Order</FaultObjectType>
          <FaultOperationType>Insert</FaultOperationType>
        </DataAccessFault>
      </detail>
    </s:Fault>
  </s:Body>
</s:Envelope>

 When this gets handled by Apex it gets turned into a CalloutException:

 

System.CalloutException 
  Cause: null 
  Message: Web service callout failed: WebService returned a SOAP Fault: The creator of this fault did not specify a Reason. faultcode=s:Client faultactor= 

 The issue I have is that the getMessage() method doesn't return the entire SOAP reponse. It has been truncated before the useful information appears.

 

Is there some way to recover the entire response from the CalloutException in code so I can give a meaning error back to the user?

 

Currently I need to resort to capturing the Outbound SOAP message and response using the third party tool like soapUI. While this works for debugging, it doesn't help the users during normal usage.

 

Related: This post from 2009 seems to be dealing with the same issue but has not resolution - CalloutException: Problem with contents of fault detail?

Using describeGlobal() I can confirm ContentVersion and ContentDocument are available as objects for the current organization.

 

Using describeSObject() I can confirm that the the current users session marks ContentVersion as createable. I've also confirmed that the fields I'm setting when inserting the ContentVersion record are marked as createable (PathOnClient, VersionData and FirstPublishedLocationId).

 

In my test cases, if the user has access to the Content area via the Salesforce web interface then the test case passes with the ContentVersion being created.

 

However, when I try the same code from a developer edition org (without access to the Content area) it falls over with the message:

FIELD_INTEGRITY_EXCEPTION - User doesn't have access to Salesforce Content. Invalid field value:: Content Origin

The createable Partner API metadata for ContentVersion and the fields indicated that this should have worked.

 

I've tried checking ContentDocument.creatable, but this is false even for users who can otherwise create Content.

 

I'm working in C#, but the Java code in recipe Publishing Documents Into a Salesforce CRM Content Personal Workspace is doing much the same thing without the creatable metadata checks.

The output of the Apex String.format function doesn't seem correct when the format string contains an escaped single quote.

 

E.g. Executing the following Anonymous code in Eclipse

 

 

String formattedString = String.format('Hello {0}, \' shall we play a {1}', new String[]{'David', 'game'});
System.debug(formattedString);
System.debug('before \' after');

 

 

System.debug(formattedString) results in
Hello David,  shall we play a {1}

 

Rather than the expected

Hello David, ' shall we play a game

 

Is this a bug/feature of String.format?

 

I've had a colleague reproduce this issue in a separate install of Eclipse and also seen it with a Chatter FeedPost created by a trigger.

I'm attempting to set the value of a custom field on the ContentVersion using the partner API.

 

The following error is being returned:

 

0: Error FIELD_INTEGRITY_EXCEPTION - You cannot set the following custom fields: CustomFieldName__c. Please add them to the page layout for the record type: Default Content Type

 

How do I add this custom field to the page layout for the default content type?

 

I'm working through Apex & .NET Basics - Understanding Execution Context

When validating the challenge I'm getting the error:
 
Challenge Not yet complete... here's what's wrong: 
The Trigger 'AccountTrigger' does not appear to be calling the AccountTriggerHandler class correctly or using isBefore or isInsert content variables.

The trigger I currently have is minimal:

trigger AccountTrigger on Account (before insert) {
    AccountTriggerHandler.CreateAccounts(Trigger.new);
}

Why would I need to check Trigger.isBefore and Trigger.isInsert if the trigger is only on before insert?

 
The WSDL generated for an Apex Class method using the webservice keyword may be missing required complex types.

Take the example:
global class RetrieveOpportunity {
  webservice static Opportunity retrieveOpportunity(Id opportunityId) {
    return new Opportunity();
  }
}

This will generate a WSDL with elements like:
 
<xsd:element name="BillingAddress" minOccurs="0" type="tns:address" nillable="true"/>

The issue is that there is no address complex type in the WSDL tns namespace (http://soap.sforce.com/schemas/class/DFB/RetrieveOpportunity in this case).

This results in errors like:
Error: type 'address@http://soap.sforce.com/schemas/class/RetrieveOpportunity' not found.
Source - WSDL generated from apex can't import to SoapUI (http://salesforce.stackexchange.com/q/56005/102)
and
Error 1 Unable to import binding 'getLeadInfoBinding' from namespace 'http://soap.sforce.com/schemas/class/getLeadInfo'. App_WebReferences/WebReference/

Source - Issue with Adding reference Webservice WSDL to VS2010 (http://salesforce.stackexchange.com/q/53329/102)

The currently solution is to manually add the missing complex types to the xsd:schema with the required targetNamespace.
 
<!-- Compound datatype: Address -->
        <complexType name="address">
            <complexContent>
                <extension base="tns:location">
                    <sequence>
                        <element name="city" type="xsd:string"  nillable="true" />
                        <element name="country" type="xsd:string"  nillable="true" />
                        <element name="countryCode" type="xsd:string"  nillable="true" />
                        <element name="postalCode" type="xsd:string"  nillable="true" />
                        <element name="state" type="xsd:string"  nillable="true" />
                        <element name="stateCode" type="xsd:string"  nillable="true" />
                        <element name="street" type="xsd:string"  nillable="true" />
                    </sequence>
                </extension>
            </complexContent>
        </complexType>

<!-- Compound datatype: Location -->
        <complexType name="location">
            <sequence>
                <element name="latitude" type="xsd:double"  nillable="true" />
                <element name="longitude" type="xsd:double"  nillable="true" />
            </sequence>
        </complexType>

Can this be raised as an Apex API bug?
I'm really stuck on this one.

For the first part I have:
torch.manual_seed(123)

# TODO: Generate 2 clusters of 100 2d vectors, each one distributed normally, using
# only two calls of randn()
classApoints = torch.randn(100,2)
classBpoints = torch.randn(100,2)
#println(classApoints)

# TODO: Add the vector [1.0,3.0] to the first cluster and [3.0,1.0] to the second.
classApoints += torch.tensor([1.0,3.0])
classBpoints += torch.tensor([3.0,1.0])
#println(classApoints)

# TODO: Concatenate these two clusters along dimension 0 so that the points
# distributed around [1.0, 3.0] all come first
inputs = torch.cat([classApoints, classBpoints],0)
#println(inputs) - I suspect U might be missing something in here but I'm not certain

# TODO: Create a tensor of target values, 0 for points for the first cluster and
# 1 for the points in the second cluster. Make sure that these are LongTensors.
classA = classApoints.zero_().long()
classB = classBpoints.fill_(1).long()
targets = torch.cat([classA, classB])
#println(targets.type()) - pretty sure this is correct and I've confirmed they are LongTensors

For the 2nd part (where I'm having error) I've got:
# TODO: Set the random seed to 123 using manual_seed
torch.manual_seed(123)


# TODO: Initialize a Linear layer to output scores 
# for each class given the 2d examples
model = nn.Linear(2, 2)

# TODO: Define your loss function
loss_fn = nn.NLLLoss()

# TODO: Initialize an SGD optimizer with learning rate 0.1
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

# Train the model for 100 epochs 
n_epochs = 1
losses = []
for _ in range(n_epochs):
  optimizer.zero_grad() 
  preds = model(inputs)
  #println(preds)
  #println(targets)
  loss = loss_fn(preds, targets)
  losses.append(loss)
  loss.backward()
  optimizer.step()
print(f'Anwswer to Exercise 6: Loss after {n_epochs} epochs: {losses[-1]}')
      
iterations = np.arange(len(losses))
_ = plt.plot(iterations, losses, '', iterations, losses, '-')

The error I'm getting:
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-65-b59a439a8791> in <module>() 20 #println(preds) 21 #println(targets) ---> 22 loss = loss_fn(preds, targets) 23 losses.append(loss) 24 loss.backward() /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 489 result = self._slow_forward(*input, **kwargs) 490 else: --> 491 result = self.forward(*input, **kwargs) 492 for hook in self._forward_hooks.values(): 493 hook_result = hook(self, input, result) /usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py in forward(self, input, target) 191 _assert_no_grad(target) 192 return F.nll_loss(input, target, self.weight, self.size_average, --> 193 self.ignore_index, self.reduce) 194 195 /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce) 1330 .format(input.size(0), target.size(0))) 1331 if dim == 2: -> 1332 return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce) 1333 elif dim == 4: 1334 return torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce) RuntimeError: multi-target not supported at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:22

Can anyone assist on this?
  • December 28, 2018
  • Like
  • 0
Hello,

I am working with email services,
Sometimes the email sending is not correct, receiptdoenst receive email or not attached to correct oject.

Howcani debug the issue ?

thank you for suggestions
  • December 14, 2018
  • Like
  • 0
Hi, first timer here :)
We are at our wits end, have set up Platform Events with a CometD client. Getting "You have exceeded your daily limit" message even though according to our monitoring we have around 2000 daily events, nothing like the stated 50,000. Getting no joy from Salesforce support on this.
(I am also going to post another related question - related to the supposed 24 hour life span of a message - we are finding the Message Id cannot be retrieved after a few hours).
Many thanks
I'm trying to limit the user when they use a botton to only be able to have one record if they don't have any other records in the status of "New". 


global with sharing class RetrieveNextUtils {
    webService static Id retrieveNextCase(String userId)
    {
        //Here I'm looking to see if the current user has any leads in Lead Status containing New
        
        
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
            //Find an open case that is assigned to one of those queues
            Case caseObj = [select c.Id,c.OwnerId from Case c where 
                                                        c.IsClosed=false 
                                                        and c.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (caseObj!=null) {        
                //If we found one, assign it to the current user
                caseObj.OwnerId = userId;
                update caseObj;
                
                return caseObj.Id;
            }
        }
        
        return null;
    }
    
    webService static Id retrieveNextLead(String userId)
    {
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
        
            
            //Find an open lead that is assigned to one of those queues
            List<Lead> leads = [select l.Id,l.OwnerId from Lead l where 
                                                        l.IsConverted=false 
                                                        and l.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (leads.size()>0) {       
                //If we found one, assign it to the current user
                leads[0].OwnerId = userId;
                update leads;
                
                return leads[0].Id;
            }
        }
        
        return null;
    }
    
    //Returns a list of ids of queues that this user is a member of
    public static List<Id> getQueuesForUser(String userId) 
    {
        List<Id> listGroupIds = new List<Id>();
        List<GroupMember> listGroupMembers = [Select g.GroupId From GroupMember g 
                                                where g.Group.Type='Queue'
                                                and g.UserOrGroupId=:userId];
                                                
        if (listGroupMembers!=null && listGroupMembers.size()>0) {      
            for (GroupMember gm:listGroupMembers) {
                listGroupIds.add(gm.GroupId);
            }
        }
        
        return listGroupIds;
    }
    
    
        
   
}
Hi All, I've been struggling with this issue and couldn't find the solution

I'm trying to use SOPAUI to try some Webservices I made but whenever i create a project from the enterprise WSDL I get this error
 
Error: type 'AdditionalInformationMap@urn:enterprise.soap.sforce.com' not found.

I looked everywhere and the only thing I can think of doing is adding the type myself but not sure how.

Appreciate the help

 

Hi All!

I was attempting the "Build Flexible Apps with Visualforce Pages and Lightning Components" trailhead project but I am unable to install the package that the require to be installed prior to beginning. When i go to install the package, I recieve the errors below. I verified that it is installing into my "Hands-On Org" and I even attempted creating a new Trailhead org and the same issues persists. 

Method does not exist or incorrect signature: void setCurrentPage(System.PageReference) from the type test
DreamhouseTests: Method does not exist or incorrect signature: void setCurrentPage(System.PageReference) from the type test

Method does not exist or incorrect signature: void isRunningTest() from the type test
GetPropertiesApexController: Method does not exist or incorrect signature: void isRunningTest() from the type test

Apex class 'GetPropertiesApexController' does not exist
Similar_Properties: Apex class 'GetPropertiesApexController' does not exist


Does anyone have any ideas what I might have to do to fix this. Sorry if there has been an answer posted already, I couldn't seem to find one.

Thank you,

Michael

We are trying to install "Force.com IDE 2. The Eclipse IDE plug-in for Salesforce DX" and we follow all the steps include in the guide:
https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_intro.htm

But when I try to 'Pull the Source' an error ocurred:
    Operation Failed

    MemberName, IsNameObsolete FROM SourceMember WHERE RevisionNum >
                                ^
    ERROR at Row:1:Column:52
    sObject type 'SourceMember' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.


And there is no way to continue.
I'm attempting to retrain an evisting vision model using additional feedback. I've also tried creating a new model for the dataset.

In both cases I was using a trainParams of:
'{"withFeedback": true}'
The existing model has a SUCCEEDED status but shows no sign that the feedback was incoperated.

The new model ends up with the failureMsg:
"java.lang.IllegalArgumentException: The dataset example referenced examples/1010273-4e2abc4183fd732aae779a1a3a3cb088de02898ec2fce61aee921df31675a676 does not exist"
Has something got corrupted within my dataset? Should I just start again with a new dataset?
 
I am updating a lead via API using a python script. Lead assignment rule fire and reassign lead eveytime the script updates the lead record. Any idea why this is happening? It is only if this particular integration updates a lead that they re-fire. We have no functionality causing them to fire upon edit and there is nothing in the integration that is specifically saying they should fire.
I need to use a Salesforce user (username and password) to get a token. This token should be validated by a 3rd party software and Salesforce userid should be extracted from it. I have already realized this stuff using OpenID connect, but I would avoid redirection back and forth typical of OIDC.

I have read that I could achieve this goal using SOAP API (in place of OIDC), and I have some related questions:
  1. Is this true? Can I authenticate a user with SOAP endpoint without any redirect?
  2. If 1. is true: what type of token did I get? Can I validate it against a known salesforce endpoint (e.g. with OIDC I have /id/keys API endpoint for key validation)
  3. If 1. is true: how long is this token valid? It is a sort of one time password or this token has a time to live like a common JWT?
  4. (aka 3 bis) Can I refresh this token?
  5. Are SOAP API actively supported by Salesforce or this API should be not implemented in favour of OIDC Rest API?
In a broader sense: What are pros and cons of both types of authentication?

Hi, I am working on an application built on top of salesforce. We are pulling the metadata in and dynamically rendering the ui based on the metadata. Recently, there was a change to an api field name on a lead listview field. The field name was changed from 'Owner.Alias' to 'Owner.NameOrAlias'. I was wondering if this was possibly a mistake on the part of salesforce during the release of v40.0 of the api or if this is a more common occurance that I will need to account for in the application.

Thanks!

I need to upsert multiple records of the same type/object with one REST API call. 

I see how to upsert one record (https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm), but not how to upsert multiple. 

With the composite resources I see how to update or insert multiple records, but not how to upsert.

Is it possible to upsert multiple records? 
 
Hello,

Firs problem is that data from "Setup"->"System Overwiev" doesn't always match to "Reports"->"Admin***"-> "API Calls Made Within Last 7 Days" and a couple times already we exceeded 24h limit firstly 40k by the next day 60k our normal api usage was 25K with no sign to growth that quickly.

The was a similar question regarding this counter but it doesn't look like we are using bulk api that extensive.

Second weird things about it is that counter not only growth but some times it show lower value then it was like an hour ago (this is not a daily counter drop for sure)

I've seen counter values 61->60->59->55->56->58->54

So maybe someone already faced with that and maybe have the solution to that
 
Our Enterprise WSDL undergone some changes due to new fields in a table. So, we removed the Web Service reference in .NET project and deleted and added back. It's now throwing the below error in the line _sForceRef.login(SalesForce_User, SalesForce_Password & SalesForce_Token) as follows.

An unhandled exception of type 'System.StackOverflowException' occurred in Microsoft.GeneratedCode

The same code works good in another laptop, but I tried in both VS 2013 and 2015 and I get same error. Please help.

'New line added for SalesForce TLS changes
System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)

Dim wp As WebProxy = New WebProxy("cwybcproxy.us.dnb.com", 8080)
wp.BypassProxyOnLocal = False
_sForceRef.Proxy = wp

_loginResults = _sForceRef.login(SalesForce_User, SalesForce_Password & SalesForce_Token)

_sessionId = _loginResults.sessionId
_sForceRef.Url = _loginResults.serverUrl
_sForceRef.SessionHeaderValue = New SessionHeader()
_sForceRef.SessionHeaderValue.sessionId = _sessionId
Hi All,

While I am checking my Visualforce execution time line, I saw this two event in the log which takes more time in Visualforce.
I want to know what exactly it is and which part of the controller code is resposible for this.

Attached the log for the reference
User-added image
I use the following URL to access our production soap api: https://www.salesforce.com/services/soap/u/18.0 
I would like to know what is the URL to access the soap api in the sandbox. I tried adding the sandbox server to the URL https://cs26.salesforce.com/services/soap/u/18.0 but that did not work. Any suggestions? 
Hi,

I a very simple case that I'm surprised Salessforce migration tool can't deal with.

I have two date fields on Account: Open and Closed.

I then have a formula field that sets a boolean to true if today is between Open and Closed.

These are stored in an unmanaged package.

So far so good. But when  Itry and destroy these changes (rename package.xml to destructiveChanges.xml, create empty package.xml) I get the following error:

1.  objects/Account.object (Account.Open_Date__c) -- Error: This custom field is
 referenced elsewhere in salesforce.com. : Custom Formula Field - Account.Active
__c.

But my destructiveChanges should destroy all fields incluved, the date fields and related formula.

Do I have to bash out staged destructions, ie figure out which fields are formula fields, destroy those, then destroy other fields? These seems horrible and I was hoping the tool would be smart enough to recognise that the destruction is selft contained.

The Winter 15 API has a change to the SOQL SELECT statement (https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select.htm) that allows multiple FROM objects, but no description is given for the change.

FROM objectType[,objectType...]

The error message received indicates that it's to be used with related objects:

ERROR at Row:1:Column:21
A driving SObject type has already been set, all other entity types in the FROM clause must be relationships to the initial object.  The driving object is Case.

Can we get a description of this new syntax, or correct the docs if this is something hinted before release?  The only matching forum post was from a new dev trying to do the usual but misled by the doc bnf.

I'm trying to limit the user when they use a botton to only be able to have one record if they don't have any other records in the status of "New". 


global with sharing class RetrieveNextUtils {
    webService static Id retrieveNextCase(String userId)
    {
        //Here I'm looking to see if the current user has any leads in Lead Status containing New
        
        
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
            //Find an open case that is assigned to one of those queues
            Case caseObj = [select c.Id,c.OwnerId from Case c where 
                                                        c.IsClosed=false 
                                                        and c.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (caseObj!=null) {        
                //If we found one, assign it to the current user
                caseObj.OwnerId = userId;
                update caseObj;
                
                return caseObj.Id;
            }
        }
        
        return null;
    }
    
    webService static Id retrieveNextLead(String userId)
    {
        //Really we're only specifying the user ID for the sake of the test methods
        if (userId=='') {
            //Use the currently running user
            userId = UserInfo.getUserId();
        }
        
        //First find out which queues this user is a member of
        List<Id> listGroupIds = getQueuesForUser(userId);
        
        if(listGroupIds.size()>0) 
        {
        
            
            //Find an open lead that is assigned to one of those queues
            List<Lead> leads = [select l.Id,l.OwnerId from Lead l where 
                                                        l.IsConverted=false 
                                                        and l.OwnerId in :listGroupIds 
                                                        limit 1 
                                                        for update];
                                                
            if (leads.size()>0) {       
                //If we found one, assign it to the current user
                leads[0].OwnerId = userId;
                update leads;
                
                return leads[0].Id;
            }
        }
        
        return null;
    }
    
    //Returns a list of ids of queues that this user is a member of
    public static List<Id> getQueuesForUser(String userId) 
    {
        List<Id> listGroupIds = new List<Id>();
        List<GroupMember> listGroupMembers = [Select g.GroupId From GroupMember g 
                                                where g.Group.Type='Queue'
                                                and g.UserOrGroupId=:userId];
                                                
        if (listGroupMembers!=null && listGroupMembers.size()>0) {      
            for (GroupMember gm:listGroupMembers) {
                listGroupIds.add(gm.GroupId);
            }
        }
        
        return listGroupIds;
    }
    
    
        
   
}
Hi,
   I have downloaded the MetadataAPI (37.0) and saved it as a xml file and referenced it in .NET ,but there are some mismatch.As per version 37.0 of MetadataAPI ,the createMetaData should accept 1 parameter whereas it is accepting 4 parameters.
  The ReadMetaData Function should return "ReadResult" ,whereas I couldnt find ReadResult in my reference.cs. Plz help me out.
Dnt know why there is a mismatch between the wsdl and the reference,cs
Bug is documented at http://www.fishofprey.com/2014/10/importing-salesforce-winter-15-partner.html

This has been present since Fall 2014.

When the wsdl is converted into a .Net web service, the ListViewRecordColumn is now defined in .Net at `typeof(ListViewRecordColumn)` instead of `typeof(ListViewRecordColumn[])`. 

This will result in the following errors appearing unless it is manually corrected in the generated c#
  • System.InvalidOperationException: Unable to generate a temporary class (result=1).
  • error CS0029: Cannot implicitly convert type 'XYZ.SalesforcePartner.ListViewRecordColumn' to 'XYZ.SalesforcePartner.ListViewRecordColumn[]'
I have been succesfull in creating REST code to make Invocable Actions APIs however I was wondering to do same for SOAP API's and i could not find suitable methods in SOAP API document.

REST API: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_actions_invocable.htm
where can I get info on corresponding API's on SOAP version?
Has salesforce opted out from SOAP for Invocable Action API's?
Was trying to file a case for support to make sure this is a bug, but was pushed here instead. 

Below is a simple snippet, that can be run in a spring'16 developer org, which reproduces a System.NoDataFoundException. The test class was designed to create a number of notes, set the created date in the past, and then run a batch apex to remove notes created past a certain date. When trying to run the class, the exception is generated. The account created in the snippet does not generate the same exception. 
@isTest
public class NoteCleanUp_Test {
    
    @isTest
    public static void CleanUp_Test() {
        Account testAccount = new Account();
        
        testAccount.Name = 'Test Account';
        
        insert testAccount;
        
        System.assertNotEquals(null, testAccount.Id);
        
        Note testNote = new Note();
        
        testNote.Title = 'Test Account Note';
        testNote.Body = 'Test Account Note Body.';
        testNote.ParentId = testAccount.Id;
        
        insert testNote;
        
        System.assertNotEquals(null, testNote.Id);
        
        Test.setCreatedDate(testAccount.Id, DateTime.now().addMonths(-6));
        Test.setCreatedDate(testNote.Id, DateTime.now().addMonths(-6));
        
        Test.startTest();
        
        System.assert([SELECT COUNT() FROM Note] > 0);
        
        Test.stopTest();
	}
}

The above code will generate the exception:
System.NoDataFoundException: The sObject with the ID 00261000003I5rmAAC isn’t part of this transaction. Provide the ID of an sObject that this test method created.

With a stack trace of:
Class.System.Test.setCreatedDate: line 81, column 1
Class.NoteCleanUp_Test.CleanUp_Test: line 25, column 1

I've also posted this on the salesforce stackexchange network, which you can view here: http://salesforce.stackexchange.com/questions/117473

I'd really like either someone to confirm that yes, this is in fact a bug, or for someone to point out a error in the above code to allow me to write a test class without using a workaround (such as those specified on the linked stackexchange question).
We are working on using SOAP API of Salesforce to create some custom object records. It is working fine in our Developer and Test envournment. However, as soon as we deploy this on production we get this error. This is very strange as all our envoirnemnt as similar in terms of configurations and web access. 

We have checked the following 
Custom Object is in "Deployed" status
Sharing is enabled for the custom object
Generated WSDL from production server and now using it
Please ntote, same solution workst from test and development server
Can anyone point us in right direction as to what can be wrong? Thanking in anticipation.
Hi,

We are using Talend middleware to integrate and exchange data between our internal systems and SF using SF API. The SF CRM is acting as a 'slave' while our system database is a master.  So, almost every object in SF has an external ID that maches the record in our DB. 

All our 'upserts' works fine when matched on External ID. But in this case, we need to update - not upsert - the record in SF using External ID, which is marked as unique in SF. 

But, when runing the code this is the error: MISSING_ARGUMENT:Id not specified in an update call - for every single record regardles if the External ID already exist in SF or not.

So, my question is - can update be done on External ID or it must be the SF Id ?

Thanks


 

I have a contact form on a client's website that uses the web-to-lead feature to add a lead to SalesForce. The post is done via a .NET server post. This was working fine until recently when it just sort of stopped working. The weird thing is that it still works using the basic form that is auto-generated from the SF admin (just running locally in a browser), even when I customize that form so that the fields are exactly the same as my .NET form. I added the debug=1 parameter in both cases, and in both cases, I am getting the exact same response. But the requests from the basic form are going into SF while the requests from the .NET form are not, though in debug mode it is not returning anything that looks like an error. I'm not sure if this could be related, but one thing that I did notice with the auto-generated form is that (though it does go through) the page it posts to has HTTPS crossed out in Google Chrome with a message that says, "Your connection to this site is not private because the site loaded an insecure script."

Below is the .NET code I am using:

string postURL = "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
                NameValueCollection postData = new NameValueCollection();
                postData.Add("oid", "00Dd0000000enW3");
                postData.Add("retURL", "http://www.cheetahchassis.com");
                postData.Add("first_name", model.FirstName);
                postData.Add("last_name", model.LastName);
                postData.Add("email", model.Email);
                if (!string.IsNullOrEmpty(model.Phone))
                {
                    postData.Add("phone", model.Phone);
                }
                if (!string.IsNullOrEmpty(model.Company))
                {
                    postData.Add("company", model.Company);
                }
                postData.Add("city", model.City);
                postData.Add("00Nd00000051cEi", model.State);
                postData.Add("description", model.Message);
                postData.Add("lead_source", "Cheetah Website");
                postData.Add("debug", "1");
                postData.Add("submit", "Submit");
                if (!string.IsNullOrEmpty(model.Subject))
                {
                    postData.Add("00Nd0000006ddpY", model.Subject.Substring(4));
                }

                WebClient http = new WebClient();
                try
                {
                    http.Encoding = Encoding.UTF8;
                    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11;
                    http.UploadValues(postURL, "POST", postData);
                    TempData["mailMessage"] = "success";
                }
                catch (Exception ex)
                {
                    TempData["mailError"] = ex.Message;
                }
When I look at the http.UploadValuse result (converted from a byte array to a string) in the debugger, I get what looks like a standard redirect page or a list of name value pairs exactly the same as with the form below (if debug=1). And here is the modified version of the auto-generated form that is working.
 
<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: Please add the following <META> element to your page <HEAD>.      -->
<!--  If necessary, please modify the charset parameter to specify the        -->
<!--  character set of your HTML page.                                        -->
<!--  ----------------------------------------------------------------------  -->

<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">

<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: Please add the following <FORM> element to your page.             -->
<!--  ----------------------------------------------------------------------  -->

<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">

<input type=hidden name="oid" value="00Dd0000000enW3">
<input type=hidden name="retURL" value="http://www.cheetahchassis.com">
<input type=hidden name="lead_source" value="Cheetah Website">
<!--<input type=hidden name="debug" value="1">-->

<!--  ----------------------------------------------------------------------  -->
<!--  NOTE: These fields are optional debugging elements. Please uncomment    -->
<!--  these lines if you wish to test in debug mode.                          -->
<!--  <input type="hidden" name="debug" value=1>                              -->
<!--  <input type="hidden" name="debugEmail" value="rreid@diamatrix.net">     -->
<!--  ----------------------------------------------------------------------  -->

<label for="first_name">First Name</label><input  id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>

<label for="last_name">Last Name</label><input  id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>

<label for="email">Email</label><input  id="email" maxlength="80" name="email" size="20" type="text" /><br>

<label for="company">Company</label><input  id="company" maxlength="40" name="company" size="20" type="text" /><br>

<label for="city">City</label><input  id="city" maxlength="40" name="city" size="20" type="text" /><br>

<label for="state">State/Province</label><input  id="state" maxlength="20" name="00Nd00000051cEi" size="20" type="text" /><br>

<textarea id="description" name="description"></textarea>

<input type="submit" name="submit">

</form>

 
Hi Everyone,

I am having some trouble with my .net integration with my salesforce org. Namely the first connection to through the API.

The first connection can take anywhere from 8 - 12 seconds which is quite a while considering its a simple lead creation form, after making the initial connection the interaction with my API is quite fast. I have searched everywhere for a solution to this problem and come up with nothing.

Any suggestions?
Salesforce API response to /listViews/id/describe returns an incorrect query when both lead and campaign member filters on status field are used. Anyone else seen this behavior?

Here's our workflow
  1. Our software makes a call to /services/data/v36.0/sobjects/Lead/listviews/00BU0000003VsoeMAC/describe, where  00BU0000003VsoeMAC is a leads list ID
  2. The response from Salesforce includes a "query" like SELECT FirstName, LastName, Company, Email, Phone, Title, toLabel(Status), CreatedDate, Owner.Alias, Id, LastModifiedDate, SystemModstamp FROM Lead WHERE IsConverted = false AND Id IN (SELECT LeadId FROM CampaignMember WHERE CampaignId = '701U0000001XvK1') AND Status != 'Invited' AND Owner.FirstName = 'KC' AND Status != 'Open' AND Email != null AND Status != 'Attended' ORDER BY FirstName ASC NULLS FIRST, Id ASC NULLS FIRST
  3. Our software url-encodes this query and makes a GET to Salesforce to this url - /services/data/v36.0/query/?q=<encoded query>
  4. Salesforce responds, and our software parses the results into a list of contact records
This workflow has been failing for lead lists with multiple filters on status. For instance, we have one lead list that has filters on both lead status and campaign status.

 Here's the query returned to us by Salesforce in step #2 above -
SELECT FirstName, LastName, Company, Email, Phone, Title, toLabel(Status), CreatedDate, Owner.Alias, Id, LastModifiedDate, SystemModstamp FROM Lead WHERE IsConverted = false AND Id IN (SELECT LeadId FROM CampaignMember WHERE CampaignId = '701U0000001XvK1') AND Status != 'Invited' AND Owner.FirstName = 'KC' AND Status != 'Open' AND Email != null AND Status != 'Attended' ORDER BY FirstName ASC NULLS FIRST, Id ASC NULLS FIRST


There are three filters on "Status" here, all of which get applied to the lead object:
  1. Status != 'Invited'
  2. Status != 'Open'
  3. Status != 'Attended'

The actual list definition has an Open filter on Lead Status and the other two (Invited/Attended) on Campaign Member Status. But in the query, the Status filter on Campaign Member doesn't seem to filtering in the Campaign Member part of the query. As a result, the query execution (step #4 above) returns us leads that are not part of the selected list since all of the status filtering is being done on leads, and not campaign member as it was meant to be. The list view in the UI shows the correct/expected data. It is the API that is not returning the expected data. 

We see a bug in the query and this is how it should have been - 

SELECT FirstName, LastName, Company, Email, Phone, Title, toLabel(Status), CreatedDate, Owner.Alias, Id, LastModifiedDate, SystemModstamp FROM Lead WHERE IsConverted = false AND Id IN (SELECT LeadId FROM CampaignMember WHERE CampaignId = '701U0000001XvK1' AND Status != 'Invited' AND Status != 'Attended')  AND Owner.FirstName = 'KC' AND Status != 'Open' AND Email != null ORDER BY FirstName ASC NULLS FIRST, Id ASC NULLS FIRST

If you notice, in our query above, Invited/Attended status clause has been made part of the CampaignMember select sub query whereas Open filter check is grouped in the where clause on the Leads table select statement.

Hoping someone here proposes a solution/workaround for this, or if it indeed is a bug, have it fixed for us :)

Thanks!
Manjusha
 

As part of an SOAP integration I'm doing. I've requirement where I need to pass the BinarySecurityToken in the header of the SOAP request. Unfortunately the WSDL will not contain the header information, so wsdl2apex convertor will not generate the associated Header classes.I've included the below snippet which is not working and erroring out as 'System.CalloutException: IO Exception: input contained no data'

I've added below two classes in the Webservice stub class that's generated-

    public class Security_element{ 
        public Security_element(String securityToken){
            this.securityToken = new BinarySecurityToken_element(securityToken);
            this.wsse = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
        }
        
        public BinarySecurityToken_element securityToken;
        public String wsse;
        private String[] wsse_att_info = new String[] {'xmlns:wsse'};
        private String[] securityToken_type_info = new String[]  {'wsse:BinarySecurityToken','http://www.w3.org/2001/XMLSchema','element','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
        private String[] field_order_type_info = new String[]{'securityToken'};
    }
    
    public class BinarySecurityToken_element {
    
        public BinarySecurityToken_element(String securityToken) { 
             this.securityToken=securityToken;
             this.myValueType='wsse:X509v3';
             this.myEncodingType='wsse:Base64Binary'; 
             this.myID='X509Token';
        }
        public String securityToken;
        public String myValueType;
        public String myEncodingType;
        public String myID;
        
        private String[] securityToken_type_info = new String[]{'wsse:BinarySecurityToken','http://www.w3.org/2001/XMLSchema','element','1','1','false'};   
        private String[] myValueType_type_info=new String[]{'ValueType'};
        private String[] myEncodingType_type_info=new String[]{'EncodingType'};
        private String[] myID_type_info=new String[]{'Id'};
        private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
        private String[] field_order_type_info = new String[]{'securityToken'};              
    }

******************This will go to class that makes the callout*************************

List docList = [select id, name,Body from document where name = 'secToken.txt']; //Docuement contains the security token I need to pass in the header
public wsSampleProjectV1.Security_element sec = new wsSampleProjectV2.Security_element(EncodingUtil.base64Encode(docList[0].body));
private String sec_hns = 'Security=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; 

*********SOAP Request Header that I need to pass is -

  <soapenv:Header>
      <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:BinarySecurityToken ValueType="wsse:X509v3" EncodingType="wsse:Base64Binary" Id="X509Token">
                ---Encoded BinarySecurityToken goes here------
 
         </wsse:BinarySecurityToken>
      </wsse:Security>
      
   </soapenv:Header>

Any help on what's going wrong is much appreciated.
Good afternoon,
I have tried to use the code above but i receive this error:
e.Message = "There was an error in serializing one of the headers in message loginRequest: 'Unable to generate a temporary class (result=1).\r\nerror CS0030: Cannot convert type 'SF_Connector1.SoapApi.ListViewRecordColumn[]' to 'SF_Connector1.SoapApi.ListViewRecordColu... etc.
Googling around i found some answers to that "generic" error saying there is an dimensional array mismatch, but i have been unable to apply the suggested corrections.
I reduced the code to the very minimal section oflogin but the bug appears into the line

lr = ss.login(Nothing, "hello@hello.com.au", "Yourpassword" & "Security Token")

Of course i replaced the variable with my own login data.
Anyone can help?
This is the very last part i have to implement in my procedure and begin to be very frustrated for the impossibility to do it.
Thank you in advance.
PS, i am using VS2015, vb.net,  net framework 3.5
Claudio
I am trying to automate a data load using the Command Line tools and have everything working smoothly but it is taking 10x longer than if I do it through the Data Loader GUI.

Below is an exert from my process-conf.xml

>     <bean id="csvUpsertOrderItem"
>           class="com.salesforce.dataloader.process.ProcessRunner"
>           singleton="false">
>         <description>Upsert Transaction Headers into Orders standard object.</description>
>         <property name="name" value="csvUpsertOrderItem"/>
>         <property name="configOverrideMap">
>             <map>
>                 <entry key="sfdc.debugMessages" value="false"/>
>                 <entry key="sfdc.endpoint" value="CUSTOM ENDPOINT"/>
>                 <entry key="sfdc.username" value="USERNAME"/>
>                 <entry key="sfdc.password" value="ENCRYPTED PASSWORD"/>
>                 <entry key="process.encryptionKeyFile" value="C:\Program Files (x86)\salesforce.com\Data Loader\bin\key.txt"/>
>                 <entry key="sfdc.timeoutSecs" value="540"/>
>                 <entry key="sfdc.loadBatchSize" value="2000"/>
>                 <entry key="sfdc.entity" value="OrderItem"/>
>                 <entry key="process.operation" value="upsert"/>
>                 <entry key="sfdc.useBulkApi" value="true"/>
>                 <entry key="sfdc.bulkApiSerialMode" value="true"/>
>                 <entry key="sfdc.externalIdField" value="SlId__c"/>
>                 <entry key="process.mappingFile" value="C:\Users\User\Google Drive\Automation\OrdersLine21Jan.sdl"/>
>                 <entry key="process.outputError" value="C:\Users\User\downloads\Logs\errorUpsertOrderItem.csv"/>
>                 <entry key="process.outputSuccess" value="C:\Users\User\downloads\Logs\successUpsertOrderItem.csv"/>
>                 <entry key="dataAccess.name" value="C:\Users\User\Google Drive\Automation\JAEG_TransactionDetails.csv" />
>                 <entry key="dataAccess.type" value="csvRead" />
>             </map>
>         </property>     </bean>

From my research, it seems to be something to do with either the debug log (I think most likely) or batch size.

I have set the sfdc.debugMessages to 'false' so it is not writing the files but it does seem to write it to the command screen.  I feel this could be causing the problem, is there a default log setting?  Maybe a process command setting?

In the data loader document http://resources.docs.salesforce.com/200/6/en-us/sfdc/pdf/salesforce_data_loader.pdf it says the max sfdc.loadBatchSize is 200 but through the UI it sets it to 2000 when batch is true.  If that does restrict it, that could explain it.

I just cant find anything recent about this problem, anyone had any luck doing this at full pace recently?
In one of Jeff Douglas's blog posts he demonstrated how to create a custom Attachment related list for specific objects. http://blog.jeffdouglas.com/2014/05/30/how-to-customize-salesforce-attachments/ 
I've implemented that code to work with our custom Project object by following his examples, but I don't know how to write the test classes for both the VisualForce page and the Apex class so that we can put this custom object into production. I would really appreciate it if someone could provide a test class for this code or at least get me started. 

The code I've written thus far is below:

The Apex Controller:
public with sharing class UploadAttachmentController {
    
    public String selectedType {get;set;}
    public String description {get;set;}
    public MPM4_BASE__Milestone1_Project__c project {get;set;} 
    public Project_Attachment__c attachment {get;set;}
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public UploadAttachmentController(ApexPages.StandardController controller) { 
        this.project = (MPM4_BASE__Milestone1_Project__c)controller.getRecord();
    }   
    
    // creates a new Project_Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Project_Attachment__c obj = new Project_Attachment__c();
        obj.Project__c = project.Id; 
        obj.description__c = description;
        obj.type__c = attachment.Type__c;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Contact_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // insert the attachment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Contact_Attachment__c record
    *  2. Insert new Attachment with the new Contact_Attachment__c record as parent
    *  3. Update the Contact_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Project_Attachment__c customAttachment = [select id from Project_Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+project.Id);
    }
    
    public PageReference back() {
        PageReference pgRef = new PageReference('/'+ this.project.Id);
        pgRef.setRedirect(true);
        return pgRef; 
    }     
 
}
The VisualForce Page:
<apex:page StandardController="MPM4_BASE__Milestone1_Project__c" tabStyle="MPM4_BASE__Milestone1_Project__c" extensions="UploadAttachmentController">
 
 <apex:sectionHeader title="{!MPM4_BASE__Milestone1_Project__c.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >
 
 <apex:pageBlockButtons >
   <apex:commandButton action="{!back}" value="Back to Project"/>
   <apex:commandButton action="{!back}" value="Cancel"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Type" for="type"/>
      <apex:inputfield value="{!attachment.Type__c}" id="type" required="true"/> 
    </apex:pageBlockSectionItem> 
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="Description" for="description"/> 
      <apex:inputTextarea id="description" value="{!description}" rows="4" cols="50"/>
    </apex:pageBlockSectionItem>
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem>    
    
  </apex:pageBlockSection>
 
 </apex:pageBlock> 
 
 </apex:form>
 
</apex:page>

 
We have custom APEX code that utilizes a PaaS library from Click and Pledge. We make a call-out to Click & Pledge to process a credit card or ACH payment. Approximately 1% of the time, we never receive a response at all - the code just seems to terminate. It doesn't get to the next line of execution, and no exception is caught though it is in a try/catch block for a generic exception. We know the callout is definitely executed because a payment is created in Click & Pledge but there is no return happening.

How is it possible that the code doesn't make it to the line after the callout, and also doesn't go into the exception block? No engineer we've worked with who has looked at this has ever seen that happen. Is it some sort of network issue potentially? Also, we have never been able to reproduce this but we have done some tracking on how many times it happens and it's nearly consistently 1%. The reason this is such an important issue despite the low volume is because we think the payment hasn't gone through since we've created no record of it one way or the other due to the code never getting past the callout, so the parent is able to pay again, which makes them angry, looks bad for us, and causes a lot of refund work on our side.

Here is the block of code we are having an issue with. 

try {
result = PaymentProcessor.processCreditCard(itemName, itemPrice, creditCardInfo, tracker, false);//NAIS-1810

// [DP] 07.06.2015 NAIS-1933 Opp and sale TLI are now created just after payment attempt, regardless of whether or not it was successful
if (theOpportunity == null || theOpportunity.Id == null){
Opportunity createdOpp = FinanceAction.createOppAndTransaction(new Set{thePfs.Id}, false)[0];
theOpportunity.ID = createdOpp.Id;
}

if (result.isSuccess == true) {
// tliToUpdate.Transaction_Status__c = 'Posted';
transactionLineItemId = PaymentUtils.insertCreditCardTransactionLineItem(theOpportunity.Id, itemPrice, paymentData.ccCardType, paymentData.ccCardNumberLast4Digits, result);
}
else {
transactionLineItemId = PaymentUtils.insertCreditCardTransactionLineItem(theOpportunity.Id, itemPrice, paymentData.ccCardType, paymentData.ccCardNumberLast4Digits, result);
handleTransactionError(result);
}

} catch (Exception e){
if (PaymentProcessor.SETTINGS.Custom_Debug__c){
Custom_Debug__c cd = new Custom_Debug__c();
cd.Message__c = 'Processing failed: ' +e.getMessage();
insert cd;
}
this.pageError = true;
this.errorMessage = 'There was an error with your payment. Please contact NAIS before retrying. Error: ' + e.getMessage();
return handlePaymentError();
}
We are developing an application that runs on Heroku that uses the username/password flow to authenticate into our Salesforce instance.  When running on Winter 16 we were using the username/password OAuth flow and passing the personal security token so that we could use the Enforce IP restrictions in the connected app.  The application has had no issues logging into either sandbox or production environments until the upgrade to Spring 16 in Sandbox.  Since the upgrade we have been unable to log into sandbox using the original flow as programmed in the app.  We initially attempted to resolve the issue by resetting the personal security token but that had no effect on the error we are receiving, "invalid_grant - Authentication failure".  We have found a workaround to keep us developing which is to relax the ip restrictions and remove the personal security token from the login flow but this is only a temporary fix and not what we would like to deploy into production.

Also, we did switch the app over to point to production to verify that we are not having any issues there and it works fine; production is still on Winter 16.

Any idea what changed in the username/password OAuth flow with the upgrade to Spring 16?  I cannot find anything in the release notes that points to what the issue may be.
Hi, I want to get full fault message in SOAP API call. But right now, it’s not possible in Salesforce. I found the below workaround in one site. Can anyone guide me to get full message and how to implement the below workaround?

1.Add an 'error' string field to the response class. You then do your webservice call to an intermediate layer which hides these exceptions and always returns to salesforce a 'valid' response.
 
  • December 15, 2015
  • Like
  • 1
Hi all,

Is it possible to give a 3rd party application access to a custom webservice without giving them access to the standard API? 

To give a little background on my project. Users will use their Salesforce credentials to login and register on one of our sister company's websites. Once they have logged into the site using their Salesforce credentials, the user needs the ability to pull down Salesforce data they own, such as customer information. 

What we have built for this works great, but the issue is being able to restrict the users to the custom service. Our security team his holding up this project because of the additional access to the standard api.

Any thoughts on how to limit access to the custom service only?



 
Hi,
I am using the Force.com REST API. Whenever I do a GET on a particular object, I don't get an ETag. Does Force.com REST API support ETags? If so, is there some documentation on how to go about using this?

Thanks, Sornakumar

Hey All, 

 

The fact that the canvas app url only provides one endpoint seems to be problematic for us.  We provide the application that is connected, and under the course of normal development would like to be able to put up test versions, etc, without breaking current production users and without having to change the canvas url in the managed package.  Updating the managed package to just change the url seems heavy handed, and problematic as it would need to manually changed back to the production endpoint before release.

 

Generally we have multiple endpoints for test, beta and prod.   And it seems logical that I wouldnt need to change the managed package based on whether its running in test or prod.  Any suggestions on how I can publish a managed package with the one url but have it target a different endpoint based on something?

 

Any thoughts would be appreciated.

 

Thanks

 

Jeremy