Friday, November 5, 2010

Salesforce REST API Access Token

In my first article on the SFDC REST API I showed how you authenticate to Salesforce using OAuth. The main output of this process is the access token which must be provided when you make any other calls to the REST API. One of the first things I wondered about the access token is, how long does it last? It turns out that the access token is tied to the normal session timeout in SFDC and is configurable for each instance. To view or change the setting log into your account, click Setup, then under Administration Setup select Security Controls then Session Settings.
image
You can see that in this case the timeout is set to two hours. This means that if you go for more the two hours without calling the REST API the access token will expire. You can change this setting from between 15 minutes and 8 hours.
The next question is, when the access token expires does the user have to go through the login process again? Fortunately the answer is no, this is where the refresh token comes into play. When we did the initial authentication process to get the access token we also received a refresh token. The refresh token can be used to get a new access token without the user having to enter their username and password again.
The code to get a new access token is pretty much the same as the code we initially used to get access token.

{ 

string URI = "https://login.salesforce.com/services/oauth2/token";
StringBuilder body = new StringBuilder();


body.Append("refresh_token=" + refreshToken + "&");
body.Append("grant_type=refresh_token&");
body.Append("client_id=" + clientID + "&");
body.Append("client_secret=" + clientSecret + "&");
body.Append("redirect_uri=" + redirectURL); 

string result = HttpPost(URI, body.ToString()); 

JavaScriptSerializer ser = new JavaScriptSerializer();
token = ser.Deserialize<TokenResponse>(result); 

} 

You will notice two differences. First instead of passing the code we got when the user logged in, we pass the refresh token, and second we set the grant type to refreshToken instead of authorization_code. The function will return the same response as the initial call did with one exception. According to the OAuth specs the service is not required to return a new refresh token when a new access token is generated. This appears to be the case with SFDC since this call does not return a new refresh token. This means that you need to hold onto the original refresh token to use each time you request a new access token.

Monday, November 1, 2010

Salesforce REST API Part 2

In my last post I introduced the new Salesforce REST API. Now I will dig into some of the details of how to use the interface.

URIs

Like any REST API you access resources in Salesforce using various URIs like this:
http://na1.salesforce.com/services/data/v20.0/sobjects/Account/
The first part of the URI "http://na1.salesforce.com/" identifies your Salesforce instance. This is needed because different accounts will be hosted on different servers. As I showed in the last article you retrieve the instance URL during the authentication process.
The next piece "/services/data" identifies the service and is the same for all REST API calls. The following piece "v20.0/" is the version number which specifies the version of the API you want to use. You can retrieve a list of the available versions by calling the List Versions command which I will show in a minute. The Version command will return a URL that contains both the service and version parts of the URI.
Next 'sobjects' is the resource you will be calling. You can get a list of the available resources using the List Resources command.
Finally anything after the resource is specific to the resource and command you are calling.

Return Type

By default the REST API returns its results in JSON format. You can also request that the results be returned in XML. To do this just append .xml to the end of the URI you are calling. The documentation also indicates that you can do this using the HTTP ACCEPT header, but I have not been able to get that to work. I my examples I will be showing the results in XML.

List Versions Command

The list versions command looks like this:
https://na5.salesforce.com/services/data/.xml
Note that in all my examples I will be using the instance URL of my account, be sure to substitute your own.
Here is what is returned:
<?xml version="1.0" encoding="UTF-8"?>
<Versions>
<Version>
<label>Winter &apos;11</label>
<url>/services/data/v20.0</url>
<version>20.0</version>
</Version>
</Versions>


In this case there is only one version available, version 2.0. Also returned is the label for the version "Winter '11" and the URL to access the API for this version. One thing to note about this command is that you do not need to authenticate before calling it. It works whether you pass the access token or not.


List Resources Command

The next command you will want to know about lists the resources available for a specific version. The command looks like this:

http://na1.salesforce.com/services/data/v20.0/.xml

