Accessing Salesforce Data from a Windows Phone App

This guest article by salesforce.com is a sponsored post. Sample code for this article is available for download.

Salesforce.com recently launched their toolkit for .Net which makes developing a Salesforce app from .Net a breeze. I’ll show you how to set up your Force.com Developer Edition (DE) environment to allow making API calls. Once set up, you will be able to read and update data from within your app. For the purpose of this tutorial I will build a Windows Phone app that talks to the Salesforce1 Platform – this way you’ll gain 2 new skills: developing for the Salesforce1 Platform and developing for Windows Phone, which will make you a mobile developer as well! The Salesforce1 Platform also allows you to build mobile apps for other platforms in a similar way. Let’s get started.

First, go to https://developer.salesforce.com/signup and register for your Free DE account. For the purposes of this example, I recommend signing up for a Developer Edition even if you already have an account. This ensures you get a clean environment with the latest features enabled. Once your account is set up and you are logged in, you will see your home page as shown in Image 1 below.

Image 1

Image 1

Once signed in to the salesforce.com portal, click My Developer Account under your name on the top right. This will take you to the Force.com developer homepage. Now click Setup next to your name on the top and then select the Apps menu item under Build -> Create on the left hand side to see a screen similar to the one shown in Image 2.

Image 2

Image 2

Once you are at the screen above, make sure to click New in the Connected Apps section of the page as we want to be able to connect to this application we create via the API.

Fill out the form you see on the screen (shown in Image 3). You must fill out Connected App Name, API Name and Contact Email. Then check Enable OAuth Settings checkbox and fill out a Callback URL as well for your app. One last item you need to change in this step is Selected OAuth Scopes. For the purpose of this tutorial, you can select Full Access (full), but never do this in a production application without good reason. Press Save.

Image 3

Image 3

Assuming everything was set up properly up until this point, you will see the screen seen in Image 4. The two values you need from this screen are the Consumer Key assigned to your app and the Callback URL you’ve entered.

Image 4

Image 4

Now that your Force.com app setup is complete, you can move on to creating the Windows Phone app that will connect to this Force.com app and read data from your salesforce.com account.

Let’s assume one of your clients is James Bond and you want to manage your relationship with his firm, Bond Enterprises. I’ll show you how to first add Bond Enterprises to your Salesforce Accounts list, then add James Bond as a contact for the firm, and then add more details to the account as well.

We start by creating a new Windows Phone project in Visual Studio. In order to do this, you need the Windows Phone SDK installed, which comes with the Express (free) version of Visual Studio. You will also need the Force.com Toolkit for .Net files downloaded and installed from the GitHub link referenced at the beginning of this tutorial. Once the Windows Phone SDK and Visual Studio are installed, open Visual Studio and create a new Windows Phone project, as seen in Image 5.

Image 5

Image 5

By default, a Windows Phone project comes with a page called MainPage.xaml, which is automatically set as the start page for your application. Double click MainPage.xaml in the Solution Explorer window (press Ctrl+W, S if you do not see the Solution Explorer Window) to open the page in the editor part of the Visual Studio IDE. Once open, replace the code you see on the screen with the following:

<phone:PhoneApplicationPage
x:Class="SalesHelper.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser x:Name="AuthBrowser" IsScriptEnabled="True" Navigating="AuthBrowser_Navigating" Visibility="Collapsed" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>

Doing this sets up the PhoneApplicationPage_Loaded event handler for when the page has finished loading so you can continue your processing further. It also adds a WebBrowser control to the screen so that we can use it for the OAuth authentication.

Note: Before you proceed any further, you’ll need to add a reference to the Force.com Toolkit for .Net to your project. You can accomplish this by downloading the toolkit from https://github.com/developerforce/Force.com-Toolkit-for-NET

