Managing SalesForce Events using .Net

By | May 13, 2011

I started a project lately to synchronize events between Google Calendar and Sales Force Calendar, there may be different products available out there but those are really expensive and some require you to setup an array of files in an end users machine. For the systems administrator it will be a nightmare specially when you have more than 1000 users so we opted out to develop our solution using .Net and created a service on our servers to do the job. The article discussed here does not depict the way we created a solution but a reference on important aspects of the evets that you might be using on your own solution such as saving events to different calendar providers.

In this post will discuss some points on how to save Sales Force Events using C#.Net and suprisingly it is simple specially with the use of a well documented API for SalesForce which you can find here. Now lets get started.


First you need a developer account at SalesForce and you can do that by signing up at SalesForce, dont worry it is free and easy. Take note that you should sign up as a developer otherwise some items will not be visible to you such as API references. Once you have done that can generate your Enterprise WSDL by going to Name (in my case its “Test Account”) -> Setup -> App Setup -> Develop -> API.

Please take note that you have to do this everytime you change or update the structure of your SalesForce instance like Custom Fields. Once thats Generated, save it in a handly location as a “wsdl” file.

Next on the list is you need to generate a Security Token, you need this for connecting to SalesForce in your application. Now go to Name (in my case its “Test Account”) -> Setup -> My Personal Information -> Reset Security Question


Fire up Visual Studio and create a solution of your choice, add the WSDL to your project then add that WSDL as a Web Reference by right clicking the References folder and add a Service Reference.

You need a web reference so you need to hit Advanced

Then Add Web reference

Now point to your file the hit Add reference. At this point you have created your Web Reference. I named my instance “SalesForceService”. Now at this point you got everything you need to rock and roll.

To be able to access your SalesForce instance you need to authenticate by using this code. This is where you use your token that you generated earlier. You can also see that there is a proxy authentication included in case you needed it.

private SforceService SFAuthenticate()
{
    SforceService oSalesForceService = new SforceService();
    oSalesForceService.Timeout = 60000;

    // Set Proxy Details if you are using one
    WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(new Uri(oSalesForceService.Url.ToString())));
    oWebProxy.Credentials = CredentialCache.DefaultCredentials;
    oWebProxy.UseDefaultCredentials = true;
    oSalesForceService.Proxy = oWebProxy;

    //Initialize SalesForce Service
    string username = "[email protected]";
    string password = string.Concat("password""token");

    LoginResult oLoginResult = oSalesForceService.login(username, password);

    oSalesForceService.Url = oLoginResult.serverUrl;
    oSalesForceService.SessionHeaderValue = new SessionHeader();
    oSalesForceService.SessionHeaderValue.sessionId = oLoginResult.sessionId;
    GetUserInfoResult oUserInfo = oLoginResult.userInfo;

    return oSalesForceService;
}

Now lets go to the methods you need, on all of the methods discussed below you will need the SFAuthenticate to execute your methods

1. Creating Events to SalesForce programatically

This is a stratight-forward approch as each Event properties are exposed though the Event Class, also one of the custom fields I created called UniquKey was also exposed by the generated WSDL file. Once the event is created just pass it as a parameter on the SforceService.create method, also if you notice it accepts an array of events so you can pass multiple events in one call.

Hint: this is what I used for synchronizing events on different calendar providers.

SforceService oSalesForceService = SFAuthenticate();
SalesForceService.Event oCalendarEvent = new SalesForceService.Event();

oCalendarEvent.Subject = "Test SF Calendar Entry From .Net";
oCalendarEvent.Description = "Hurrah! I posted my first sales force calendar event through .Net";
oCalendarEvent.Location = "New Zealand";
oCalendarEvent.StartDateTimeSpecified = true;
oCalendarEvent.StartDateTime = new DateTime(2011, 5, 31, 9, 0, 0);
oCalendarEvent.EndDateTimeSpecified = true;
oCalendarEvent.EndDateTime = new DateTime(2011, 5, 31, 9, 0, 0).AddHours(1);

oCalendarEvent.UniqueKey__c = Guid.NewGuid().ToString();

SaveResult[] oResults = oSalesForceService.create(new Event[] { oCalendarEvent });

oSalesForceService.logout();

