Sunday, December 2, 2012

Windows 8 + Salesforce.com Part 4

Over the past three posts I have shown how to build a Windows 8 Windows Store Application that will display the Account records from Salesforce.com. As the application is currently built the user needs to login to Salesforce each time it is run. In this post I will show how to keep the use logged in using a refresh token.
Before I continue  a note about the architecture of this demo. I had originally planned to build this using the Model-View-ViewModel (MVVM) design pattern which is very common to XAML applications, but decided for the sake of simplicity to just do a basic event driven architecture for now. At a later date I might do some posts on how to change this into an MVVM based application.
Ok, now on to the updates we are going to make to the program from Part 3. First we need to add a function to sfdcLibrary.cs to get an access token given a refresh token.

public async Task<bool> RefreshToken(string refreshToken)
{
    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);
    var response = await HttpPost(URI, body.ToString());

    if (response.StatusCode != System.Net.HttpStatusCode.OK) return false;

    var data = await response.Content.ReadAsStringAsync();
    AccessToken = Deserialize<TokenResponse>(data);

    return true;
}

This function works just like the one we used to get the initial access token, but this one starts from a refresh token and uses that to get the access token. We are also going to change the AccessToken to a public property since we will need to reference it outside of the class.

public TokenResponse AccessToken { get; set; }

Now lets modify AccountsView.xaml to include a UI to login and logout.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
    <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" IsHitTestVisible="false" Style="{StaticResource PageHeaderTextStyle}"/>
    <StackPanel Grid.Column="2" Orientation="Vertical" Margin="10,10,10,10" >
        <Button Name="UILogout" HorizontalAlignment="Center" Click="UILogout_Click">Logout</Button>
        <Button Name="UILogin" HorizontalAlignment="Center" Click="UILogin_Click">Login</Button>
        <CheckBox Name="UIStayLoggedIn" HorizontalAlignment="Center">Stay Logged In</CheckBox>
    </StackPanel>
</Grid>

This is the XAML markup for the gird that forms the header of the page. I have added a third column to the grid to hold the controls. I also added a StackPanel with a Login button, Logout button and a check box to control whether the application should stay logged in or not.

To MainPage.xaml.cs we are going to add two functions to control the UI state.

private async void LoggedIn()
{
    UILogin.Visibility = Visibility.Collapsed;
    UIStayLoggedIn.Visibility = Visibility.Collapsed;
    UILogout.Visibility = Visibility.Visible;
    var acc = await App.SFDC.ReadAccounts();
    model.Accounts = acc.records;
}

This function sets the form to a logged in state. The UILogin and UIStayLoggedIn controls are hidden, UILogout control shown and the viewmodel loaded with a list of accounts. You will notice that in XAML Visibility isn’t just a Boolean, it actually has three states. Visible displays the controls, Hidden hides the control but still reserves space for it in the UI and Collapsed hides it and doesn’t reserve space for it. The second function is similar and sets a logged out state.


private void LoggedOut()
{
    UILogin.Visibility = Visibility.Visible;
    UILogout.Visibility = Visibility.Collapsed;
    UIStayLoggedIn.Visibility = Visibility.Visible;
    model.Accounts = null;
    App.SFDC.AccessToken = null;
}

Again we set the control visibility, clear the accounts from the model and clear the access token.  Next we need to change the LoadState function.


protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    LoggedOut();

    this.DataContext = model;

    if (ApplicationData.Current.LocalSettings.Values["refreshToken"] != null)
    {
        if (await App.SFDC.RefreshToken((string)ApplicationData.Current.LocalSettings.Values["refreshToken"])) LoggedIn();
    }
}

In this function we start by setting the UI to the logged out state and then set the data context to the viewmodel. In the next line we check the users local settings to see if we have saved a refresh token there. If we do have a saved token we use it call RefreshToken and if this is successful we set the logged in state.

Finally we need handlers for the Login and Logout button click events.

private async void UILogin_Click(object sender, RoutedEventArgs e)
{
    if (await App.SFDC.LoginSalesforce())
    {
        if ((bool)UIStayLoggedIn.IsChecked) ApplicationData.Current.LocalSettings.Values["refreshToken"] = App.SFDC.AccessToken.refresh_token;
        LoggedIn();
    }
}

When the login button is clicked we call the LoginSalesforce function which does the OAuth authentication. If the user has checked the stay logged in checkbox we store the refresh token that was returned as part of the access token in the users local settings so we can use it later to re-authenticate without the user having to re-enter their credentials. If the checkbox wasn’t checked we just login for this one session and the user will need to login again next time the application is run. Finally the Logout event handler.

private void UILogout_Click(object sender, RoutedEventArgs e)
{
    ApplicationData.Current.LocalSettings.Values.Remove("refreshToken");
    LoggedOut();
}

When the user logs out we clear the refresh token from the user’s configuration settings and set the form to the logged out state.

You can download the source for this version of the application here.

Saturday, November 24, 2012

Windows 8 + Salesforce.com Part 3

In my last two posts I showed how to connect to Salesforce.com from a Windows 8 Windows Store application, and then how to retrieve a list of accounts. In this article I will show how to display the accounts.
The first thing we need is a view model class to hold the data we want to display. For an application this simple we could get away without a view model but creating one is a good practice and it does make things easier for more complex applications.

public class AccountsViewModel : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<sfdcAccount> accounts;

    public ObservableCollection<sfdcAccount> Accounts
    {
        get { return accounts; }
        set {
            accounts = value;
                if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Accounts"));
        }
    }
  
}

You will notice that that class implements the INotifyPropertyChanged interface. This is needed so that XAML data binding can detect changes to the object. The implementation of the interface is in the first line, the PropertyChanged event which needs to be called whenever a property of the object changes. The rest of the class is a property that holds an ObservableCollection of sfdcAccounts. In the setter you will see that we raise the PropertyChanged event passing in a reference to the object and a PropertyChangedEventArgs object containing the name of the property. Even though this is an ObservableCollection it only allows the data binding to see when items are added to or removed from the collection. The PropertyChanged event is needed to notify data binding if the actual collection object referenced by the property changes.

Next we need a new page to display the accounts, so from the project select Add/New Item, then select Items Page and change the name to AccountsView.xaml. You will get a message asking to add files to your project, select Yes. To have this page displayed at startup open App.xaml.cs and in the OnLaunched function change MainPage in the following line to AccountsView.

if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))

While we are in App.xaml.cs we need to create an sfdcLibrary object that we can use throughout our application. To do this add the following property

public static sfdcLibrary SFDC { get; set; } 

then add the following line to the App() constructor

SFDC = new sfdcLibrary();

Now lets work on the AccountsView we created earlier. In AccountsView.xaml.cs you will notice that the class inherits from LayoutAwarePage. This is a helper class that is part of the Windows Store Application template which wraps the base Page class and provides help with things like navigation.  The first change we need to make in this file is to add this private variable which will hold the view model

