Keywords

.NET (3) .rb (1) *.cod (1) 3110c (1) Algorithm (1) Amazon Cloud Drive (1) amkette (1) Android (1) Apex (6) apex:dynamic (1) API (1) API version (1) Application Development Contest (2) Artificial Intelligence (2) Atricore (1) b2g (1) Binary Search Tree (1) Blackberry Application Development (1) Blackberry Java Development Environment (1) Blender Game Engine (1) bluetooth (2) Boot2Gecko (1) bug fix (1) C (1) C++ (2) Cloud computing (1) Cloud Storage (1) Code Blocks (1) Code for a Cause (2) codejam (1) Coding (1) const_cast (1) Custom Help (1) Dancing With the Googlers (1) Data Structures (1) desktop environment (5) Doubly Linked List (1) Dropbox (1) dynamic visualforce component (1) dynamic_cast (1) Enterprise WSDL (1) Execution Context (1) fedora 14 (1) fedora 17 (5) Firefox OS (1) Flashing Nokia 3110c handset (1) Force.com (7) Gaia (1) Game Developement (1) GCC (2) GDG (2) Goank (1) Google (4) Google Developer Group (2) Google Drive (1) GTK+ (5) HACK2012 (2) Hall of Mirrors (1) help for this page (1) HTML5 (2) HTTP Web Server (1) IDE (1) Identity Provider (1) Intelligent Systems (1) Java (1) JDE (1) JOSSO (1) location based social network (1) me.social (1) MinGW (1) Natural Language Processing (1) Natural Language Toolkit (1) neckphone (1) NLKT (1) Nokia Pheonix (1) Notebook (1) Numeric XML Tags (1) OAuth2.0 (1) OLPC (7) OLPC-XO-1 (7) One Laptop per Child (5) Override custom help (1) Paas (1) Partner WSDL (1) Polymorphism (1) programming contest (1) PyGTK (4) Python (10) Recycled Numbers (1) reinterpret_cast (1) Research (1) REST (1) RM-237 (1) Robotics (1) Ruby (1) Saas (2) Salesforce.com (7) SDK (1) Service Provider (1) Single sign on (1) SOAP (3) Speaking in Tongues (1) SSO Agent (1) SSO Gateway (1) static_const (1) sugar (7) sugar activity (4) sugarlabs (7) SVG (2) Symbiotic AI (1) Tabbed container (1) TCP/IP (1) TCP/IP stack (1) Typecasting (1) typeid (1) ubuntu 13.10 (1) UDP (1) Upgrade Assembly (1) Visualforce (2) Web Server (1) Web Services (3) Web2.0 (1) wikipedia (1) wikipediaHI (1) WSDL (1) XML tags (1)

Sunday, September 11, 2011

Creating Custom Apex SOAP based Web Service in Salesforce.com's Force.com platform


This blog describes how to create a Custom web service in Salesforce using Apex.

Steps:
  • Navigate to Setup>Develop>Apex Classes  and create new class by clicking new button.
  • Write a class with "global" access modifier with methods (to be exposed) with "webService" keyword
        eg.

global class KartikService
{
    webService static String hello(String Name) 
    {
        return 'Hello '+Name+' ! :D';
    }
}

  • Then save this class. After saving the class you will view a button "Generate WSDL". Click on that to get WSDL for web service you just created. Save the WSDL file. Let say file name is "KartikService.wsdl"
  • Now we will consider how we generate clients to call this service in Java and in .Net.



 For Java:



  • We will create new project in Eclipse with name "ApexCustomWS"
  • You need Enterprise/Partner WSDL to access your Salesforce org. by getting a valid sessionId.
  • Import Enterprise or Partner WSDL file into the project and generate the web service client for that.
  • Import the "KartikService.wsdl" into project and  generate web service client by right clicking on the WSDL file.
  • Image below shows code generated for Partner WSDL in Blue box and code for Custom Web service in Red Box

Above step will generate few Java files. Now add a class "Test.java" and write following code:

package com.sforce.soap.schemas._class.KartikService;
 
import java.net.URL;
import org.apache.axis.AxisFault;
import com.sforce.soap.partner.LoginResult;
import com.sforce.soap.partner.SessionHeader;
import com.sforce.soap.partner.SforceServiceLocator;
import com.sforce.soap.partner.SoapBindingStub;
 
public class Test 
{
   public static void main(String[] args) 
   {
       try 
       {
         //Get a stub for calling partner WSDL's login method in order to get SessionID
         SoapBindingStub bind= (SoapBindingStub)new SforceServiceLocator().getSoap();
         LoginResult lr=bind.login("your_username_here", "your_Password+SecurityToken");
 
         //Create a sessionHeader object and set its sessioId property to sessionId 
         //received in loginResult object                        
         SessionHeader sh=new SessionHeader();
         sh.setSessionId(lr.getSessionId());
 
         //Create a service locator object for your custom web service
         KartikServiceServiceLocator locator=new KartikServiceServiceLocator();
 
         //Get URL for your custom web service
         URL url=new URL(locator.getKartikServiceAddress());
 
         //Create a stub for your custom web service with URL for your service and locator as parameters
         KartikServiceBindingStub stub=new KartikServiceBindingStub(url, locator);
 
         //Set the header property of stub with name "SessionHeader" and value as sh-sessionHeader 
         //object created above 
         stub.setHeader(locator.getKartikServiceAddress(), "SessionHeader", sh);
 
         //now make call to custom service-in our case its "Hello(String name)"
         System.out.println(stub.hello("KARTIK"));
        }
        catch (Exception e) 
        {e.printStackTrace(); }  
   } 
}


Its output:

Hello KARTIK !


For VB.NET:

    • Create a new Winows project or ASP.net project with name "ApexCustomWS"
    • Add Web Service Reference using Partner.wsdl with namespace name as "sForceService"
    • Add Web Service Reference using KartikService.wsdl with namespace name as "MyCustomApexWS"


               

    • Now the project in solution explorer with these references will look like :


               

    • Now we write a procedure "callCustomApexService" that first calls login service and get a sessionID and then make call to custom web service.
    • Code:
    • Imports ApexCustomWS.sForceService
      Imports ApexCustomWS.MyCustomApexWS
       
      Public Class Form1
          Public Sub callCustomApexService()
              Dim stub As New ApexCustomWS.sForceService.SforceService
              Dim lr As LoginResult
              Dim sh As New ApexCustomWS.sForceService.SessionHeader
       
              'make call to login service to get sessionId
              lr = stub.login("your_username_here", "your_Password+SecurityToken")        sh.sessionId = lr.sessionId
              stub.Url = lr.serverUrl
              stub.SessionHeaderValue = sh
       
              'Create stub to call custom web service
              Dim myserviceStub As New MyCustomApexWS.KartikServiceService
              myserviceStub.SessionHeaderValue = New MyCustomApexWS.SessionHeader
              myserviceStub.SessionHeaderValue.sessionId = sh.sessionId
       
              MsgBox(myserviceStub.hello("KARTIK"))
       
          End Sub
          Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
              callCustomApexService()
          End Sub
      End Class
Output of above code will be a MessageBox when the Winform will load in memory.

15 comments:

FreshersForce.com said...

where i get the wsdl file

Kartik said...

Hi,

After saving the web service class you will view a button "Generate WSDL". Click on that to get WSDL for web service you just created. For Partner/Enterprise WSDL file goto Setup>Develop>API.

Unknown said...

Hi Karthik,

In order to sync data between two systems I have to create web service in Salesforce.I was thinking of writing soap webservce in salesforce and webservice method will take couple of parametes,including external id.The logic in the method would be use External Id to query salesforce database and then loop through the result and if the record is there then update or else insert record in the Salesforce and return salesforce ID which can be stored in the other system.
My question:-While writing webservice in salesforce.Do I have to anything with XMl,or System will write Xml in the background and I should only write webservice in the salesforce and give to the other person.
Thanks for your Help.

Welcome Friends said...

how do we generate jar file for wsdl generated from custom webservice apex class

Anonymous said...



Thanks for sharing fabulous information. It' s my pleasure to read it.I have also bookmarked you for checking out new posts. by HRM 531 Week 4

Anonymous said...

It is really good to have a clear cut example.

however, i have come across situations where we need to move a solution through different environments.
like: DEV, TEST, PROD

and it would be beneficial to understand how we can set the End-Point of these webservices during Run-Time.
that would be overwriting the default values that are set on the classes when they are downloaded.

thanks,

pr said...

sf2sf communication using soap:

after adding partner wsdl of client org, into my sf org how i login and getting records from another sfdc account..

my code:

in parent org:

//code start
partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
String username = 'partner@gmail.com';
String password = 'passwordNItDpNyIGEY4SOdqtZtwbs69';
partnerSoapSforceCom.LoginResult loginResult = sp.login(username, password);
system.debug('@@@' + loginResult);

// i am login successfully but i want to ger records from partner organization .....

post the code please...soap b/w 2 sfdc organizations

Anonymous said...

Hi Kartik, I trying to learn salesforce integration plz help me how I can learn, or provide me any reading stuff or link where i can learn integration.

Unknown said...

Accuratesolutions Mobile-Anwendung Entwicklungsunternehmen . Eastern Apps ist ein führender mobile Anwendungen Entwicklungsunternehmen hoch Know-how in iPhone, Windows und Android- Apps.

Ram Ramky said...

I have never read more interesting articles than yours before. You make me so easy to understand and I will continue to share this site. Thank you very much and more power!
Salesforce.com training in chennai
Salesforce crm Training in Chennai

Augurs Technologies Pvt Ltd. said...

Web Development Development Company in Lucknow India, USA, UK

swetha singh said...

I have gone through your blog, it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic. Kindly post more like this, Thank You.
air hostess training in chennai
Air Hostess Training Institute in chennai
air hostess academy in chennai
air hostess course in chennai

ajithajohn said...

Great blog. It is simply innovative and useful.
Its pretty good and well noted. All your points are very useful.
salesforce training in chennai
salesforce course in chennai
salesforce training institute in chennai
salesforce training in bangalore
salesforce training institute in bangalore
salesforce course in bangalore

jefrin said...

All points are very useful
best salesforce training institute chennai

Unknown said...

You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...

Salesforce community Portals
Salesforce partner community
Salesforce customer community
Salesforce partner portal
Salesforce customer portal
Certified cloud portals
Salesforce community
Salesforce partner community licence cost
Salesforce community cost