Managing User Identities in Salesforce with C#

For this blog post I will show how to do the following things in SalesForce.

  • Create new user
  • Add user to Role
  • Enable/Disable a User

Pre-requisites

If you don’t already have SalesForce info, you can create a free developer account at here. Then get a username and an encrypted password.

Create Webservice Description WSDL for the Proxy client.

WSDL is a description of the services or functions that are advertised by the Webservice. There are two ways to supply the information of the of the Webservice to the Proxy client, you can do it via the url or you can put the SOAP data into a file and supply the data. I prefer the second option, there are some items to work out but I find it is a faster way to grab the data.

You can generate the SalesForce wsdl from here.

I will save it as “SFenterpriseVS.wsdl”

Generate the Proxy Client

You can add the Webservice to your C# solution or you can add it as a separate dll reference. I like to add it as a separate reference. If anything changes in the API, I don’t have to recompile my C#.

In VStudio open a new solution. Chose Class Library, name it “SalesForceConnector”


Right click on the Project and select “Add service reference”


Click Advanced


Click “Add web reference”


Enter the save file path


Enter ‘SalesForceWebReference’ in the ‘Web reference name’ text box and click on ‘Add Reference’ button. Which will generate the .NET proxy class of the client to consume.

There is proxy class generation does something that will throw a VS compile error.

Click on the “Show All Files” button on the right top.

Look for the Reference.cs file. Open the file.

Search for “[][]” and replace it with “[]”


In VStudio, compile the solution


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;
using SaleforceOperations.WebReference;
using System.Net;

namespace Walkthrough
{

class QuickstartApiSample
{
private SforceService binding;

[STAThread]
static void Main(string[] args)
{
QuickstartApiSample sample = new QuickstartApiSample();
sample.run();
}

public void run()
{
// Make a login call
if (LoginToSaleforceService())
{
string userId = CreateUserAccount();
sObject[] roles = GetRolesList();
string roleId = GetRoleId("Western Sales Team", roles);
if (!string.IsNullOrEmpty(userId))
{
EnableDisableUser(userId, true);
AssignRoleToUser(userId, roleId);
}
// Log out
Logout();
}
Console.WriteLine("\nPress Any key to exit.");
Console.ReadLine();
}

private string CreateUserAccount()
{
User createUser = new User();
string firstName = "Jane";
string lastName = "Doe";
string email = "jandoe@salesforce.com";
string companyName = "Salesforce.com";

createUser.FirstName = firstName;
createUser.LastName = lastName;
createUser.Email = email;
createUser.CompanyName = companyName;
createUser.Username = "jane@saleforce.com";
createUser.Alias = "jane";
createUser.CommunityNickname = "Danny";
createUser.TimeZoneSidKey = "Pacific/Auckland";
createUser.LocaleSidKey = "en_US";
createUser.EmailEncodingKey = "UTF-8";
createUser.ProfileId = GetProfileId();
createUser.LanguageLocaleKey = "en_US";

SaveResult[] saveResults = binding.create(new sObject[] { createUser });
string Id = "";
if (saveResults[0].success)
{
Id = saveResults[0].id;
}
else
{
Console.WriteLine(saveResults[0].errors[0].message);
}
return Id;
}

private string GetProfileId()
{
string profileId = "";
String soqlQuery = "select id from profile where name='Standard User'";
try
{
QueryResult qr = binding.query(soqlQuery);
bool done = false;

if (qr.size > 0)
{
while (!done)
{
sObject[] records = qr.records;
for (int i = 0; i 0)
{
while (!done)
{
records = qr.records;
for (int i = 0; i < records.Length; i++)
{
UserRole userRole = (UserRole)records[i];
Console.WriteLine("Role Id = " + userRole.Id);
Console.WriteLine("Role Name = " + userRole.Name);
}

if (qr.done)
{
done = true;
}
else
{
qr = binding.queryMore(qr.queryLocator);
}
}
}
else
{
Console.WriteLine("No records found.");
}
}
catch (Exception ex)
{
Console.WriteLine("\nFailed to execute query succesfully," + "error message was: \n{0}", ex.Message);
}
return records;
}

private void EnableDisableUser(string UserId, bool enableDisable)
{
try
{
User user = new User();
user.Id = UserId;
user.IsActive = enableDisable;

SaveResult[] saveResults = binding.update(new sObject[] { user });

if (saveResults[0].success)
{
Console.WriteLine("The user is enable or disable" + saveResults[0].id + " was succesful");
}
else
{
Console.WriteLine("There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message);
}
}
catch (Exception ex)
{
Console.WriteLine("\nFailed to execute query succesfully," + "error message was: \n{0}", ex.Message);
}
}
private string GetRoleId(string roleName, sObject[] roles)
{
string roleId = "";
for (int i = 0; i < roles.Length; i++)
{
UserRole userRole = (UserRole)roles[i];
if (roleName == userRole.Name)
{
roleId = userRole.Id;
break;
}
}
return roleId;
}

}
}

Advertisements