private AccountsViewModel model = new AccountsViewModel();

Next replace the LoadState function with this one

protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    this.DataContext = model;
    if (await App.SFDC.LoginSalesforce())
    {
        var acc = await App.SFDC.ReadAccounts();
        model.Accounts = acc.records;
    }
}

LoadState is called in response to the OnNavigatedTo event which happens whenever a page is displayed.  The first thing we do in this function is set the page’s DataContext property to the view model. DataContext will be used as the base for all the data binding we do on the page. Next we call the LoginSalesforce function to do the OAuth login and if it is successful we read the account list from Salesforce and assign it to the Accounts property of the viewmodel.

We are almost done, the final changes we need to make are in AccountsView.xaml. First in the Page.Resources section change the source to point to the Accounts property of the view model like this

Source="{Binding Accounts}"/>

This will bind the Accounts list in our view model to the GridView which will display the data. Next thing we need is a DataTemplate to be used to display each account.

<DataTemplate x:Key="StandardItemTemplate">
    <StackPanel Orientation="Vertical" Width="200" Height="200" Background="#FF07B3F3"  >
        <TextBlock  Text="{Binding Name}" HorizontalAlignment="Center" Margin="20,10,20,0" FontWeight="Bold" TextWrapping="Wrap" FontSize="20" TextAlignment="Center" />
        <TextBlock Text="{Binding AccountNumber}" HorizontalAlignment="Center" Margin="20,10"/>
    </StackPanel>
</DataTemplate>

The template starts with a 200x200 StackPanel with a blue background. Inside this we have two TextBlocks, the first one will show the Name of the account and the second will show the AccountNumber. Finally we need to change the ItemTemplate property of the GridView to use the template we just defined.

ItemTemplate="{StaticResource StandardItemTemplate}"

StaticResource tells XAML that we are using a resource defined elsewhere in the markup, in this case in our Page.Resources section. StandardItemTemplate is the Key property we defined in the template markup.

If we run the application we will first get a Salesforce login screen. Once the correct username and password are entered all the accounts in the Salesforce instance will be displayed.

image

Now that we have a basic working application I will expand on it in future blog posts.
You can download the full source for this application here. To use this code you will need to put your ClientID and ClientSecret in the sfdcLibrary class.

Saturday, November 17, 2012

Windows 8 + Salesforce.com Part 2

This is the second part of a series of posts on how to create a Windows 8 WinRT application that uses the Salesforce REST API. In the first part I showed all the code needed to authenticate to Salesforce. In this post I will show how to to retrieve data from Salesforce. In part 3 we will pull all the pieces together a display the data.
First thing we need is an object model to hold the data we retrieve from Salesforce. For the purposes of this application we will read a list of Accounts. Let’s start with a class to hold a single Account:

public class sfdcAccount
{       
    public sfdcAttributes Attributes { get; set; }

    public string Id { get; set; }
    public string Name { get; set; }
    public string AccountNumber { get; set; }
    public string Type { get; set; }
    public string Phone { get; set; }
    public string WebSite { get; set; }
    public string Industry {get; set;}
    public string BillingStreet { get; set; }
    public string BillingCity { get; set; }
    public string BillingState { get; set; }
    public string BillingPostalCode { get; set; } 
    public string CustomerPriority__c { get; set; }
 }

The first property is of type sfdcAttributes and will be used to hold meta-data about the record, we will look as this class next. The rest of the properties are a selection of fields from the Account record. There are more fields then this in Salesforce but this is a good group to work with. Here is the sfdcAttributes class that holds the type of the record and it’s unique URL. This can be used with any Salesforce object, not just the Account.

public class sfdcAttributes
{
    public string Type { get; set; }
    public string Url { get; set; }
}

Finally, we need a class to hold the meta data that is returned when we query for a group of records.

public class sfdcCollection<T>
{
    public bool done { get; set; }
    public int totalSize { get; set; }
    public string nextRecordsUrl { get; set; }
    public ObservableCollection<T> records { get; set; }
}

I made this a generic class so that it can be used for a collection of any Salesforce object, for example sfdcCollection<sfdcAccount> for a collection of accounts. The records property will hold the collection of sfdcAccounts. In the Windows forms application I made this a List<T> but to facilitate XAML data binding I have made it an ObservableCollection<T> which allows the binding system to detect changes to the collection. You will need to include the System.Collections.ObjectModel namespace to use the ObservableCollection.

In the last post we created a class called sfdcLibrary to hold all our Salesforce related code. We will add the following property and constructor to this class.

public string VersionUrl { get; set; }

public sfdcLibrary()
{
    VersionUrl = "/services/data/v26.0";
}

The Salesforce REST supports multiple versions of the API, so whenever you make a call to the API you must use the URL for the appropriate version. This variable will allow us to specify the version we want to use in one place. In this case we will hard code it to v26.0 of the API.

Now that we have an object model to hold the data we want to display we need some code to read it from Salesforce.


public async Task<sfdcCollection<sfdcAccount>> ReadAccounts()
{
    var query = accessToken.instance_url + VersionUrl + "/query?q=SELECT id,accountNumber,name,BillingStreet,BillingCity,BillingState,BillingPostalCode,CustomerPriority__c,Type,Phone,WebSite,Industry from account";

    var resp = await HttpGet(query);

    sfdcCollection<sfdcAccount> accts = null;

    if (resp.StatusCode == System.Net.HttpStatusCode.OK)
    {
         accts = Deserialize<sfdcCollection<sfdcAccount>>(await resp.Content.ReadAsStringAsync());
    }
    return accts;
}

This function will read all the Account records from your Salesforce instance, and return them in an sfdcCollection of sfdcAccounts (the Task<> is needed  because this is an async function). Reading all the records isn’t really practical in a real world application since it might return a very large number of records, but it is ok for the purposes of this demonstration.

In the first line of the function we build the URI to query for the Account fields we want. The URI starts with the instance URL, we then appends the version URL to this and finally the SOQL query.  The second line uses the HttpGet function to get the results of the query in the form of an HttpResponseMessage object, we will look at HttpGet in a second. Finally we check the HTTP status from the request and if it was successful  we use the Deserialize function which I showed in the last post to turn the JSON response into a object model we can work with.

The final function we need to look at is HttpGet.

public async Task<HttpResponseMessage> HttpGet(string uri)
{
    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
    client.DefaultRequestHeaders.Add("Authorization", "OAuth " + accessToken.access_token);

    return await client.GetAsync(uri);
}

This works pretty much the same as the HttpPost function I showed in the last blog post.

We now have all the code we need to authenticate to Salesforce and read back a collection of Accounts. In the next post I will show how we display the Accounts.

Tuesday, November 6, 2012

