Salesforce soap API VB.NET example code

Please see this example code as a starting point to your project!

(I assume you already have downloaded API and referenced it in your project! Here ApexApi is service reference name. If not, please see my this post)


' To store Session and ServerURL from Login call
Private Shared sessionId As String = Nothing
Private Shared serverUrl As String = Nothing

Private Sub btnContacts_Click(sender As System.Object, e As System.EventArgs) Handles btnContacts.Click
    Dim records As ApexApi.sObject() = getContactDetails()
    If records.Length <= 0 Then
        MsgBox("No records found!")
        Exit Sub
    End If

    ' Convert custom object to dataset to display properly in datagridview
    Dim ds As DataSet = New DataSet
    ds = rowTodsContact(records)

    Dim TableView As DataView
    TableView = ds.Tables("ContData").DefaultView
    DataGridView1.DataSource = TableView
End Sub

Private Function getContactDetails() As ApexApi.sObject()
Try
    Dim lr As ApexApi.LoginResult
    Using ss As ApexApi.SoapClient = New ApexApi.SoapClient
        If sessionId Is Nothing Or sessionId = "" Then
           ' Login Call
           lr = ss.login(Nothing, "hello@hello.com.au", "Yourpassword" & "Security Token")
           If lr.passwordExpired Then
               MsgBox("Password Expired")
               Exit Sub
           End If
           sessionId = lr.sessionId.ToString().Trim()
           serverUrl = lr.serverUrl.ToString().Trim()
        End If
    End Using

    ' Store SessionId in SessionHeader; We will need while making query() call
    Dim sHeader As ApexApi.SessionHeader = New ApexApi.SessionHeader
    sHeader.sessionId = sessionId
    
    ' Variable to store query results
    Dim qr As ApexApi.QueryResult = New ApexApi.QueryResult
    Using ss1 As ApexApi.SoapClient = New ApexApi.SoapClient
          ss1.ChannelFactory.Endpoint.Address = New System.ServiceModel.EndpointAddress(serverUrl)
          ' Limit to display only 100 records 
          ss1.query(sHeader, Nothing, Nothing, Nothing, "SELECT AccountId, OwnerId, FirstName, LastName, Email FROM Contact LIMIT 100", qr)
    End Using
               
    Dim records As ApexApi.sObject() = qr.records
    Return records
Catch ex As Exception

    MsgBox(ex.Message)
    Return Nothing
End Try
End Function

Private Function rowTodsContact(ByVal records() As ApexApi.sObject) As DataSet
 Dim ds As DataSet = New DataSet
 Try
       ds.Tables.Add("ContData")
       ds.Tables("ContData").Columns.Add("AccountId", GetType(String))
       ds.Tables("ContData").Columns.Add("OwnerId", GetType(String))
       ds.Tables("ContData").Columns.Add("FirstName", GetType(String))
       ds.Tables("ContData").Columns.Add("LastName", GetType(String))
       ds.Tables("ContData").Columns.Add("Email", GetType(String))
       For i As Integer = 0 To records.Length - 1
            Dim con As ApexApi.Contact = DirectCast(records(i), ApexApi.Contact)
            Dim accId As String = con.AccountId
            Dim ownerId As String = con.OwnerId
            Dim fName As String = con.FirstName
            Dim lName As String = con.LastName
            Dim email As String = con.Email
            ds.Tables("ContData").Rows.Add(accId, ownerId, fName, lName, email)
       Next
       Return ds
Catch ex As Exception

     MsgBox(ex.Message)
     Return Nothing
End Try
End Function

LoginScopeHeader while accessing Salesforce API

For Enterprise WSDL, you dont have to necessarily pass Login Header! Just pass Nothing and it should work.


Dim lr As ApexApi.LoginResult
Dim ss As ApexApi.SoapClient = New ApexApi.SoapClient

' Login Call
lr = ss.login(Nothing, "hello@hello.com.au", "yourSFpassword" & "SecurityToken")

For your Information, LoginScopeHeader has two parameters:
1) Organization ID
2) Portal ID

Click here for more information on how to find above values.

Destination URL not reset error Salesforce

While referencing Salesforce APIs, you may encounter the below error:

Destination URL Error

Destination URL Error

—-Reason—-
This is because you have not set the correct URL in your call that was returned (along with your SessionId) when you made login() call.

—-Solution—-
To resole the error, please create a new instance of SoapClient. For example, if you have created “ss” to make login call then create “ss1” for other calls you want to make.

(I assume you already have downloaded API and referenced it in your project! Here ApexApi is service reference name. If not, please see my this post)

Dim lr As ApexApi.LoginResult
Dim ss As ApexApi.SoapClient = New ApexApi.SoapClient

' Login Call
lr = ss.login(Nothing, "hello@hello.com.au", "yourSFpassword" & "SecurityToken")

If lr.passwordExpired Then
    MsgBox("Password Expired")
    Exit Sub
End If

sessionId = lr.sessionId.ToString().Trim()
serverUrl = lr.serverUrl.ToString().Trim()

' Store SessionId in SessionHeader; We will need while making query() call
Dim sHeader As ApexApi.SessionHeader = New ApexApi.SessionHeader
sHeader.sessionId = sessionId

' Variable to store query results
Dim qr As ApexApi.QueryResult = New ApexApi.QueryResult

