• Stars
    star
    367
  • Rank 115,686 (Top 3 %)
  • Language
    C#
  • License
    BSD 3-Clause "New...
  • Created almost 11 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Force.com Toolkits for .NET provides an easy way for .NET developers to interact with the Force.com & Chatter REST APIs using native libraries.

Force.com Toolkit for .NET Build Status

This SDK is now targeting .NET Standard 2.0, .NET 4.5.2, .NET 4.6.2, and .NET 4.7.2.

The Force.com Toolkit for .NET provides an easy way for .NET developers to interact with the Lighting Platform APIs using native libraries.

The Common Libraries for .NET provides functionality used by the Force.com Toolkit for .NET and the Chatter Toolkit for .NET. While you can use the Common Libraries for .NET independently, it is recommended that you use it through one of the toolkits.

NuGet Packages

Published Packages

You can try the libraries immmediately by installing the DeveloperForce.Force and DeveloperForce.Chatter packages:

Package Manager:

Install-Package DeveloperForce.Force
Install-Package DeveloperForce.Chatter

.NET CLI:

dotnet add package DeveloperForce.Force
dotnet add package DeveloperForce.Chatter

Operations

Currently the following operations are supported.

Authentication

To access the Force.com APIs you must have a valid Access Token. Currently there are two ways to generate an Access Token: the Username-Password Authentication Flow and the Web Server Authentication Flow

Username-Password Authentication Flow

The Username-Password Authentication Flow is a straightforward way to get an access token. Simply provide your consumer key, consumer secret, username, and password concatenated with your API Token.

var auth = new AuthenticationClient();

await auth.UsernamePasswordAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURUSERNAME",
                                 "YOURPASSWORDANDTOKEN");

You can also specify a SalesForce API version when creating an authentication client if your use case requires it. The default API Version is currently v36.0

var auth = new AuthenticationClient("v44.0");

You can get the latest API version from your Force.com instance in authentication client.

var auth = new AuthenticationClient();
await auth.GetLatestVersionAsync();

Web-Server Authentication Flow

The Web-Server Authentication Flow requires a few additional steps but has the advantage of allowing you to authenticate your users and let them interact with the Force.com using their own access token.

First, you need to authenticate your user. You can do this by creating a URL that directs the user to the Salesforce authentication service. You'll pass along some key information, including your consumer key (which identifies your Connected App) and a callback URL to your service.

var url =
    Common.FormatAuthUrl(
        "https://login.salesforce.com/services/oauth2/authorize", // if using sandbox org then replace login with test
        ResponseTypes.Code,
        "YOURCONSUMERKEY",
        HttpUtility.UrlEncode("YOURCALLBACKURL"));

After the user logs in you'll need to handle the callback and retrieve the code that is returned. Using this code, you can then request an access token.

await auth.WebServerAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURCALLBACKURL", code);

You can see a demonstration of this in the following sample application: https://github.com/developerforce/Force.com-Toolkit-for-NET/tree/master/samples/WebServerOAuthFlow

Creating the ForceClient

After this completes successfully you will receive a valid Access Token and Instance URL. The Instance URL returned identifies the web service URL you'll use to call the Force.com REST APIs, passing in the Access Token. Additionally, the authentication client will return the API version number, which is used to construct a valid HTTP request.

Using this information, we can now construct our Force.com client.

var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;

var client = new ForceClient(instanceUrl, accessToken, apiVersion);
var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);

Sample Code

Below you'll find a few examples that show how to use the toolkit.

Create

You can create with the following code:

public class Account
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

var account = new Account() { Name = "New Account", Description = "New Account Description" };
var id = await client.CreateAsync("Account", account);

You can also create with a non-strongly typed object:

var client = new ForceClient(_consumerKey, _consumerSecret, _username, _password);
var account = new { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);

Update

You can update an object:

var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);

account.Name = "New Name 2";

var success = await client.UpdateAsync("Account", id, account);

Delete

You can delete an object:

var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.Create("Account", account);
var success = await client.DeleteAsync("Account", id)

Query

You can query for objects:

public class Account
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}


var accounts = await client.QueryAsync<Account>("SELECT id, name, description FROM Account");

foreach (var account in accounts.records)
{
    Console.WriteLine(account.Name);
}

You can query for metadata:

var describe = await client.DescribeAsync<JObject>("Account");

foreach (var field in (JArray)describe["fields"))
{
    Console.WriteLine(field["label"]);
}

Bulk Sample Code

Below are some simple examples that show how to use the BulkForceClient

NOTE: The following features are currently not supported

  • CSV data type requests / responses
  • Zipped attachment uploads
  • Serial bulk jobs
  • Query type bulk jobs

Create

You can create multiple records at once with the Bulk client:

public class Account
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