Windows 8 + Salesforce.com Part 1

Over the past year I have written a bunch of articles about interfacing to Salesforce.com and Windows 8 WinRT application, so I thought it was about time to combine the two. This is the first of a series of articles that will show how to write a Windows 8 Win RT application that accesses Salesforce through the REST API.
The first thing you will need to do is setup the REST API in your instance of Salesforce. I covered how to do this in my Salesforce REST API post. Once this setup is done you will get a Consumer Key and Consumer Secret which we will use in a little bit.
To get started with our application,  open up Visual Studio 2012, create a new project and select Visual C#, Windows Store, Blank App (XAML). This will give us a simple base template to build on.
The next step in using the Salesforce REST API is to use OAuth to authenticate to Salesforce. The basic steps for doing this are the same as in the Windows forms app that I described in my original posts, but the details are a little different when implementing the process in a WinRT app. Add a class called sfdcLibrary to the project to hold all the Salesforce access functions, and add the following namespaces:

using System.IO;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using Windows.Security.Authentication.Web;
using System.Net.Http;

Next add the following private variables to the class

private string clientID = "[Your Consumer Key]";
private string clientSecret = "[Your Consumer Secret]";
private string redirectURL = "resttest:callback";

private TokenResponse accessToken = null;

Be sure to put in the consumer key and consumer secret you got when you setup Remote Access in Salesforce. TokenResponse is a class that will hold all the details that the authentication process sends back. It looks like this.


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; }
}

Now we can look at the code for doing the OAuth login, here is the first part

public async Task<bool> LoginSalesforce()
{
    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);

    var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(authURI.ToString()), new Uri(redirectURL));

    if (result.ResponseStatus != WebAuthenticationStatus.Success) return false;

First thing you will notice  is the async keyword and the return type of  Task<bool>. These will allow this function to be called asynchronously and are also needed because we will be using async functions. Next we build the URI that is needed to bring up the Salesforce login page to authenticate the user. In the Windows forms application we used a web browser control to handle this, but it turns out to be much easier to do in WinRT by using WebAuthenticationBroker class.


On the WebAuthenticationBroker we call the AuthenticateAsync method. The first parameter just specifies that we don’t want any special options. The second is a URI object  that contains the URI of the page that will do the authentication. When the method is called a new page will be displayed automatically in the application and the web page pointed to by the URI will be displayed so the user can login. The final parameter of the method is used to determine when the login process is complete. It contains the URI that the login page will re-direct to when done, so the AuthenticateAsync function will look for this address to know when to return from the method.

The AuthenticateAsync method will return a  WebAuthenticationResult object that has a ResponseStatus property. This property will have one of three values, Success if the authentication succeeds, UserCancel if the user click the back arrow to cancel the login, or ErrorHttp if there was some sort of HTTP error, for example if the login page could not be found. In this case, if the status is not success we will return false from the function.

If the authentication succeeds we will get something like this back in the WebAuthenticationResult.ResponseData property:

resttest:callback?code=jPrxA6bDXmdSBjzBFDRCwY1D09JvsHbzaL5.ISrdh2PE247HeZH.Qxv4_9p1XwXSMR78xvN8Jw%3D%3D

We need the code so we will use the next two lines to extract it.

string response = result.ResponseData;
string code = response.Substring(response.IndexOf("code=") + 5);

Now we can do the second part of the authentication process

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);
var tokenResponse = await HttpPost(URI, body.ToString());
if (tokenResponse.StatusCode != System.Net.HttpStatusCode.OK) return false;

var data = await tokenResponse.Content.ReadAsStringAsync();
accessToken = Deserialize<TokenResponse>(data);
return true;


The first line contains the URI used to request an access token. Next we build up the body of the request, then call the HttpPost function to get the access token. We will look at this function in a minute. What we get back from the HttpPost function is a HttpResponseMessage object. The HttpPost function doesn’t throw any exceptions if there is an HTTP error so in the next line we need to check the StatusCode property to be sure the request succeeded. If the response succeeded we use the ReadAsStringAsync function to read the data that was returned. Finally we deserialize the JSON data returned from the HttpPost function to create the accessToken object. We will look at the Deserialize function in a minute.

Now lets look at the two helper functions that the login function uses, first HttpPost.

public async Task<HttpResponseMessage> HttpPost(string uri, string body)
{
    var client = new HttpClient();
    var content = new StringContent(body);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    return await client.PostAsync(uri, content);
}

Just like the login function we are making this one async. It accepts the URI  for the request and the data to be sent in the body of the request and it will return an HttpResponseMessage object. In the Windows forms version we used the WebRequest class but here we will use the HttpClient class which is a little easier to use. First we create an instance of HttpClient. Next we create a StringContent object from the body parameter and then in the next line set the proper ContentType header. Finally we execute the PostAsync method passing in the URI and content then returning the HttpResponseMessage object.

The final function we need to look at is the Deserialize function.

public static T Deserialize<T>(string json)
{
    var bytes = Encoding.Unicode.GetBytes(json);
    using (MemoryStream stream = new MemoryStream(bytes))
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(stream);
    }
}

In the Windows forms app we use the JavaScriptSerializer class to deserialize JSON, but this is not available in WinRT. The alternative is to use the DataContractJsonSerializer. It’s a pretty straight forward function so I am not going to go into the details. Just note that it’s a generic function so T will contain the type that we want to deserialize the Json into.

We now have all the code we need to do OAuth authentication with Salesforce from a WinRT application. In my next post I will show how to retrieve data and then we will get into actually using this code to display the data.

Thursday, October 25, 2012

JSON.NET

Throughout the articles I have been writing on the Salesforce.com REST API I have been working with a lot of JSON data. One nice thing about the Salesforce REST API is that you have the choice to work with either JSON or XML data, but what if you are working with an API that only supports JSON? One option is to use the JavaScriptSerializer class that is available in the .NET Framework. You can read my Salesforce REST API Query Deserialization post for information on how to use this class. One of the downsides of this class is that it only supports serialization and deserialization of object models to and from JSON. Another more flexible option I have found for handling JSON is the JSON.NET library.
JSON.NET does support serialization between object and JSON, and claims to do it faster then JavaScriptSerializer, but it also provides some other ways of working with JSON including support for LINQ to JSON.
To get started with JSON.NET you will need to download the library from the Codeplex site. Inside the zip file you will find the source code along with pre-compiled binaries for Framework 2.0, 3.5 and 4.0 as well as versions for Silverlight, Windows Phone and WinRT. Copy the appropriate binaries to your project’s bin folder and then add a reference to it to your project. For the purposes of this demo I have also imported the Newtonsoft.Json.Linq namespace.
In the demo I am going to use this chunk of JSON which I have loaded into a string called jsonData.

