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.
- To get Metadata WSDL API, click “Setup” on the right of the corner.
- Go “Develop > API”.
- Click on Generate Metadata WSDL.
- Right click on Save file(“metadata.wsdl”).
- 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.
- Right click on your project and click “Add > Service Reference”.
- Click on “Advanced.. > Add Web Reference..”.
- Give the local path where you keep WSDL files.
- Provide the web reference name as “MetadataService” for Metadata API, “SForceService” for Partner API, and click on “Add Reference”.
- 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,
- 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.
- 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.
- SForceService.SforceService service = null;
- SForceService.LoginResult loginResult = null;
- service = new SForceService.SforceService();
- loginResult = new SForceService.LoginResult();
- 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,
-
- private void CreateMetadataObjects()
- {
- try {
- MetadataService.Metadata mtData = new MetadataService.Metadata();
- MetadataService.MetadataService mtDataService = new MetadataService.MetadataService();
- mtDataService.SessionHeaderValue = new SessionHeader();
- mtDataService.SessionHeaderValue.sessionId = loginResult.sessionId;
- mtDataService.Url = loginResult.metadataServerUrl;
- CustomField field = new CustomField();
- string Objectlable = Convert.ToString(txtObjectName.Text).Trim();
- MetadataService.CustomObject co = new MetadataService.CustomObject();
- co.fullName = Objectlable.Replace(' ', '_') + "__c";
- co.deploymentStatus = MetadataService.DeploymentStatus.Deployed;
- co.deploymentStatusSpecified = true;
- co.description = "Created by Salesforce MetaData Tool in C#";
- co.enableActivities = true;
-
- co.label = Objectlable;
- co.pluralLabel = Objectlable + "s";
- co.sharingModel = MetadataService.SharingModel.ReadWrite;
- co.sharingModelSpecified = true;
- co.nameField = field;
- co.nameField.label = Objectlable;
- co.nameField.type = FieldType.Text;
- co.nameField.typeSpecified = true;
- UpsertResult[] results = mtDataService.upsertMetadata(new Metadata[] {
- co
- });
- MessageBox.Show("Sucessfully created object.", "Object Creation", MessageBoxButtons.OK, MessageBoxIcon.Information);
- } catch (Exception ex) {
- MessageBox.Show(ex.Message.ToString());
- }
- }
In the same way, we can create custom fields under newly created custom object.
Fields Creation Sample Code using Metadata API,
- CustomField field = new CustomField();
- MetadataService.Metadata mtData = new MetadataService.Metadata();
- MetadataService.MetadataService mtDataService = new MetadataService.MetadataService();
- mtDataService.SessionHeaderValue = new SessionHeader();
- mtDataService.SessionHeaderValue.sessionId = loginResult.sessionId;
- mtDataService.Url = loginResult.metadataServerUrl;
- string objectFullName = txtObjectFullName.Text.Trim() + "__c";
- field.description = "Created by Salesforce MetaData Tool in C#";
- field.label = txtFieldLabel.Text.Trim();
- field.fullName = objectFullName + "." + txtFieldName.Text.Trim() + "__c";
- field.required = chkRequired.Checked;
- field.typeSpecified = true;
- UpsertResult[] results = mtDataService.upsertMetadata(new Metadata[] {
- field
- });
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.