var accountsBatch1 = new SObjectList<Account>
{
	new Account {Name = "TestStAccount1"},
	new Account {Name = "TestStAccount2"}
};
var accountsBatch2 = new SObjectList<Account>
{
	new Account {Name = "TestStAccount3"},
	new Account {Name = "TestStAccount4"}
};
var accountsBatch3 = new SObjectList<Account>
{
	new Account {Name = "TestStAccount5"},
	new Account {Name = "TestStAccount6"}
};

var accountsBatchList = new List<SObjectList<Account>>
{
	accountsBatch1,
	accountsBatch2,
	accountsBatch3
};

var results = await bulkClient.RunJobAndPollAsync("Account",
						BulkConstants.OperationType.Insert, accountsBatchList);

The above code will create 6 accounts in 3 batches. Each batch can hold upto 10,000 records and you can use multiple batches for Insert and all of the operations below. For more details on the Salesforce Bulk API, see the documentation.

You can also create objects dynamically using the inbuilt SObject class:

var accountsBatch1 = new SObjectList<SObject>
{
	new SObject
	{
		{"Name" = "TestDyAccount1"}
	},
	new SObject
	{
		{"Name" = "TestDyAccount2"}
	}
};

var accountsBatchList = new List<SObjectList<SObject>>
{
	accountsBatch1
};

var results = await bulkClient.RunJobAndPollAsync("Account",
                       BulkConstants.OperationType.Insert, accountsBatchList);

Update

Updating multiple records follows the same pattern as above, just change the BulkConstants.OperationType to BulkConstants.OperationType.Update

var accountsBatch1 = new SObjectList<SObject>
{
	new SObject
	{
		{"Id" = "YOUR_RECORD_ID"},
		{"Name" = "TestDyAccount1Renamed"}
	},
	new SObject
	{
		{"Id" = "YOUR_RECORD_ID"},
		{"Name" = "TestDyAccount2Renamed"}
	}
};

var accountsBatchList = new List<SObjectList<SObject>>
{
	accountsBatch1
};

var results = await bulkClient.RunJobAndPollAsync("Account",
                       BulkConstants.OperationType.Update, accountsBatchList);

Delete

As above, you can delete multiple records with BulkConstants.OperationType.Delete

var accountsBatch1 = new SObjectList<SObject>
{
	new SObject
	{
		{"Id" = "YOUR_RECORD_ID"}
	},
	new SObject
	{
		{"Id" = "YOUR_RECORD_ID"}
	}
};

var accountsBatchList = new List<SObjectList<SObject>>
{
	accountsBatch1
};

var results = await bulkClient.RunJobAndPollAsync("Account",
                       BulkConstants.OperationType.Delete, accountsBatchList);

Upsert

If your object includes a custom field with the External Id property set, you can use that to perform bulk upsert (update or insert) actions with BulkConstants.OperationType.Upsert. Note that you also have to specify the External Id field name when starting the job.

// Assumes you have a custom field "ExampleId" on your Account object
// that has the "External Id" flag set.

var accountsBatch1 = new SObjectList<SObject>
{
	new SObject
	{
		{"Name" = "TestDyAccount1"},
		{"ExampleId" = "ID00001"}
	},
	new SObject
	{
		{"Name" = "TestDyAccount2"},
		{"ExampleId" = "ID00002"}
	}
};

var accountsBatchList = new List<SObjectList<SObject>>
{
	accountsBatch1
};

var results = await bulkClient.RunJobAndPollAsync("Account", "ExampleId"
                       BulkConstants.OperationType.Upsert, accountsBatchList);

Contributing to the Repository

If you find any issues or opportunities for improving this respository, fix them! Feel free to contribute to this project by forking this repository and make changes to the content. Once you've made your changes, share them back with the community by sending a pull request. Please see How to send pull requests for more information about contributing to Github projects. You will be required to sign a Salesforce CLA for your submission to be considered.

Reporting Issues

If you find any issues with this demo that you can't fix, feel free to report them in the issues section of this repository.

More Repositories

1

deploy-to-sfdx

An open-source and community-driven tool for one-click Salesforce DX deployments from public repositories to Scratch Orgs
JavaScript
98
star
2

salesforce-cli-zsh-completion

A Zsh completion file for the Salesforce CLI (and script for updating it)
Shell
90
star
3

sfdx-waw-plugin

A plugin for the Salesforce CLI built by Wade Wegner and containing a lot of helpful commands.
TypeScript
72
star
4

salesforce-cli-bash-completion

Shell
57
star
5

sfdx-travisci

Setup Travis CI to work with Salesforce DX
Apex
26
star
6

salesforce-dx-pipeline-sample

Shell
26
star
7

azure-website-go-builder

Shell
25
star
8

sfdx-puppeteer

Shell
21
star
9