{
  "totalSize" : 4,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E0000000qhJeIAI"
    },
    "Id" : "015E0000000qhJeIAI",
    "Name" : "TestDocument",
    "FolderId" : "005E0000000V7EpIAK",
    "DeveloperName" : "TestDocument11"
  }, {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E0000000qV91IAE"
    },
    "Id" : "015E0000000qV91IAE",
    "Name" : "test",
    "FolderId" : "005E0000000V7EpIAK",
    "DeveloperName" : "test"
  }, {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E0000000qhIdIAI"
    },
    "Id" : "015E0000000qhIdIAI",
    "Name" : "test pdf",
    "FolderId" : "005E0000000V7EpIAK",
    "DeveloperName" : "test_pdf"
  }, {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E00000019TzdIAE"
    },
    "Id" : "015E00000019TzdIAE",
    "Name" : "Test in Folder",
    "FolderId" : "00lE0000000zg7MIAQ",
    "DeveloperName" : "Test_in_Folder"
  } ]
}

To work with the JSON the first thing we need to do is parse it with this line of code:

var obj = JObject.Parse(jsonData);

Once we have the JObject created it’s pretty easy to access the data in our JSON. For example what if we wanted to get the totalSize property. The code would look like this:

int totalSize = (int)obj["totalSize"];

Since totalSize is at the top level of the JSON we can use the property name as an index into obj and then cast the result to an integer. What if we now want to dig deeper into the JSON, for example to get the Id property of the first record.

string id = (string)obj["records"][0]["Id"];

In this line we first reference the records array in obj, then get the first record with the [0] index, and then finally the property name Id. We can keep stringing together numeric indexes and property names to get to any piece of data in the JSON. For example to get the url attribute in the first record we would use:

string url = (string)obj["records"][0]["attributes"]["url"];

So far we have only looked at accessing single value, but it’s also easy to iterate through an array.

var records = (JArray)obj["records"];

for (int i = 0; i < records.Count(); i++)
{
    Console.WriteLine(records[i]["Id"]);
}

To make the code a little easier to follow we first get the records array from obj which will return a JArray object. Now we can use a for loop to iterate through the elements of the array then use records[o][“Id”] to get the ID from each record.

Saturday, October 20, 2012

.NET Rocks Road Trip

One of my favorite podcasts is the programming podcast .NET Rocks! Hosted by Carl Franklin and Richard Campell the show has had over 800 episodes since it’s debut in 2002. The show primarily focuses on development with .NET and other Microsoft technologies but also talks about general programming topics. Carl and Richard also host a podcast called The Tablet Show which focuses on mobile development for both Microsoft and non-Microsoft platforms.

Currently Carl and Richard are doing a road trip where they will be recording shows in 37 different cities all around the country. Today I had the pleasure of attending their event at the Microsoft office in Malvern PA. The road trip continues until December so I check out the list of future cities and see if there is one near you, I promise you will have a great time!

Here are some picture from today’s event.

DNR1
The 37’ RV they are traveling the country in.

DNR2
The Microsoft office in Malvern.

DNR3
Richard (center), Carl (right) and their guest for this show Glenn Block.

DNR4
Richard and Carl.

DNR5
Carl jamming for the crowd.

DNR6
Hanging out with the guys in the RV after the show and Carl providing a little entertainment.

Friday, October 5, 2012

Salesforce REST API Folders and Documents

In a recent post I described how to retrieve a file stored in Salesforce using the REST API. In that post I showed how to retrieve a document using its internal ID number which really isn’t to useful in practice, it would be better to retrieve it by name. In this post I will show how to look at folder and file information in Salesforce. All the queries in this post can be executed using the code I showed in the Salesforce REST API Query post.
Let’s start by looking at folders. You can query for a list of folders by using this SOQL statement:

SELECT ID,Name,DeveloperName FROM folder

This will return a JSON response something like this:

{
  "totalSize" : 1,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Folder",
      "url" : "/services/data/v24.0/sobjects/Folder/00lE0000000zg7MIAQ"
    },
    "Id" : "00lE0000000zg7MIAQ",
    "Name" : "Test Folder",
    "DeveloperName" : "Test_Folder"
  } ]
}

In the response you will see a record for each Folder in your Salesforce instance with fields for the ID, the folder name, and the DeveloperName which is a unique name without any spaces.

Now that we have the folder ID we can query for all the documents in that folder.

SELECT ID, Name, DeveloperName FROM document where Folderid='00lE0000000zg7MIAQ'

which will return a response like this:

{
  "totalSize" : 1,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Document",
      "url" : "/services/data/v24.0/sobjects/Document/015E00000019TzdIAE"
    },
    "Id" : "015E00000019TzdIAE",
    "Name" : "Test in Folder",
    "DeveloperName" : "Test_in_Folder"
  } ]
}


Just like the folder query this one returns an Id, Name and DeveloperName for each document in the folder. If you want you can also remove the where clause from that query and it will return a list of all documents no matter what folder they are in.

You might think that you could do something like this in one query using a join, but although SOQL does support joins, they don’t work with folders and documents, so you have to do the two separate queries.

Besides Id,Name and DeveloperName there are some other useful fields you can retrieve for a document.

LastModifiedById – Internal ID of the user that last modified the document record.
LastModifiedDate – Date that the document record was last modified.
CreatedById – Internal ID of the user that created the document record.
CreatedByDate – Date the document record was created.
AuthorID – Internal ID of the user who is currently selected as the author of the document.
Type – The file extension of the document.
ContentType – The MIME type of the document.
Keywords – The keywords field in the document record.
Description – The description field in the document record.
IsInternalUseOnly – The boolean Internal Use Only field in the document record.

Sunday, September 16, 2012

Windows 8 Hard Drive Problem

I have taken a break from my Windows 8 posts because I am having a problem with my Windows 8 environment.

I have a Dell Studio 540 that has worked for a couple years without any problems. To try out Windows 8 I purchased a new Seagate Barracuda 500 GB SATA drive, switched the SATA cable from my old drive to the new one and installed the Windows 8 x64 RTM from MSDN. Initially it worked ok but after about a week of off and on use I started getting corrupt files on the drive and it eventually got to the point where none of the restore tools in Windows 8 could fix the problem. At this point I ran the Seagate diagnostics on the drive but it didn’t find any problems.

I re-formatted the drive and re-installed Windows 8, and again after a couple days I got corrupt files. I also checked the event log this time and noticed NTFS errors in the log. As a final test I re-formatted the drive but installed Windows 7 this time. I have been running Win 7 on the drive for over a week now with no problems, so it appears to be an issue with Windows 8.

If anyone has seen any issues like this with Windows 8 please let me know. I’ll also post here if I find a resolution to the problem.

Saturday, September 15, 2012

Koding.com