Remember if you want to return the results in JSON format just leave off the .xml or specify .json instead of .xml.

The result looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<urls>
<sobjects>/services/data/v20.0/sobjects</sobjects>
<search>/services/data/v20.0/search</search>
<query>/services/data/v20.0/query</query>
<recent>/services/data/v20.0/recent</recent>
</urls>


This shows the resources that are accessible through the API. The current resources are:

sobjects – Allows you to access information about the objects in the database and to insert, read, updated and delete objects.

query – Allows you to run SOQL queries.

search – Allows you to run a SOSL search.

recent – This seems to return a list of recent objects, but I haven't found any official documentation on it.

That's all for now. In future postings I will get into some more details on how each of these resources is used.

Saturday, October 30, 2010

Salesforce.com REST API


A while back I had the opportunity to develop a .NET desktop application that interfaced to Salesforce.com using the SOAP API, so I was very interested when I heard about SFDC's new REST based API. The beta of this interface has just been made available to developers and will eventually go into production in a future release. SFDC has made a simple Java sample available but no .NET samples yet, so I thought I would write an article explaining how to access the API from .NET. This example will be done in C# using Visual Studio 2010 and the .NET Framework 4.0 although there is no reason this couldn't be done with earlier versions of the framework.
To try out the API you will need a Salesforce.com developer account. You can sign up for a free account at http://developer.force.com/. I am not sure if the REST API is automatically enabled for all developer accounts, but if not you can sign up for it here.

Authentication

Before you can use the REST API you need to authenticate to Salesforce.com. There are two ways to do this, using a Session ID from the old SOAP API, or using OAuth which is what I will be doing in this sample. OAuth allows an application to access a web based resource without the user having to provide their login details to the calling application. The exact details of how OAuth works are beyond the scope of this article but you can learn more at ouath.net.
The first step in authentication is to enable the REST interface. To do this log into your SFDC account and select Setup. Under App Setup, select Develop then Remote Access, this will display a list of Remote Access Applications. The list will be empty at this point, so click on New to add a new remote access application.
clip_image002
There are two required fields, the Application name which can be anything of you choosing, and the Callback URL which needs a little explanation. OAuth is primarily designed to be used between two web sites. The web site requesting access will redirect to the SFDC login screen, and when the user has logged in the SFDC web site will re-direct back to the Callback URL you specify. If you are developing a web application this needs to be the URL of a secure (HTTPS) page. In this demo, since we are developing a desktop app, we don’t want to actually redirect so we put in an identifier of our choice that we will catch in our application.
Once you have filled out the form, click Save, then click on the application name on the list. The details you entered will be re-displayed along with the Consumer Key and Consumer Secret which we will need during the authentication process. I created some object level variables to hold this information:
private string clientID = “YOUR CONSUMER KEY";
private string clientSecret = “YOUR CONSUMER SECRET";
private string redirectURL = "resttest:callback";

Since the key and secret are specific to my SFDC account I have omitted them in the demo. You will need to put in the ones from your account.

The next thing we need to do is have our application call the SFDC login page. If this was a web app we could simply re-direct to is, but since this is a desktop app we can use the WinForms WebBrowser control. I added a WebBrowser control to my form and then put the following code in the Form_Load event:

var authURI = new StringBuilder();
authURI.Append("https://login.salesforce.com/services/oauth2/authorize?");
authURI.Append("response_type=code");
authURI.Append("&client_id=" + clientID);
authURI.Append("&redirect_uri=" + redirectURL);
webBrowser1.Navigate(authURI.ToString());



First we build a URL that points to the SFDC login page and includes the Consumer Key (called client_id) and the re-direct URL as query strings. Next we call Navigate on the web browser control to point to this location.
Once the user has entered their credentials using the web browser control it will be re-directed to resttest:callback. We can catch this in the webBrowser_DocumentCompleted event handler:

if (e.Url.AbsoluteUri.StartsWith("resttest:callback"))
{
webBrowser1.Navigate("about:blank");
code = e.Url.Query;
code = code.Substring(6);

GetToken();
}

When the redirect is found the first thing I did was redirect the web browser control to a blank page. This is not necessary but it looks nice. The URL that is returned will look like this:

callback?code=aPrx9vip.t4qSZdAs_DHNIR9mEcerAoVsq.hX9qVAtUNfAibMV8ClSmYxbsxiWb81O8BzgRwLA%3D%3D

We need to get the code query string since this is needed for the next part of the authentication process. The code is only valid for a short time so we need to use it to get an access token which is what we will actually use to do the REST calls. Here is the code to get the token:
private void GetToken() {
string URI = "https://login.salesforce.com/services/oauth2/token";
StringBuilder body = new StringBuilder();
body.Append("code=" + code + "&");
body.Append("grant_type=authorization_code&");
body.Append("client_id=" + clientID + "&");
body.Append("client_secret=" + clientSecret + "&");
body.Append("redirect_uri=" + redirectURL);

string result = HttpPost(URI, body.ToString());

}

This time instead of passing the parameters as query string we will pass them in the body of the post. You can see that we add parameters for the code returned in the last step, the clinet_id (Consumer Key), client_secret (Consumer Secret) and redirect_uri, then call an HttpPost. The HttpPost is simply a wrapper function around a System.Net.WebRequest object. You can see the full code in the download.

The result returned from the post will be the JSON encoded authentication data:

{
\"id\":\"https://login.salesforce.com/id/0axD7230dz0xrrP/x0e7f0D0A039F1y\",
\"issued_at\":\"1288375889300\",
\"refresh_token\":\"5APp8axZfY11MvXxUzgcRXyJ6zGtoLbD66hgHfx97d9Vklp7uFRmB6minfJwRJr_Ea4Zh563C0s_eg==\",
\"instance_url\":\"https://na5.salesforce.com\",
\"signature\":\"W11FfBhvQ1kwXvNsNTas+Gn3812XRmPL2utxxKbEqss=\",
\"access_token\":\"K0DT029060yJrrP!AR4AQJMczwx9435JeGyhsY40M.OM1BJo5c72z9Hb.F6T5lvqX992pt0KPabj8Snx7L1CqaKxUi7wixxcnfIa9UDY1KiXl0fb1\"

}

If you are using .NET Framework 3.5 or 4, the easiest way to parse this is to use a JavaScriptSerializer call from the System.Web.Script.Serialization namespace. First I created a class to put the data into.

public class TokenResponse
{

public string id { get; set; }
public string issued_at { get; set; }
public string refresh_token { get; set; }
public string instance_url { get; set; }
public string signature { get; set; }
public string access_token { get; set; }

}

Then we can use the following code to parse the response. This will convert the JSON into an instance of the TokenResponse class.

JavaScriptSerializer ser = new JavaScriptSerializer();
token = ser.Deserialize<TokenResponse>(result);

Now the authentication process is complete, so we can actually use this token to call a REST function. We start with a wrapper function that does an HTTP GET.

public string HttpGet(string URI, string Parameters)
{

System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Method = "GET";
req.Headers.Add("Authorization: OAuth " + token.access_token );
System.Net.WebResponse resp = req.GetResponse();

if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();

}

You will notice that I am adding the access_token we got in the last step as the Authorization header. To actually call this routine we do the following:

string s = HttpGet(token.instance_url + @"/services/data/v20.0/", "");

We are doing the get using the instance URL returned in the last step, and calling the REST function “/services/data/v20.0/”. This will return a list of the available REST resource and will look something like this:

{
"sobjects":"/services/data/v20.0/sobjects",
"search":"/services/data/v20.0/search",
"query":"/services/data/v20.0/query",
"recent":"/services/data/v20.0/recent"
}