uber-sdk-for-net

A C# .NET SDK for Uber's API - https://developer.uber.com/
C#
19
star
10

waw-sfdx-docker

Dockerfile
16
star
11

WordToMarkdown

A simple console application that converts a Word document to markdown.
C#
14
star
12

azure-go-lang-site-extension

PowerShell
12
star
13

sfdx-code-gen

A tool for generating Salesforce DX source code from templates.
JavaScript
11
star
14

Sample-UnitTestHttpClient

C#
11
star
15

sfdx-dreaminvest

JavaScript
10
star
16

sfdx-platformencryption

An example for using Platform Encryption in a DE scratch org with Salesforce DX
9
star
17

ValidateACSTokenWebAPI

Demonstrate how to validate an ACS token in an ASP.NET Web API service
C#
9
star
18

sfdx-dh-decompose

A script that shows you how to decompose the famous dreamhouseapp/dreamhouse-sfdx into multiple package directors
Shell
7
star
19

wa-servicemanagement-with-kinect

Use the Kinect and your PC to interact with the Windows Azure Service Management API
C#
7
star
20

salesforce-dx-pipeline-mdapi-sample

Shell
6
star
21

CappedExponentialBackOff

C#
6
star
22

sfdx-core-test-plugin

An example of using the Salesforce DX Core Libraries in an OCLIF-based plugin
TypeScript
6
star
23

sfdx-forceentarch

Andrew Fawcett's "Force.com Enterprise Architecture (2nd Edition)" applied to Salesforce DX
Shell
6
star
24

Salesforce.SOAPHelpers

This .NET library provides a way for interacting with Salesforce's Force.com SOAP APIs.
C#
5
star
25

sfdx-cli-commands

JavaScript
5
star
26

sfdx-platformevents

JavaScript
5
star
27

TechEd14SDK

This repository contains code written during my TechEd NA 2014 session.
C#
5
star
28

wadewegner.github.com

This is the source of Wade Wegner's blog.
HTML
4
star
29

sfdx-wsdl2apex-plugin

JavaScript
4
star
30

StartupNamer

A simple application that will come up with names for startups and check the WHOIS registry to see if it's available
C#
4
star
31

th-trailblazerapp

Shell
4
star
32

CustomObjectsUsingSOAP

Interact with the Force.com SOAP and Metadata APIs using SOAP and .NET without proxy classes
C#
4
star
33

salesforce-dx-buildpack

Shell
3
star
34

an-internet-of-beers

JavaScript
3
star
35

Salesforce.CSharp.Tooling

A simple C# SDK for interacting with the Salesforce Tooling API using the REST interface.
C#
3
star
36

slack-twitter-bot

A simple slack bot that will keep track of tweets and post to a room
JavaScript
3
star
37

raspberrypi-camera-azure

Python
3
star
38

bac

JavaScript
3
star
39

TwitterOAuthRESTAPI

C# code for Twitter OAuth signed and application-only auth requests
C#
2
star
40

cloudybrews.github.com

JavaScript
2
star
41

sfdx-externalservices

JavaScript
2
star
42

bash_profile_OSX

This is the .bash_profile file for my Mac.
Shell
2
star
43

sdkLocalDatabaseCS_WithAzureTables

A simple example showing how to update this To Do application to use Windows Azure tables instead of the local database.
C#
2
star
44

sdkMicrophoneCS_UploadToBlob

A simple example of how to upload audio to Windows Azure blob storage from the Windows Phone.
C#
2
star
45

build-go-lite-windows

Go
1
star
46

Salesforce.Owin.Security.Provider

C#
1
star
47

intro-to-react

JavaScript
1
star
48

TwitterFollowers

C#
1
star
49

Salesforce.CSharp.Metadata

A simple C# SDK for interacting with the Salesforce Metadata API.
C#
1
star
50

ConnectIQ_AppJsonRequest

Shell
1
star
51

bash_profile_PC

Shell
1
star
52

gearset-test

1
star
53

sfdx-createlotsoftests

A bash script that uses the Salesforce CLI to create lot of Apex classes/tests and then run them
Shell
1
star
54

mycircleproj

1
star
55

sfdx-facialrecognition

Apex
1
star
56

sfdx-geolocation

1
star
57

TechEd_NZAU

Demos used in my Windows Azure and Windows Phone demos at TechEd NZ and AU
JavaScript
1
star
58

apex-metadata-api-sfdx

Source for the Apex Metadata API project on Trailhead
Apex
1
star
59

twilio-sync-node-sample

A simple exploration of Twilio's Sync API
JavaScript
1
star
60

ConnectIQ_WidgetJsonRequest

Shell
1
star
61

sfdx-userassist-plugin

JavaScript
1
star
62

deploy24-rag-demo

Python
1
star