' Create new instance for another call
Dim ss1 As ApexApi.SoapClient = New ApexApi.SoapClient
ss1.ChannelFactory.Endpoint.Address = New System.ServiceModel.EndpointAddress(serverUrl)

' Now run the query and it should resolve the error
ss1.query(sHeader, Nothing, Nothing, Nothing, "SELECT FirstName, LastName FROM Contact LIMIT 100", qr)
Dim records As ApexApi.sObject() = qr.records
Dim con As Contact = DirectCast(records(0), Contact)
Dim fName As String = con.FirstName
Dim lName As String = con.LastName

' Display
MsgBox("FirstName : " & fName & Chr(10) & "LastName : " & lName)

Add Salesforce API to your VB.NET Project or how to connect to Salesforce API ?

This will be your first step to get connected to Salesforce APIs for your integration project. Please follow steps below to access Salesforce APIs and start coding.

1) First thing you would need is to locate Salesforce API. For that, please login to your Salesforce Account. Note: the logged in user MUST have “Modify All Data” permission. In short, if the user falls under System Administrator profile then this option is checked bydefault.

2) Now go to Setup -> Develop -> API

APISetup

APISetup

3) Please choose appropriate API. If you are not sure then follow this link.

Choose API

Choose API

4) Generally if you are a developer and setting up integration for your org. then choose Enterprise WSDL. After clicking on appropriate WSDL, click Generate.

Generate WSDL

Generate WSDL

5) You will see large XML generated. Please Save this page. Note: Don’t copy this whole page to XML notepad and save because it won’t work!

Save Page

Save Page

6) Save this wsdl.xml file to your project folder.

Save Local

Save Local

7) Open Microsoft Visual Studio and create new VB.NET project.

8) On the right side of your IDE (i.e. your development environment), you will see Solution Explorer. (If you can’t see, go to View menu and select from there).

9) Right click on your project and select “Add Service Reference”.

Add Service Reference

Add Service Reference

10) Write your local address where wsdl.xml file is located.

Add Local Address

Add Local Address

11) Click Go. If the URL you provided is correct, you will see like below. You can now start developing! 🙂

Name Reference

Name Reference

12) If you want to have a look at example code of how to make login call to salesforce API or how to display basic contacts in gridview then please see here.

Difference between On-Demand Email-to-Case & Email-to-Case Agent – Salesforce.com

Salesforce.com has a functionality to create a case automatically or attach an incoming Email to an existing case, when customer sends an Email to one of your company’s email ID, like support@company.com. There are two options in Salesforce.com to enable that feature.

  • On-Demand Email-To-Case
  • Email-To-Case Agent

************Please keep the following notes in mind for both options************

  • When customer sends an Email about the issue to your support email and if there is no case raised then it will create a new case.
  • When customer replies to an existing case then it will attach that email to the existing case only, and it WON’T create a new case every time. It will identify this based on unique reference no. for every case, called Case_ThreadID. So when you create your custom Email Template in Salesforce, do not forget to add “Case_ThreadID” in Subject and Body of email!

I have listed down main differences.

On-Demand Email-To-Case  Email-To-Case Agent 
Does not need for any agent/program to be installed. Needs E2C Java Agent to be installed behind company’s Firewall.
Does not need Exchange Server 2007 or any other extra software to support this feature. Needs Exchange Server 2007 with Rollup 5 installed.
It’s inbuilt feature from SalesForce, so it can work with anything. Works only with IMAP, won’t work with POP3.
Does not supports attachments Larger than 10MB Supports attachments Larger than 10MB
Does not keep Email traffic within firewall. Keeps traffic within your Firewall.
No extra overhead. Large overhead to keep different mail boxes and continuous checking on servers.

Salesforce.com as a Case Management System?

Welcome to the Cloud Case Management System!

Before few months, I have been given a project to design Case Management System (CMS) in Salesforce.com CRM! I have been given all administrative access to Salesforce.com CRM and after lots of research and studies about Case Management, I have started planning and designing CMS. After sometime, I have found that it’s actually a good idea to build CMS within Salesforce.com.

Read more of this post

Redirecting users to a customized Visual Force Page – Salesforce.com

Let’s say you have developed custom object in Salesforce.com. You have standard Edit button that allows you to edit the entered information. Now you want to override this Edit button that redirects you to your custom page, rather than standard visual force page. In this case, you have to write APEX script that will override standard page to your custom page.

Example:

Say for Ex., you have “testcase” custom object. You have a field called “status”. You want to retrieve status field from testcase and compare it. If it is “Expired” then you want to redirect it to Google.com Else Yahoo.com.

Apex Class:

public class test

{

<!--more-->pagereference p;

testcase__c tc;

List&lt;testcase__c&gt; testcase = new List&lt;testcase__c&gt;();

public testcase__c testcase()

{

return tc;

}

public test(ApexPages.StandardController controller)

{

tc =(testcase__c)controller.getrecord();

}

public pagereference compare()

{

if(tc.status__c =='expired')

{

p=new pagereference('https://google.com');

}

else

{

p=new pagereference('https://yahoo.com');

}

return p;

}

}

<strong>Visual Force Page:</strong>

&lt;apex:page standardController="Testcase__c" extensions="test"&gt;

&lt;apex:form &gt;

&lt;apex:inputField value="{!Testcase__c.status__c}"/&gt;

&lt;apex:Commandbutton value="Compare Status" action="{!Compare}"/&gt;

&lt;/apex:form&gt;

&lt;/apex:page&gt;