So there are the basics of how to get started with the SFDC REST API. You can download the full code in a Visual Studio 2010 here:

Visual Studio 2010 Salesforce REST API Demo

You can find more information on the Developerforce web site:

Getting Started with the Force.com REST API (Java)

REST API Resource Page

REST API Documentation

Monday, September 6, 2010

LightSwitch Concurrency

 

I was curious how LightSwitch dealt with database concurrency, so I setup a little test to find out. I started with the sample application I have been working on in my previous posts. First I published the application then ran the setup and finally started two instances of the application. Next I added a new record, and then opened it for editing in both instances. In one instance I made a change to the Address field and saved the record. In the second instance I made a change to Start Date field and clicked save. When I did this LightSwitch detected the concurrency violation and displayed the following screen:

clip_image002

Here for each conflicting field you receive a drop down menu where you can select between the value on the server and the one from your instance.

Saturday, September 4, 2010

LightSwitch Query and Details Screens


In my first posting on LightSwitch I showed how to setup a screen to create a new record. This isn't very useful without a way to view and edit records. In this posting I will show how to setup a search and details screen.

I am going to start with the same Employee table I created in the first post:

clip_image002

Next I created a new Search screen for Employees. When you run the app you will get the new search screen:

clip_image004

On this screen you can browse records, search from them, export them to Excel and click the Employee name to edit the record. This brings up a couple questions. First, where does the edit screen come from? It's not the same as the Create screen we started with. Turns out LightSwitch dynamically creates the edit screen when you view the record. You can easily override this by creating a new Details Screen like this:

clip_image006

If you keep the Use as Default Details Screen option checked it will become the details/edit screen that opens when you click on a record.

The next question is how do you change the field that you click to view a record? This is not entirely intuitive; you need to make the change in the table view. Select the table, and then at the bottom of the properties window set the Summary Property to the one that you want to be clickable. You can also change the Display Name which will become the name at the top of the column. In this example I am using the Id as the Summary Property:

clip_image008

To finish this you need to go back to the editor for the SearchEmployee screen and add the FirstName into the field list:

clip_image010

Now when you run the application the Id will be clickable to take you to the detail/edit screen.

clip_image012

Sunday, August 22, 2010

LightSwitch Custom Controls Sizing

When I was working on my last post I couldn't figure out how to get my custom control to auto size when the screen was resized. After looking at this a little closer I found the trick to doing this. First in the custom control's XAML change the column sizes so they are relative.

<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>

After you have re-built the control return to the designer for the CreateNewEmployee screen. Click on the Name control and then scroll to the bottom of the properties list and set the Content Size to Stretch.



clip_image002



Now the textboxes in the custom control will stretch when the page is re-sized.

Friday, August 20, 2010

Basic LightSwitch Custom Controls

Out of the box LightSwitch comes with a limited set of visual controls, but since the UI is rendered in Silverlight you can include other Silverlight controls including your own custom controls. Here I will provide a simple example of how to make your own custom control, its easier then you might think. To do this you will need to install LightSwitch on top of a full version of Visual Studio 2010. I am going to start with a simple table, then add a Create New Employee screen to the application. I am going to create a custom control that formats the First, Last and Middle name text boxes in a different way.

clip_image002

  1. In your LightSwitch solution add a new Silverlight 4 Class Library project. I am going to call it EmployeeDbControls.

  2. To the new project add a Silverlight User Control item. I am going to call it NameControl.

  3. Here is the XAML I am going to add to that control:
    <Grid x:Name="LayoutRoot" DataContext="{Binding Screen.EmployeeProperty}">

    <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="150" />
    <ColumnDefinition Width="150" />
    <ColumnDefinition Width="150" />
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">First</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Middle</TextBlock>
    <TextBlock Grid.Column="2" Grid.Row="0">Last</TextBlock>
    <TextBox Margin="5" Grid.Column="0" Grid.Row="1" Text="{Binding FirstName,Mode=TwoWay}"></TextBox>
    <TextBox Margin="5" Grid.Column="1" Grid.Row="1" Text="{Binding MiddleName,Mode=TwoWay}"></TextBox>
    <TextBox Margin="5" Grid.Column="2" Grid.Row="1" Text="{Binding LastName,Mode=TwoWay}"></TextBox>

    </Grid>

    This will create three textboxes laid out in a grid. The important thing to note here is the data binding properties. First we need to set a DataContext so I am did this on the grid so that all the controls in the grid can use it. In the DataContext binding the EmployeeProperty comes from the editor for the Create New screen, you can see it just above the field names:

    clip_image004


    The second part of the binding is in the textboxes. Here we simply bind to the field names in the record. Note that the mode must be set TwoWay so we can edit and display.


  4. Once the control is complete, build the project.

  5. Return to the designer screen for the Create New screen and remove the FirstName, MiddleName and LastName fields.

  6. Click on the line that says "(TOP ROW) Vertical Stack", then click the Add Layout Item menu and select Custom Control. You will see this screen:

    clip_image006


  7. Click Add Reference… and select the EmployeeDbControls project.

  8. Drill down on the EmployeeDbControls reference and select NameControl. Click OK to close the References screen.

    clip_image008


  9. Click and drag the NameControl up above the Address field.

  10. Make sure the NameControl is selected, then in the property window change the Display Name from ScreenContent to Name.

  11. Run the application. When you open the CreateNewEmployee screen you will see the new control.

clip_image010

If I wanted to I could create a Details Screen for the Employee table and add the new name control to that screen so we have the same control when we are editing a record.

This is a very basic example but will get you started with designing custom controls for LightSwitch.

LightSwitch Table Relationships


In my last post I introduced Microsoft's new RAD tool called Visual Studio LightSwitch. In the example in that post I showed how to create an application with a single table, now I’ll explain how to do table relationships.

Last time I created an employee table. Now I want a table that lists the work history for each employee. First add a new table called WorkHistory. You will notice that I did not put a foreign key on the WorkHistory table to relate it to the Employee table; LightSwitch will take care of this for you.

clip_image002

A note on table naming. LightSwitch tries to be very helpful in naming your tables. The name you type at the top of the table editor is actually the entity name, it represents a single thing. The name that shows up in the Solution Explorer is the table name which LightSwitch will try to pluralize for you. So the WorkHistory entity creates a table called WorkHistories. For this reason do not pluralize the entity name. If you were to enter WorkHistories as the entity name you would end up with a table called WorkHistoriesSet.

Once you have created the table you need to setup the relationship by clicking the Relationship… button which brings up the relationship designer:

clip_image004

The options are set at the top of the screen and relationship will be displayed both graphically and in plain English. The Navigation Property is the name of the property that will be created on each table to manage the relationship.

The change will not automatically show up in the Add New screen I created last time, so the easy fix is to delete that screen and add a new one. When you select Employee for the Screen Data you will now get the option of including the Employee WorkHistories on the screen.

clip_image006

When you run the application you will now have an Add New screen where the employee's details and work history can be edited.

clip_image008

Microsoft Visual Studio LightSwitch Beta 1

LightSwitch is a new tool from Microsoft for doing rapid application development of data driven applications. It's sort of like Microsoft Access but with a much more robust underlying architecture. The design tool is actually a version of Visual Studio 2010 that has been simplified to allow even someone without programming skills to build a database and the front end application to manipulate it without having to write any code. On the back end LightSwitch can use SQL Server (including SQL Express), SQL Azure or SharePoint for data storage, and uses Silverlight 4 either in our out of browser for the user interface.

LightSwitch Beta 1 is currently available to MSDN subscribers, and will be available to the general public on August 23rd, 2010.

Installation