Recently I have been trying out a new online development environment called Koding.com.  This site combines and online IDE,  a hosting environment, as well as social networking elements that  allow you to easily develop web based applications in PHP, Perl, Python and Ruby. The site is currently in a closed Beta, but you can request an invite from the login screen. It is free to try out the Beta, but the site will eventually move to a pay model. Their FAQ says that there will be an option for a small, free development environment.

Once your account is created and you click on the Develop tab you will be taken to this screen.

image

On the far left are buttons that take to various parts of the site and just to the right of that is the file structure for you hosting site. You will be assigned a sub-domain at koding.com to access your applications, in my case it is danlb2000.koding.com. The directory structure is automatically populated with some sample files to start with. In the main pane of the screen you will see the development tools, but the only one that is currently available is Ace Editor which is a basic text editor. You can double click on a file in the directory to open it for editing, or right click on a folder to get to a context menu that will allow you to create a new file.

image

Besides the text editor, there is also a terminal window that gives you access to the bash shell for you hosting server.

image

The site currently has support for both the MySQL and Mongo databases. Setting up a database is very easy. From your account settings you select Database settings, then click the plus sign on the Database Settings line to add a new database.

image

Once you select the type the database will immediately be setup and you will be provided with the host name, userid and password to access it. There is currently no graphical MySQL management tool built into the site, but I did find instructions on their wiki that explains how to install PhpMyAdmin in your site, although I haven’t tried it yet.

What I have seen so far is a very nice start at an online development environment. There are still a lot of features missing, but what has been implemented works nicely. I look forward to seeing how this site evolves over time.

Sunday, September 9, 2012

Scheduled Toast Notification

In my last post I introduced Toast Notifications for WinRT apps. In that example I had the notification show immediately, but you can also schedule a toast to appear sometime in the future. The NotificaitonsExtensions library doesn’t have direct support for scheduled toast but this is pretty easy to work around.
Here is the code for a scheduled toast:

var toast = ToastContentFactory.CreateToastText01();
toast.TextBodyWrap.Text = "You have a new message";

var schedToast = new ScheduledToastNotification(toast.GetXml(), DateTime.Now.AddSeconds(30), new TimeSpan(0, 0, 60), 5);
ToastNotificationManager.CreateToastNotifier().AddToSchedule(schedToast);


The first two lines setup a toast notification using the NotificationsExtensions library just like we did in the last example. In the next line we create the scheduled toast object, by passing four parameters to the constructor. For the first parameter we use the GetXml() function to get the XML template from our toast object. The second parameter sets the time when we want the toast to appear, in this case 30 seconds in the future. The third and fourth parameters are optional and allow you to enable the snooze capability of the notification. When the user closes the toast it will reappear after the time interval set in the third parameter  (this must be from 60 seconds to 60 minutes), and will reappear the number of time in the fourth parameter (this must be from 1 to 5).

The final line calls the AddToSchedule function to schedule the notification.

Once the notification has been created it will pop up at the scheduled time even if the program is no longer in memory. There is a function called RemoveFromSchedule that can be used to remove the notification if you have still have a reference to the ScheduledToastNotification object. In most cases we won’t still have a reference to this object so we need a way to find it. To do this we will first have to add a unique identifier to the ScheduledToastNotification object:

schedToast.Id = "ToastID1";

Here I am just using a fixed string, but for a real application you will have to come up with some method of uniquely identifying notifications. After the notification has been created you can use the Id to find and remove it:

var scheduled = ToastNotificationManager.CreateToastNotifier().GetScheduledToastNotifications();
foreach( ScheduledToastNotification notify in scheduled) {
    if (notify.Id == "ToastID1")   ToastNotificationManager.CreateToastNotifier().RemoveFromSchedule(notify);
}

In this code the first line gets a list of all scheduled toast notifications that our app has created. The next two lines will iterate through this collection looking for the Id of the notification we want to remove, then calling RemoveFromSchedule to remove it.

Monday, September 3, 2012

Toast Notifications

There is one other type of notification that I didn’t cover in my original articles on WinRT application notification, that is the toast notification. In this article I will explain how to use these with the NotficationsExtensions that I introduced in my last post.
Unlike tile notifications and badges, toast notifications show up in the application UI instead of on the start screen tile, and will even show up if they user is in a different app. The notification tile appears on the upper right corner of the screen and will stay visible for a short period of time or until the user closes it.
Before we can show toast notifications there are  a couple things we need to do. First, open the Package.appmanifest in your application and be sure Toast capable is set to Yes.
image
Next, on the start screen select Settings from the Charm menu, click Change PC Setting, then select Notifications and be sure Show app notification is turned on
image
Now we can look at the code. First be sure you have the NotificationsExtensions library included in your application as I described in my last post. You will also want to add these two namespaces:

using NotificationsExtensions.ToastContent;
using Windows.UI.Notifications;

Here is the code to display a simple notification.

var toast = ToastContentFactory.CreateToastText01();
toast.TextBodyWrap.Text = "You have a new message";
var notify = toast.CreateNotification();
ToastNotificationManager.CreateToastNotifier().Show(notify);

The first line uses the NotificationsExtensions library to create an object for the notification template we want to use. Just like notification tiles on the Start menu there are a number of different notification styles, some with text and some with text and an image. Once we have the template object we can set the text we want to display, this is done in the second line. Finally the third and fourth lines display the notification which will stay on the screen for about seven seconds then fade out.

image

If you want it to stay on the screen longer you can do this to have it displayed for 25 seconds:

toast.Duration = ToastDuration.Long;

This is a simple example of a notification, but there are other things we can do with it. When the notification popped up you will notice that there was a sound along with it. You can change this sound to one of a couple different built in sounds like this:

toast.Audio.Content = ToastAudioContent.Reminder;

or you can turn it off completely like this:

toast.Audio.Content = ToastAudioContent.Silent;

Instead of a single short sound, you can also specify one of a series of looping sounds that will play until the toast disappears or is dismissed.

toast.Duration = ToastDuration.Long;
toast.Audio.Loop = true;
toast.Audio.Content = ToastAudioContent.LoopingCall;

For the looping sounds to work you also have to have the Duration set to Long and the Loop property set to true.

Saturday, September 1, 2012

Notifications Extensions

When I wrote my first article on tile notifications in WinRT apps back when the developer preview was released I commented that the method for setting up the content for the tiles was a little cumbersome and I hoped that a better way would come along in the release version. There was no changes to the actual framework, but the WinRT samples do come with  a helper library called NotificationsExtensions that does make things easier.
You can get the source code for the library from the App tile and badge sample. You can find the source there in both C# and VB.NET. In this article I will be showing how to use it in C#. Once you have downloaded the sample you will want to pull out the NotificationsExtensions project folder and add it to your own project. If you want, once you have compiled the project, you can just add the NotficationsExtensions.winmd file found in the bin directory into other projects and included it as a reference instead of using the source project.
To use the library the first thing you will want to do is include a couple namespaces:

using NotificationsExtensions.TileContent;
using Windows.UI.Notifications;

The first is the namespace for the tile notification helper classes and the second is the WinRT namespace for notifications. Also remember that if you want to see the wide tile on the start screen you will need to create a 150x310 pixel jpg or png and point the Wide Logo property in the application manifest to it.

Now we are ready to setup the tile content.

ITileWideText03 tileContent = TileContentFactory.CreateTileWideText03();
tileContent.TextHeadingWrap.Text = "Wide tile notification";

ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();
squareContent.TextBodyWrap.Text = "Square tile notification";
tileContent.SquareContent = squareContent;

The first line uses the TileContentFactory class from the NotificationsExtensions library to create a helper class to build the wide tile content template. In TileContentFactory there is a function to create a class for each tile template. You can see all the available templates on the Tile Template Catalog page on MSDN. Once the template class is created you can use its properties to set the content of the template instead of having to deal directly with the XML template.  The second line sets the text to appear on this tile.

The next three lines use a similar process to setup a square tile template. If your application supports both tile sizes then you should always create a notification template for each size so it will display no matter which size the user has set the tile to. The third line of that section attaches the square content to the content we created for the wide tile.

Once we have the templates setup it’s a simple matter to display them using the notification functions:

TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());

If you compare this to how the notification was done in my original post, you can see that this does make thing a little easier.

Badge Notifications

Besides tile notifications the library also has helpers for doing badge notifications. As described in my earlier post, badges are either small numbers or symbols that can be shown in the lower right corner of a tile. To do badges you will want to include one more namespace:

using NotificationsExtensions.BadgeContent;

The code to show a numeric badge looks like this:

BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent(10);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification());

The first line creates the content for the numeric badge using the new library. You can see that the number to be displayed is passed to the constructor. The second line uses the framework functions to display the badge.

The code to display glyph badges is similar:

BadgeGlyphNotificationContent badgeContent = new BadgeGlyphNotificationContent(GlyphValue.Busy);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification());

In this case we pass one of the GlyphValue enumerations to the constructor to specify which shape we want to display.

Saturday, August 25, 2012

MSDN Magazine

One of my favorite magazine for .NET programmers is Microsoft’s MSDN Magazine, and over the years I have accumulated quite a library of them. What some people might not know is that the magazine is available online at http://msdn.microsoft.com/en-us/magazine/default.aspx. The most recent three issues are available in HTML format. Issues older then three months are available in HTML and most are also available for download in PDF or CHM format. Note that if you want to view the CHM files in Windows 8 you will need to right click on the file, select properties, the click the Unblock button otherwise you will not see the content when you open the file.

The magazine archive on the MSDN site actually goes all the way back to January of 2001. A lot of the information in these older issues is obsolete, but they are still worth taking a look at. While going through  the older issues I have found some very in depth articles on programming and .NET specific topics that are still relevant today. Here are a few you might want to take a look at:

Tame Your Software Dependencies for More Flexible Apps by James Kovacs

Digging into IDisposable by Shawn Farkas

An Introduction to Delegates by Jeffrey Richter

Thursday, August 23, 2012

WinRT App Tile Notification Update

Back when the developer preview of Windows  8 came out I did some blog posts on how to use the tile notification capability in new style WinRT apps. I have been going back over these posts to see what, if anything, has changed between then and the RTM release of Windows 8.
Metro App Tile Notification
The code in the original post works pretty much the same in the RTM version but I did run into one odd problem. In my original post I used the following line of code to get the XML node from the tile template:

 var textNode = xmlTemplate.SelectSingleNode("/title/visual/binding/text[@id='1']");

In the RTM this doesn’t work, the node is not be found. It turns out that this is the expected behavior since the SelectSingleNode method required the XML to have a namespace, otherwise it won’t find the node. I am not sure why this worked in the developer preview. There are ways to get around the missing namespace, but there is an easier solution:
 var textNode = xmlTemplate.GetElementsByTagName("text")[0];

This line achieves the same thing and doesn’t have the namespace issue. Other then this change everything in the original post works fine.

Sunday, August 19, 2012

Windows 8 “Metro” Apps Update

When the Windows 8 developer preview came out I wrote some articles talking about how to develop the new “Metro” style apps. Now that Windows 8 has gone RTM (if you have an MSDN subscription you can download Windows 8 and Visual Studio 2012 right now) I thought I would update the information in those articles.

The first article was called Windows 8 Metro Apps.

The first big change between then and now actually came fairly recently. Due to a legal dispute Microsoft will no longer use the term “Metro” for apps developed for the new user interface in Windows 8. As to what they will now be called, there still seems to be some confusion over this. I have seen the terms “Windows 8 style” and “Modern UI” apps used but they don’t seem to have settled on a final name. To make things more confusing Visual Studio uses the term “Windows Store app”, and as of this writing you will still see the term Metro used in some of the documentation. This naming confusion should eventually settle out. Personally I am going to use the term WinRT app for now since these new style apps run in the new Windows Runtime environment.

Starting a New App

When you create a new project in Visual Studio 2012 the WinRT app templates can be found under each language in the Windows Store group. Also in the new project windows be sure to check out the item called Online. This will give you access to a large number of template and sample applications in various languages.

Developer License

When you try to create your first WinRT app you will be asked to apply for a Developer License. This is a free license and you will need it whether you plan to publish you app to the app store or not.  This license will be tied to your Microsoft account, so you will need one of those if you don’t already have one.

Other then this only other difference you will see when you run the app is the default icon has changed since the developer preview. It now looks like this:

image

Saturday, June 30, 2012

Salesforce REST API Read File

In my last post I showed how to upload a file to Salesforce, now lets look at how to read it back. This requires two steps, one to read the document object and a second step to read the actual file data.
Reading the document object is just like reading any other type of object in Salesforce. First we need a class to hold the document object.