Now that the code for the design of the MainPage is complete, open the code-file for this page, called MainPage.xaml.cs. In case you do not see this file in the Solution Explorer window, click the arrow next to MainPage.xaml to expand it and you will see the code file (.cs) underneath it. Since this is the page where we do the OAuth authentication, we will set up some variables that help with that. Towards the top of the MainPage class (just after the opening parenthesis), add the following:

private const string AuthorizationEndpointUrl = "https://login.salesforce.com/services/oauth2/authorize";
private const string CallbackUrl = "http://localhost:5000/auth/salesforce/callback";
private const string ConsumerKey = "<Add your Consumer Key here>";

As you can tell, you will need to replace <Add your Consumer Key here> you find in your Force.com dashboard, as seen in Image 4. The above code also sets the URL we need to hit for authorization and also the call back URL, which in the case of a mobile app can just point to localhost. Now, add the PhoneApplicationPage_Loaded method which will navigate the WebBrowser control to the authentication URL.

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(App._accessToken))
{
AuthBrowser.Visibility = Visibility.Visible;

var url =
Common.FormatAuthUrl(
AuthorizationEndpointUrl,
ResponseTypes.Token,
ConsumerKey,
CallbackUrl,
DisplayTypes.Touch);

AuthBrowser.Navigate(new Uri(url));

return;
}

LoadAccounts();
}

The call to the LoadAccounts() method will navigate the user to the Accounts List page.
At this point, we have our OAuth implementation complete (there is a part which captures the return token from the OAuth server and stores it for future use). You can see all this in play in the sample code provided with this tutorial. If you run the code at this time, you should see Screen 1 in your Windows Phone app. Once you log in, you should see the Authorization Screen 2. Please note that since we have not yet implemented the Accounts List page, at this point you will receive an error when the app tries to navigate to it.

Screen 1

Screen 1

Screen 2

Screen 2

Now we will add a new page to our app which will show the Accounts List. Add a new Windows Phone Portrait Page to your project, as seen in Image 6, and name it ListAccounts.xaml

Image 6

Image 6

In ListAccounts.xaml page, replace the ContentPanel grid control with the following piece of code, which adds a ListBox to the page which will contain a list of all Accounts associated with your salesforce.com account.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="OrganizationsList" ItemsSource="{Binding}" SelectionChanged="OrganizationsList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal" Margin="2"  >
<TextBlock Name="nme"  Text="{Binding Name}" Margin="2" />
<TextBlock Text =" - " Margin="2" />
<TextBlock Name="desc"  Text="{Binding Description}" Margin="2" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>

In the OnNavigatedTo event handler for the page, which is called after the page navigation has completed, we will fetch the list of accounts and bind the dataset we receive back to the ListBox named OrganizationsList in the code above.

async protected override void OnNavigatedTo(NavigationEventArgs e)
{
var client = new ForceClient(App._instanceUrl, App._accessToken, App.ApiVersion);
var accounts = await client.QueryAsync<Account>("SELECT id, name, description FROM Account");

OrganizationsList.ItemsSource = accounts;
}

You will notice that this method is set to be an async method, which allows us to make an asynchronous call and await the completion of its execution before moving forward with the rest of the code in this method. The first line inside the method creates a new Force.com client object which will be used to interact with your salesforce.com account and passes the Instance URL and the Access Token returned by the OAuth call to it along with the ApiVersion. The second line contains the actual query that is run against your Force.com data to fetch a list of Accounts. This is a standard SQL query that can be customized with a where clause to filter the resultset. The third line,

	OrganizationsList.ItemsSource = accounts;

binds the list of accounts returned by the Force.com Toolkit for .Net to the ListBox we added to the page earlier. The result of doing this and running the app again is shown in Screen 3.

Screen 3

Screen 3

We similarly add another page called AddAccount.xaml, which allows us to add and edit an Account. Replace the ContentPanel grid inside this page to the following:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBlock Text="Account Name:" />
<TextBox Name="AccountName" />
<TextBlock Text="Account Description:" />
<TextBox Name="AccountDescription" />
<TextBlock Text="Phone:" />
<TextBox Name="AccountPhone" />
<TextBlock Text="Website:" />
<TextBox Name="AccountWebsite" />
</StackPanel>
</Grid>