LightSwitch is currently being provided as a DVD ISO image. Installation is very simple. Currently the only option during install is where you want to install the program. The installer will install any pre-requisites that you need along with an instance of SQL Server 2008 Express edition. If you already have Visual Studio 2010, LightSwitch will be integrated into the existing install. I have installed this on a Windows XP system that already had VS 2010, and a Server 2003 machine that did not and both install worked without any problems.

Building an Application

It is extremely easy to get an application up and running. I created a little employee tracking application with the ability to search records, add new records and edit existing ones in literally less the 5 minutes.

When you startup Visual Studio there will be two new project types one for Visual Basic and one for C#.

clip_image002

Next you will be prompted to Create new table or Attach to external database. When you select Create new table you get a classic table editor screen. Here you can enter your field names; select their data type and indicate if they are required fields. You can also change some of the other field settings using the property window. This process has been made very user friendly. If there is something it doesn’t like about a field name as you are typing it you will immediately get a tooltip explaining the error. The data types have been simplified from what you would see in SQL Server, for example no VarChar, NVarChar, or Text, just a String data type. There are also special data types for things like e-mail addresses and phone numbers.

clip_image004

Once your table is complete click the Screen… and you will be able to add the visual parts of your application. I added two screens, a New Data Screen to add records and a Search Data Screen to search for records. You simple select the screen type, and then select the table it will work with from the Screen Data drop down.

clip_image006

At this point you have a fully working application that you can execute.

Here’s a screen shot of the add screen:

clip_image008

And here is the search screen

clip_image010

Initial Reaction

I am not a big fan of tools like this that dumb down the development process. They tend to get you 80% of the way to what you want to build, but leave no way of getting the remaining 20% that would truly make the application useful. The tools is good for entering data, but the only current option for output is Excel export. It could really use a simple point and click report designer. For me the jury is still out on this tool. What is currently there is very nicely done, but it is still very limited. If Microsoft continues to improve the functionality this could be a great alternative to developing applications in Access.

More information

Here are some links to get more information on LightSwitch:

Office MSDN LightSwitch Site

Jason Zanders Weblog: Introducing Microsoft Visual Studio Light Switch

Jason Zanders Weblog: LightSwith Architectural Overview

Sunday, May 30, 2010

XAML Presentation Questions

During my presentation at PhillyNJ.NET there were a couple questions I could not immediately answer.

x:Name

When you create a blank Silverlight project in Visual Studio you start with the following code:

<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">

</Grid>
</UserControl>

Someone questioned why the Name property on the Grid is in the ‘x’ namespace when other properties aren’t. The ‘x’ namespace is the base XAML namespace. The XAML standard specifies a name property that applies to all elements which is references by x:Name. Classes that are serialized into XAML can also have their own Name property, for example the Grid element has a Name property. In WPF and Silverlight the Name property on the objects is mapped directly to the x:Name XAML property, so you could use either x:Name or Name and everything would work fine. The use of x:Name just seems to be done by convention.

Label vs Textblock

One of the more common controls in Winforms is the label control. There is no label control in the base Silverlight installation, but there is one if the Silverlight Toolkit. This brings up the question, what is the difference between a label and the standard TextBlock control? It turns out TextBlock isn’t technically a control. It derives from FrameworkElement, whereas Label derives from ContentControl which gives label extra functionality that TextBlock doesn’t have. For example a Label can use a control template, and can contain content other then plain text.

Non-Rectangular Windows

In Winforms it was a little tricky to do non-rectangular windows, but it’s actually pretty easy in WPF. There is a good example here, http://devintelligence.com/2007/10/shaped-windows-in-wpf/. I have not seen any indication that you can do non-rectangular windows in Silverlight. This actually wouldn’t be to useful since you would still be constrained to the rectangular browser window.

XAML UI for WPF and Silverlight Presentation

Thanks to everyone who attended my presentation at the May meeting of PhillyNJ.NET. Here are the Visual Studio 2010 projects for that I used in the demo:

XAML Basics Demo

XAML Data binding Demo