How To Call Salesforce Metadata API From C#.NET

Introduction

This article explains how to connect or integrate Salesforce Metadata SOAP API with C#.

What is Metadata API in Salesforce?

Metadata API is used to retrieve, deploy, create, update, or delete the customization information, such as - custom object definitions and page layouts, for your organization.

Integrating Metadata API with C#

This API allows your application to manage the metadata of your organization's Force.com instance. This API is intended for managing the customizations, and for building tools that can manage the metadata model, not the data itself.

We require two WSDL to integrate it in .NET application.

  • Metadata WSDL- This API is for the users who are developing client applications for their organization.
  • Partner WSDL- This API is for salesforce.com partners who are developing client applications for multiple organizations. This API would be helpful for authentication with salesforce.org.

Here are the steps to connect Salesforce Metadata API with C#.

Step 1 - You must have a Salesforce developer account. If you don’t have developer account, create new from the following link.

Step 2 - Connect with the Salesforce.org, using your credentials.

  1. To get Metadata WSDL API, click “Setup” on the right of the corner.
  2. Go “Develop > API”.
  3. Click on Generate Metadata WSDL.
  4. Right click on Save file(“metadata.wsdl”).
  5. Save file somewhere in your computer.

Please follow the same steps to get Partner WSDL.



Step 3 - Once you have Metadata and Partner WSDL, you can create new sample application in .NET.

Create new sample web or window form.



Step 4 - Once you create the page, you can add Metadata and Partner SOAP WSDL Web reference in your project.
  1. Right click on your project and click “Add > Service Reference”.
  2. Click on “Advanced.. > Add Web Reference..”.
  3. Give the local path where you keep WSDL files.
  4. Provide the web reference name as “MetadataService” for Metadata API, “SForceService” for Partner API, and click on “Add Reference”.
  5. Now, Metadata and Partner SOAP API are added in your project.

The Partners WSDL that needs to get an OAuth consumer Id for authentication, can contact salesforce.com.



Step 5 - After adding Web reference of Metadata and Partner WSDL, we will have to authenticate with Salesforce.
Authenticating and get a Session,

  1. Capture a username and password: These values can be hard-coded as part of your application's .config files, stored in a database for retrieval, or passed to the API via values collected from the application user.

    In this example, the username and password are simply hard-coded as string variables within the application. You need to append the password with your security token.

    You can reset or get security token from “My Setting > Personal > Reset My Security Token”.



    A security token is an automatically generated key that you must add to the end of your password to log into Salesforce from an untrusted network.

    For example, if your password is “mypassword” and your security token is XXXXXXXXXX, then you must enter “mypasswordXXXXXXXXXX” to log in.

    Security tokens are required whether you log in via the API or a desktop client, such as - Connect for Outlook, Connect Offline, Connect for Office, Connect for Lotus Notes, or the Data Loader.

    For more details, refer to this link.

  2. Once the username and password values are established, they are passed to the API to determine if they are valid.

As part of this validation, a binding to the API is established by instantiating a SforceService object. Once the binding is established, the result of the login attempt is returned in the form of a LoginResult object.

Best practices also dictate this login attempt to be wrapped in a try/catch block to allow for graceful handling of any exceptions that may be thrown as a part of the login process.

  1. SForceService.SforceService service = null;  
  2. SForceService.LoginResult loginResult = null;  
  3. service = new SForceService.SforceService();  
  4. loginResult = new SForceService.LoginResult();  
  5. loginResult = service.login("[email protected]""test@XYZ29ORuVMaexaeLugNW9RhX17");  
Step 6 - Once you get session Id, we can create custom objects and fields using metadata API.

In my sample attached code, I have created custom objects and fields.

Custom Object Creation Sample Code using Metadata API,
  1. /// </summary>   
  2. private void CreateMetadataObjects()   
  3. {  
  4.     try {  
  5.         MetadataService.Metadata mtData = new MetadataService.Metadata();  
  6.         MetadataService.MetadataService mtDataService = new MetadataService.MetadataService();  
  7.         mtDataService.SessionHeaderValue = new SessionHeader();  
  8.         mtDataService.SessionHeaderValue.sessionId = loginResult.sessionId;  
  9.         mtDataService.Url = loginResult.metadataServerUrl;  
  10.         CustomField field = new CustomField();  
  11.         string Objectlable = Convert.ToString(txtObjectName.Text).Trim();  
  12.         MetadataService.CustomObject co = new MetadataService.CustomObject();  
  13.         co.fullName = Objectlable.Replace(' ''_') + "__c";  
  14.         co.deploymentStatus = MetadataService.DeploymentStatus.Deployed;  
  15.         co.deploymentStatusSpecified = true;  
  16.         co.description = "Created by Salesforce MetaData Tool in C#";  
  17.         co.enableActivities = true;  
  18.         ////co.enableActivitiesSpecified = true;   
  19.         co.label = Objectlable;  
  20.         co.pluralLabel = Objectlable + "s";  
  21.         co.sharingModel = MetadataService.SharingModel.ReadWrite;  
  22.         co.sharingModelSpecified = true;  
  23.         co.nameField = field;  
  24.         co.nameField.label = Objectlable;  
  25.         co.nameField.type = FieldType.Text;  
  26.         co.nameField.typeSpecified = true;  
  27.         UpsertResult[] results = mtDataService.upsertMetadata(new Metadata[] {  
  28.             co  
  29.         });  
  30.         MessageBox.Show("Sucessfully created object.""Object Creation", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  31.     } catch (Exception ex) {  
  32.         MessageBox.Show(ex.Message.ToString());  
  33.     }  
  34. }  
In the same way, we can create custom fields under newly created custom object.

Fields Creation Sample Code using Metadata API,
  1. CustomField field = new CustomField();  
  2. MetadataService.Metadata mtData = new MetadataService.Metadata();  
  3. MetadataService.MetadataService mtDataService = new MetadataService.MetadataService();  
  4. mtDataService.SessionHeaderValue = new SessionHeader();  
  5. mtDataService.SessionHeaderValue.sessionId = loginResult.sessionId;  
  6. mtDataService.Url = loginResult.metadataServerUrl;  
  7. string objectFullName = txtObjectFullName.Text.Trim() + "__c";  
  8. field.description = "Created by Salesforce MetaData Tool in C#";  
  9. field.label = txtFieldLabel.Text.Trim();  
  10. field.fullName = objectFullName + "." + txtFieldName.Text.Trim() + "__c";  
  11. field.required = chkRequired.Checked;  
  12. field.typeSpecified = true;  
  13. UpsertResult[] results = mtDataService.upsertMetadata(new Metadata[] {  
  14.     field  
  15. });  
Step 7 - That’s it. We have done the code for Metadata API integration with C#. Now, it’s time to run our sample application.

Create object using Metadata API. Enter Object name as “Salary” in the given textbox and click on “Create Object” button.



Once object is created, proceed for field creation. Click on field creation button. As soon as you click on “Proceed for field creation” button, you will get fields details on the form.

Enter object and field name and other required details, here.



Output - After successfully creating the object and fields using metadata API, you can see the same as in the following screen, on your Salesforce.org.



Summary

This article explained how to integrate Salesforce Metadata and Partner SOAP API with C#.

We learned about Partner and Metadata WSDLs. I hope this article will help the developers who want to integrate the Salesforce Metadata API with C#.

To learn how to integrate Salesforce API with C#, read my previous article.

 

Up Next
    Ebook Download
    View all
    Learn
    View all