Create a custom Web service in Salesforce and consume it in C#.Net application

In Previous article, we have consumed the standard enterprise wsdl of the salesforce. In this article we will create the webservice using apex in salesforce and consume it in C#.Net application.

In Salesforce create below class (using force.com IDE)

global public with sharing class SaveExpenditureWebService {

	webservice static Expenditure__c createExpenditure(Decimal amount,String expName, String paidByName )
	{
		Expenditure__c c = new Expenditure__c();
		Person__c p = [Select p.Name From Person__c p Where Name = :paidByName limit 1];
		c.Amount__c = amount;
		c.Name = expName;
		c.Exp_Date__c = Date.today();
		c.Paid_By__c = p.Id;
		insert c;

		return c;
	}
}

Note:

  • Apex class in which webservice is going to be written must be declared “global“.
  • Keyword “webservice“ must be used for a method which should be exposed as a webservice.
  • Method must be declared as static.

In above code, I am using a custom object “Expenditure__c“ to insert into Salesforce.  Any type of code can be written.
Now in C#, create windows application with following controls:

Create Custom web service in salesforce using apex and consume using C#.Net
Create Custom web service in salesforce using apex and consume using C#.Net

Add the reference to “enterprise WSDL“ as shown in previous article.
Now, add the reference to newly created custom WSDL. (In Salesforce, go to the Apex classes and click on wsdl button to get the generated WSDL link)
In this case, name of web reference added is “SFDCCustom“.
Write below code, in c# application:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SFDCWebServiceExample.SFDCCustom;
using SFDCWebServiceExample.SFDC_Enterprise_WSDL;
using System.Web.Services.Protocols;

namespace SFDCWebServiceExample
{
    public partial class AddExpenditure : Form
    {
        private SforceService binding;
        private LoginResult lr;
        private SaveExpenditureWebServiceService myBinding = new SaveExpenditureWebServiceService();

        public AddExpenditure()
        {
            InitializeComponent();
        }

        private void btnExpenditure_Click(object sender, EventArgs e)
        {
            if (login())
            {
                try
                {
                    #region[Consume Custome webservice]
                    //Code 2
                    myBinding.SessionHeaderValue = new SFDCCustom.SessionHeader();
                    myBinding.SessionHeaderValue. sessionId = lr.sessionId;

                    // Update: Copy the URL returned by login to the endpoint for our web service
                    int idx1 = lr.serverUrl.IndexOf(@"/services/");
                    int idx2 = myBinding.Url.IndexOf(@"/services/");
                    if (idx1 == 0 || idx2 == 0)
                    {
                        MessageBox.Show("Invalid URL strings in bindings");
                    }

                    myBinding.Url = lr.serverUrl.Substring(0, idx1) + myBinding.Url.Substring(idx2);

                    decimal amnt = 0;

                    Decimal.TryParse( txtAmount.Text,out amnt);

                    SFDCCustom.Expenditure__c c = myBinding.createExpenditure(amnt, txtExpName.Text, cboPaidBy.SelectedItem.ToString());
                    MessageBox.Show("Record Added Succesfully to salesforce");
                    #endregion
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message);
                }
            }
        }

        private bool login()
        {
            try
            {
                binding = new SforceService();
                binding.Timeout = 6000;
                lr = binding.login(txtUserName.Text, txtPwd.Text);
                return true;
            }
            catch (SoapException e)
            {
                MessageBox.Show(e.Message);
            }
            return false;
        }

        private bool validateControls()
        {
            if (txtPwd.Text.Trim() == string.Empty && txtUserName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please provide the credentials");
                return false;
            }
            return true;
        }
    }
}

Note:

  • To login into application, use the Enterprise WSDL and after that use custom WSDL (That’s why we have two objects of the binding).
  • After login update “SessionHeaderValue” by the custom WSDL sessionHeader.
  • After setting the session header, change the URL of the binding object.

Assumption:
In drop down list, the names of the person added must be available in Salesforce, so that the SOQL to find the person object should return the value.

Download Source code of consuming and creating web service in salesforce

Posted

in

,

by


Related Posts

Comments

9 responses to “Create a custom Web service in Salesforce and consume it in C#.Net application”

  1. […] You can download the source code in next tutorial. […]

  2. Nag Avatar
    Nag

    Hi ,
    I am getting Below Error.
    Can You help me ….Please.
    Error 1: The type or namespace name ‘Expenditure__c’ does not exist in the namespace ‘SFDCWebServiceExample.SFDCCustom’ (are you missing an assembly reference?)

    1. JitendraZaa Avatar
      JitendraZaa

      This Custom Object “Expenditure__c” must be present in your org then only you can use it.

      1. Nag Avatar
        Nag

        Thanks for Your Response,

        I have already created custom object (Expenditure__c) in my organization…

        thank you..

  3. Nag Avatar
    Nag

    Thanks for Your Response,

    I have already created custom object (Expenditure__c) in my organization…

  4. Nita Avatar
    Nita

    Hi,
    I’m getting error “No service available for class ‘SaveExpenditureWebServiceService’”

    are there something I missed when copy paste example source code?

  5. nitish dikshit Avatar
    nitish dikshit

    hi,
    i have one requirement of integration of sales force and biztalk.can you give me code
    of integrating biztalk and salesforce.?it’s very urgent.please help me!!!

  6. Suyog Avatar
    Suyog

    Hello,
    After adding first Web reference, i added the Generated WSDL from apex class to the web reference,but its not working.(as, in your above given example it is “SFDCCustom”)
    Thank You.

  7. suriyadev p Avatar
    suriyadev p

    Hi Jitendrazaaa/ Everyone,

    I am new to salesforce. I am here to integrate my basic windows app (visual studio) data to sales force lead.
    I followed your first tutorials and connected to sales force API. got all the salesforce objects into message box. So while following I couldn’t how to connect to sales force and load data to lead.

    Can please help me with load data into sales lead using windows app.
    Thank you
    suriyadev91@gmail.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading