Monday, May 20, 2013

Simple Salesforce.com Apex programming sample to call apex webservice using CSharp (C#)


Here is a very simple code to call a apex web service in salesforce using C#. It's also return a "Contact" object with values.The returning value is based on the query used in the apex web service code. From this example you can understand how to query salesforce objects, how to call apex web service, how to connect to salesforce via code and also you can understand how to retrieve salesforce object value.You can also query the custom objects.
You need to add two web reference in your application.
     1. Enterprise WSDL web reference
     2. WSDL for the webservice class you have created.

To get the Enterprise WSDL navigate to

  • Your Name -> Setup -> App Setup -> Develop -> API
  • There you can get the  Enterprise WSDL

To get the WSDL for the webservice class you have created, navigate to

  • Your Name -> Setup -> App Setup -> Develop -> Apex Class
  • There select your class. 
  • Then click generate WSDL

In the following code ApexService_WSDL is Enterprise WSDL web reference and Enterprise_WSDL is WSDL web reference for the webservice class you have created.

Apex WebService Code in SalesForce:
global class MyCustomController  
 {  
    webservice static Contact[] ReturnObject()  
    {  
      Contact[] cont=[SELECT Firstname, Lastname FROM Contact];  
      return cont;  
    }  
 }  

C# Code in Client Side Application:
SforceService binding = new SforceService();  
 private LoginResult lr;  
 binding.Timeout = 10000;  
 lr = binding.login("YOUR LOGIN EMAIL ID", "PASSWORD + SECURITY TOKEN");  
 binding.Url = lr.serverUrl;  
 binding.SessionHeaderValue = new Enterprise_WSDL.SessionHeader();  
 binding.SessionHeaderValue.sessionId = lr.sessionId;
 
 using (ApexService_WSDL.MyCustomControllerService client = new MyCustomControllerService())  
 {  
    client.SessionHeaderValue = new ApexService_WSDL.SessionHeader();   
    client.SessionHeaderValue.sessionId = lr.sessionId;                   
    ApexService_WSDL.Contact[] m = client.ReturnObject();  
 }  

Don't forget to replace you salesforce email id , password + security token ;). To get or reset your security token, navigate to the following path.

  •      Your Name -> Setup -> My Personal Information -> Reset Security Token, and click the Reset My Security Token button
  • And you will get a mail with security token.

No comments:

Post a Comment