2. Searching Events in SaleForce programatically

Searching is also easy all you need is to create a SOQL Query (its not mispelled, its really SOQL and it is the Salesforce Object Query Language similar to SQL) to get the fields you need. Take note as well that you cannot use * (select all fields), this makes sure that your codes are always optimized for what you only need. The result of that query is then outputted as a QueryResult and you can parse it as an Event. Only the fields you selected are the only fields that are populated on the Event object. To get the list of what are the available fields for the Event Object, check the Event properties.

SforceService oSalesForceService = SFAuthenticate();

QueryResult oQueryResult = null;
oSalesForceService.QueryOptionsValue = new QueryOptions();

oQueryResult = oSalesForceService.query("SELECT Id, Subject, Description, Location, StartDateTime, EndDateTime FROM Event WHERE UniqueKey__c = '{Your GUID Here}'");
for (int i = 0; i < oQueryResult.size; i++)
{
    Event oCalendarEvent = oQueryResult.records[i] as Event;
}

oSalesForceService.logout();

3. Updating Events in SalesForce programatically

For updating you just Set the Event properties to the values you want and pass it as a parameter on the SforceService.update method

SforceService oSalesForceService = SFAuthenticate();

QueryResult oQueryResult = null;
oSalesForceService.QueryOptionsValue = new QueryOptions();

oQueryResult = oSalesForceService.query("SELECT Id FROM Event WHERE UniqueKey__c = '{Your GUID Here}'");
for (int i = 0; i < oQueryResult.size; i++)
{
    Event oCalendarEvent = oQueryResult.records[i] as Event;
    oCalendarEvent.Description = "Updated Sales Force Event from .Net";
    SaveResult[] oSaveResults = oSalesForceService.update(new Event[] { oCalendarEvent });
}

oSalesForceService.logout();

4. Deleting events in SalesForce programatically

For deleting you pass the Event as the parameter on the SforceService.delete method

SforceService oSalesForceService = SFAuthenticate();

QueryResult oQueryResult = null;
oSalesForceService.QueryOptionsValue = new QueryOptions();

oQueryResult = oSalesForceService.query("select Id from Event where UniqueKey__c = '{Your GUID Here}'");
for (int i = 0; i < oQueryResult.size; i++)
{
    Event oCalendarEvent = oQueryResult.records[i] as Event;

    DeleteResult[] oSaveResults = oSalesForceService.delete(new string[] { oCalendarEvent.Id.ToString() });
}

oSalesForceService.logout();


9 thoughts on “Managing SalesForce Events using .Net

  1. Pingback: Managing Google Calendar Events using .Net « Raymund Macaalay's Dev Blog

  2. Brahmeswar

    Thank you for posting this valuable article.

    I am able to successfully authenticate with Salesforce.

    Can I know how to get the list of Contacts, Subscribers and Leads.

    Reply
    1. rsmacaalay

      This is a sample for Contact

      QueryResult oQueryResultUser = null;
      oSalesForceService.QueryOptionsValue = new QueryOptions();
      oQueryResultUser = oSalesForceService.query("select email, name from Contact where id in " + sWhereClause);
       
      if (oQueryResultUser.records != null)
      {
          for (int i = 0; i < oQueryResultUser.records.Count(); i++)
          {
              SalesForceWS.Contact oUser = (SalesForceWS.Contact)oQueryResultUser.records[i];
          }
      }

      I hope this gives you an idea, its all in that SOQL Query

      Reply
  3. Brahmeswar

    Thank you for quick reply on getting Contacts.

    Also I did to know the process how get Authenticated from my web app to Salesforce. (i.e. If we click a button “Get Authorise with Salesforce” then the page has to get redirected to Saleforce application, once we get authorise or Allow then it has to redirect to my our web application)

    Right now I was able to get authenticated by providing the Username and Password (password+token), But I am looking for the above scenario.

    Reply
  4. Brahmeswar

    Kindly can you provide me the code snippet for Authenticating the Salesforce. This should be same as Twitter (oAuth)

    Reply
    1. rsmacaalay

      Just to clarify on your question you need something like a persisting authentication token that brings you from your applicaiton to salesforce without further authentication?

      Reply

Leave a Reply