public class sfdcDocument
{
    public string Description { get; set; }
    public string Keywords { get; set; }
    public string FolderId { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Body { get; set; }
}

Here is the code to retrieve the document object and de-serialize it.

var uri = instanceURL + "/services/data/v24.0/sobjects/Document/015E0000000qhId";

var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "application/json";
req.Method = "GET";
  
var resp = req.GetResponse();
var sr = new System.IO.StreamReader(resp.GetResponseStream());
var result = sr.ReadToEnd();

// Convert the JSON response into a token object
JavaScriptSerializer ser = new JavaScriptSerializer();
sfdcDocument doc;
 
doc = ser.Deserialize<sfdcDocument>(result);


First we create the REST URI needed to retrieve the document. We are using the simplest method of reading the document here, by just specifying the id of the document we want to read. There are ways to query by filename but I will cover that at another time. Now we make an HTTP get request, setting the accesstoken to the value we got during the authentication process, then read the response and finally de-serialize it.

The document object contains a field called Body which contains the URI used to retrieve the actual binary file data. Here is the piece of code needed to do that.

System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("Authorization: OAuth " + accessToken);
client.DownloadFile(instanceURL + doc.Body, @"c:\temp2\" + doc.Name );


Here we use a WebClient to simplify reading the file. As always we add the access token, then execute DownloadFile using the instanceURL you got along with the access token, and the Body property of the document to specify the whole URI. We can also use the Name property of the document to get the original filename for the document and save it using the same document name.

Sunday, June 3, 2012

Salesforce REST API File Upload

The next part of the Salesforce.com REST API I want to talk about is how to work with documents. In this article I will explain how to upload documents to a folder in Salesforce. Creating a document is similar to creating any other type of Salesforce object so you may want to refer back to my original article on this topic, although I will cover all the code in detail here.
To create a document in Salesforce we will need to post a JSON or XML representation of the document meta-data just like we would with any other Salesforce object, but for a document we will also need to send the binary data from the file. To do this we will send a multi-part MIME document in the body of the HTTP post. The first thing we are going to need is a class to hold the document meta data.

public class sfdcDocument
{
    public string Description { get; set; }
    public string Keywords { get; set; }
    public string FolderId { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }

}

Most of these are self explanatory, but we do need to talk I little about FolderId. When you upload a document to Salesforce you must provide the ID of the folder you want to upload it to. There are ways of querying for folder names, but for the purposes of this demo we will hard code the Id. To get a FolderID log into Salesforce and select the Documents tab. If the tab is not show, click on the + at the end of the tabs and pick Documents from the next screen. From the Folders drop down select the folder you want to upload to and click Go. The next screen will show the contents of you folder and you will be able to get the ID from the URL. For example in “na9.salesforce.com/015?fcf=005E0000000V7Ep” the folder ID is 005E0000000V7Ep.

Now lets look at the code to upload a document.

var doc = new sfdcDocument();
doc.Name = "TestDocument";
doc.FolderId = "005E0000000V7Ep";

First we create a new sfdcDocument object and populate the required fields. You will need to replace the FolderID with the one for the folder you will use.
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
This line is used to create a boundary string to separate the parts of the multi-part MIME message we are going to build. This can be any value that we are sure will not appear somewhere else in the message.
var uri = instanceURL + "/services/data/v24.0/sobjects/Document/";
var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Method = "POST";
var os = req.GetRequestStream();

Now we can build the HttpWebRequest object. In the first line we create the URI for the document resource. The instanceURL variable is the url of your specific Salesforce instance. You will get this when you request an access token during the authentication process. Next we create the request object and set the Authorization header. The variable accessToken in the token you received during the authentication process.  The next line sets the content type for the message. For normal Salesforce object this would be json or xml, but in this case we specify a multpart type and pass the boundary string we created earlier. Finally we set the http method to POST and create a variable for the request stream.

// Add header for JSON part
string body = "";
body += "\r\n--" + boundary + "\r\n"; ;
body += "Content-Disposition: form-data; name='entity_document'\r\n";
body += "Content-Type: application/json\r\n\r\n";

// Add document object data in JSON
var ser = new JavaScriptSerializer();
body += ser.Serialize(doc);

The next step is to add the JSON encoded meta data for the document. We start building the message body by included in the boundary string to mark the start of the first message part. The next two lines are the header for this part of the request. Since we are sending the meta data in JSON format we set the content type to “application/json”. Finally we serialize our document object and added it to the request body.

// Add header for binary part 

body += "\r\n--" + boundary + "\r\n"; ; body += "Content-Disposition: form-data; name='Body'; filename='test.pdf'\r\n"; body += "Content-Type: binary/octet-stream\r\n\r\n";
Now we are ready to setup the binary part of the message. It starts with a header that is similar to the one on the JSON part. In the second line we specify the filename of the document. This filename doesn’t appear to be used anywhere since the actual document in Salesforce uses the Document Name for it’s filename, but the filename attribute must be present and it must contain a value. The third line specifies the content (MIME) type of the file. It is important that this is set correctly so that the file will open in the right program when you open it from Salesforce. An easy way to determine the correct content type is to manually load a file into Salesforce and check the MIME type that it assigns.


// Add header data to request
byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
os.Write(data, 0, data.Length);

// Add file to reqeust
FileStream fileStream = new FileStream(@"c:\temp\test.pdf", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
    os.Write(buffer, 0, bytesRead);
}
fileStream.Close();

Now we need to add everything to the request stream. The first part of this code writes all the header information to the request stream, and the second part writes the actual binary contents of the file to the stream.

// Add trailer
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
os.Write(trailer, 0, trailer.Length);
os.Close();

To complete the request we add a trailer string to it, and then close the stream.

// Do the post and get the response.
WebResponse resp;

try
{
    resp = req.GetResponse();
}
catch (WebException ex)
{
    resp = ex.Response;
}

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

Finally we send the request and get the response. If an error occurs with the request an exception will be thrown. Here we catch that exception and get the actual response from the Exception.Response property. This will normally contain some useful error messages generated by Salesforce. If we have done everything right we should get a response like this:

{
    "id":"015E0000000qhJeIAI",
    "errors":[],
    "success":true
}

The success property will tell you if the insert succeeded and the id property will contain the a unique id for the document that was created.

One important thing to note about doing a document insert is that it will always create a new document even if you insert a document with the same name as one already in the folder. Salesforce will create a unique name for each document you insert.

Saturday, May 12, 2012

Salesforce Password Login

I recently got an e-mail with a question on the Salesforce REST API that I thought I had covered, but it looks like I didn’t. The question is, is there a way to use the REST API with a username and password instead of OAuth? The answer is yes, and this article will explain how to do it.

You will want to refer to my original article on the Salesforce.com REST API since there are a number of concepts that are the same which I will not cover in detail here.

The first thing you will need to do is setup Remote Access in Salesforce.com just like you do when you access the REST interface using OAuth. Refer to my original article for instructions on how to do this. Once setup you will get a Consumer Key and Consumer Secret which you will need for the password login process.

You will also need, of course, a Salesforce username and password you want to login in with. Finally you will need the Security Token for that account. To get this, login to Salesforce with that account, click the down arrow next to your name in the top right and click Setup, click the down arrow next to My Personal Information on the left, click Reset My Security Token, then click the Reset Security Token button. Once you do this a new security token will be sent to the e-mail address you have configured for this account. 

You can get around using the security token by registering an IP address or range of IP addresses as trusted. To do this, in the Salesforce setup, select Network Access from the Security Controls section. On that screen you can enter one or more ranges of IP addresses of computers you trust. You would have to register the IP address of any computer that is going to make calls to the REST API.

Now that we have this information we can make a call to Salesforce to get the access token that will be needed to make all the other REST calls. Here is the code to do this.

private void GetToken(string consumerKey, string consumerSecret,string username, string password, string securityToken) { 
            string URI = "https://login.salesforce.com/services/oauth2/token"; 
            StringBuilder body = new StringBuilder(); 
            body.Append("grant_type=password&"); 
            body.Append("client_id=" + consumerKey + "&"); 
            body.Append("client_secret=" + consumerSecret + "&"); 
            body.Append("username=" + username + "&"); 
            body.Append("password=" + password + securityToken); 
            string result = HttpPost(URI, body.ToString()); 
        }


This is similar to the code we used get the access token using OAuth but instead of passing in the authentication code we use the username password and security token instead. You will notice that the security token is simply appended to the end of the password. If you have registered your computer as trusted you will just be sending the password without the security token.

This function will return a string containing the access token structure encoded in JSON. Refer to the original article for details on how to extract the access token. Once you have the access token the REST API can be used just like you do when logging in with OAuth.

I have attached a new demo application that shows how to access the REST API using both OAuth and username/password authentication. Be sure to fill out the variables at the top of MainForm.cs with your consumer Key, consumer Secret, etc.
Visual Studio 2010 Salesforce REST API Demo

Sunday, March 4, 2012

Visual Studio 2011 Beta Search

I have been looking at the new features in Visual Studio 2011 and one area they have made a lot of improvements in is search. As I showed in my post on the Solution Explorer  there is now a search box that allows you to quickly find files in the solution explorer, but there are also other areas where search has been improved.

One of these is the quick launch box which you will find at the right end of the menu bar.

image

If you type a word in the box and hit enter you will get a list of all the menus and options that contain that keyword. Clicking on one of the menu items will directly execute that command, and click on a Options item will take you to that section of the options dialog.

image

With the large number of menu and settings options in Visual Studio the quick launch can make it much easier to find commands and options, especially ones you don’t use often.

Another area where some small improvements have been made is in the quick find function. The quick find box is a little cleaner and works a bit differently then it did in VS 2010.

image

The search direction options are now on a drop down menu next to the search box which defaults to Find Next. This makes it fairly intuitive to they way we normally search.

image

The scope selection icon has also been removed from the search box. You can access the scope selection by clicking the arrow in the upper left corner of the search box to expand it  into a search/replace box. You will now see the scope select option. You will also notice that the replace option is shown below the find option unlike in 2010 where they were side by side. I feel this is a more logical layout and should also reduce the change of the search box hiding a piece of code.

image

Friday, March 2, 2012

Visual Studio 2011 IDE Improvements


Yesterday I talked about some of the enhancements to the Solution Explorer in the Visual Studio 2011 beta. The one thing I didn’t show was the new file preview function. On the Solution Explorer icon bar there is a new toggle button called Preview Selected Item.

IconBar

When this button is toggled on and you click on any of the files in Solution Explorer a preview of the file will be displayed in a tab anchored to the right side of the tab bar. If you click another file this tab will be replaced with the preview of that file. This makes it really easy to browse through files.

PreviewTab

At this point the file is in preview mode. You can click on the icon next to the file name in the tab to make the file editable or just starting editing the file. Once it’s out of preview mode the file joins the tabs to the left and works like any other file.

Another new feature is the ability to pin files to the left side of the tab bar.

Pin

When you click the pin icon on a tab it will always stay on the left side no matter how many more files you open.

Thursday, March 1, 2012

Visual Studio 2011 Solution Explorer

 

Yesterday Microsoft released a new beta of Visual Studio 2011. I’ve been playing around with it a bit to check out some of the new features.

The first and most noticeable change is the new appears of the UI. Microsoft has gone with a simpler “Metro-style” look for the interface.  Here you can see a comparison of part of the UI from Visual Studio 2011 on the left and Visual Studio 2010 on the right.

SolExplorer1         image

The new look doesn’t bother me, but I don’t think it really adds anything.

Since we are looking at the solution explorer let’s talk about one of the nice new features that has been added to VS 2011. In Visual Studio 2010 Productivity Power Tools add-on there was a feature call the Solution Navigator that combined functionality from the Solution Explorer, Class view, Object Browser and other components into a single tool. In VS 2011 this functionality has been added to the Solution Explorer right out of the box, no need for an add-on. Let’s look at some of the features this brought to the Solution Explorer.

The first new feature is the search box directly below the icon bar. Start typing into this box and the list of files will be filtered to only show file names with that word in it. Here you can see where I typed “Logo” in to the search box and the resulting file list:

SolExplorerSearch

The new Solution Explorer also merges in the capabilities of the Class Explorer so you can continue drilling down from the file level to see the Classes that are in the file, then the properties and methods that are in that class.

SolExplorerClassExp

Finally you can right click on a property or method to see what code is calling the method, what code the methods calls, etc.

SolExplorerClassExp2

The Solution Navigator is a great tool so it was nice to see it made a first class part of Visual Studio.

Wednesday, February 29, 2012

Windows 8 and VS 2011 Beta

Microsoft did two exciting Beta releases today, Windows 8 (being called a “Consumer Preview” instead of  a Beta despite the fact that the default desktop background is a Betta fish), and Visual Studio 2011 Beta.

Windows 8 Consumer Preview

To download the new version you can get the web installer here or download the ISOs from here. I first tried running the web installer from an instance of the Windows 8 Developer Preview running in a VM but couldn’t do the install because I did not have enough space on the virtual C: drive. I decided to just create a new VM using VirtualBox 4.1.8, which now has a profile specifically for installing Windows 8, and install the Windows 8 CP from scratch. The install went very quickly and smoothly and installed without any problems on my first try.

My first impressions are that it seems faster then the previous version and the new tile based start menu works a little more smoothly. There is also a new task switcher that pops up along the left side of the screen when you press the Windows Key + Tab which is a nice feature. The classic desktop is still there, but the start menu button is now completely gone. You can still use the Windows key to switch back and forth between the desktop and the new start screen. I still don’t see how this new start screen is going to work out for desktop users, especially for power users.

Visual Studio 2011 Beta

You can download the Visual Studio 2011 Beta from here, and you can also get it from the MSDN Subscription downloads. I first tried installing the Ultimate version of the beta on my Windows Vista machine but it only supports Windows 7, 8 CP, Server 2008 R2 and Server 8 Beta. I am hoping this changes before the final release. I ended up installing the Beta on a Windows 7 virtual machine, and although the install took quite a while it went pretty smoothly. I also tried the install on a Windows 8 CP VM which, despite some information I saw to the contrary, is support.

I haven’t had to much time to play with the VS 11 Beta yet, but the one thing that is very noticeable when you start it up is the new, very Metro-like  interface. It seems like a cleaner interface then the previous version, but I will need to work with it for a while to see if it’s really any better.