Getting the default record type of a user for Event Creation in Salesforce

I have been twisting my head around in finding a solution for this simple task and I guess its worth while to share this information to everyone as I cannot search anything on Google or even in Developer Force any solution related to my problem. Eventually it ended up in calling their premier support for assistance, then after a week of emails sent back and forth the answer was:

“you cannot get the default record type for user without logging to salesforce.com”

what that means is that you cannot get the default record type for a user if you are using a privileged account, you must use the users login credentials when performing the query, which defeats the purpose of having a super user account creating events for you programatically.

Anyway here is what I initially done to get the default record type, At first they suggested this solution in Java

Schema.DescribeSObjectResult oSObjectResult = Event.SObjectType.getDescribe();
ListRecordTypeInfo> oRecTypeInfos = oSObjectResult.getRecordTypeInfos();

Schema.RecordTypeInfo has a method isDefaultRecordTypeMapping()

So I used that information to grab what I want in C#.Net, so I created a method to extract that information

public SforceService Authenticate()
{
    try
    {
        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
        LoginResult oLoginResult = oSalesForceService.login(sUserName, string.Concat(sPassword, sToken));

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

        return oSalesForceService;
    }
    catch (Exception ex)
    {
        return null;
    }
}

public string GetRecordType()
{
    SforceService oSalesForceService = Authenticate();

    string sRecordTypeId = "";

    DescribeSObjectResult oObjectResult = oSalesForceService.describeSObject("Event");
    List<RecordTypeInfo> oRecTypeInfos = oObjectResult.recordTypeInfos.ToList();
    foreach (RecordTypeInfo oRecTypeInfo in oRecTypeInfos)
    {
        if (oRecTypeInfo.defaultRecordTypeMapping == true)
        {
            sRecordTypeId = oRecTypeInfo.recordTypeId;
        }
    }
    return sRecordTypeId;
}

Using that will be an issue as it is not showing options on filtering it by Owner ID like what SalesForce have in other tables, so the result shown after I executed the method is the default record type of the privileged Account.  So I thought I can go directly to the related tables perform SOQL queries like such

oQueryResult = oSalesForceService.query("Select Id, Name from RecordType where SobjectType = 'Event' and IsActive = True and OwnerID = '" + sOwnerID +"'");

and might have some hope in there but after checking the RecordType and RecordTypeInfo there is not field for Owner ID

and in User class there are no fields for Default record type.

So the only real solution for this as of this post date is to keep a local copy of the default record type per user or as a Global setting if you wish.   So when I create event I assign the RecordTypeId by getting it by the “Record Type Name” defaulted to a user which is stored locally.

oEvent.RecordTypeId = GetRecordTypeId(sUserDefaultRecordType);
public string GetRecordTypeId(string sRecordTypeName)
{
    SforceService oSalesForceService = Authenticate();

    QueryResult oQueryResult = null;

    oSalesForceService.QueryOptionsValue = new QueryOptions();
    oQueryResult = oSalesForceService.query("Select Id from RecordType where SobjectType = 'Event' and IsActive = True and Name = '" + sRecordTypeName + "'");

    if (oQueryResult.size != 0)
    {
        RecordType oRecordType = (RecordType)oQueryResult.records[0];
        return oRecordType.Id;
    }
    return null;
}

I hoped I helped someone out there with a similar situation as I have

Managing SalesForce Events using .Net

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 = "you@company.com";
    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();
Follow

Get every new post delivered to your Inbox.

Join 774 other followers