This just adds some controls to the screen which will allow us to enter the information regarding an account.

In AddAccount.xaml.cs, you will need to add an event handler for the save button and add the following code to it to save the information entered:

async void abibSave_Click(object sender, EventArgs e)
{
var account = new {Name = AccountName.Text, Description = AccountDescription.Text, Phone = AccountPhone.Text, Website = AccountWebsite.Text};
var id1 = await client.CreateAsync("Account", account);
}

As you can tell, the call to CreateAsync returns us an ID for the record created. We can use this ID later on to edit this record using the code below. Remember that we do not need to store IDs for each record created, we can easily perform a search and fetch the IDs for any record(s) as shown previously when fetching a list of accounts.

var account = new { Name = AccountName.Text, Description = AccountDescription.Text, Phone = AccountPhone.Text, Website = AccountWebsite.Text };
var success = await client.UpdateAsync("Account", editID, account);

These two lines create a new Account object and then call the UpdateAsync method available in the Force.com Toolkit to update the record with a given ID.

Using the code so far, we can create a new account for Bond Enterprises, as seen in Screen 4 and then also edit it to include more details or change data, as seen in Screen 5.

Screen 4

Screen 4

Screen 5

Screen 5

At this point you will also notice that the new account for Bond Enterprises has been added to our Accounts List, as seen in Screen 6.

Screen 6

Screen 6

From the edit account screen (Screen 5) we can also add a contact associated with that particular account. For this, we will need to add a new page called AddContact.xaml, add some controls to allow the user to enter Contact data on the screen, and save the information in your salesforce.com account.

The event handler for the Save button will be as follows:

async void abibSave_Click(object sender, EventArgs e)
{
ForceClient client = new ForceClient(App._instanceUrl, App._accessToken, App.ApiVersion);

// Create an object
dynamic d = new ExpandoObject();
d.FirstName = FirstName.Text;
d.LastName = LastName.Text;
d.Title = Title.Text;
d.Phone = Phone.Text;
d.AccountID = NavigationContext.QueryString["acID"].ToString(); //The Account ID for the account this contact needs to be associated with.
d.Email = Email.Text;
string recordId2 = await client.CreateAsync("Contact", d);

}

The code snippet above shows you another way to add dynamic objects, using the ExpandoObject available in .Net. We are passing the Account ID for the account this contact will be associated with using query parameters; hence, we fetch it using the QueryString object of the NavigationContext. The last line is actually the one that creates a new Contact in salesforce.com using the CreateAsync method and returns the ID of the newly created contact.

Hope you have earned a good sense of how easy the Force.com Toolkit for .Net is to implement. It provides us with some powerful, yet simple, functionality to create, fetch, edit and delete objects in salesforce.com.

Note that you can download the attached sample project and run it by simply replacing the Consumer Key value in MainPage.xaml.cs with your own Consumer Key from Force.com dashboard. In this tutorial, I have omitted talking about some non-essential code, which does not provide value on working with the Force.com Toolkit. However, this code is an essential part of getting the app to work properly and is included in the attached sample.

You can even pin your app to the Start screen and see the beautiful Sales Helper icon that comes with it, as seen in the bottom left corner of Screen 7.

Screen 7

Screen 7

Resources

For a comprehensive set of resources, check out: https://developer.salesforce.com/en/mobile/resources

About The Author

Paras Wadehra is a Software Architect and Microsoft MVP. He is a vocal dev advocate and helps other developers get started developing mobile apps. He also speaks at various industry events and conferences. He can be reached on Twitter at @ParasWadehra and his blog can be found at http://paraswadehra.blogspot.com/ You can also see his apps in the Windows Phone Store

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *