Apr
6
Written by:
Michael Washington
4/6/2012 8:26 AM
Visual Studio LightSwitch Beta in Visual Studio 2011, allows you to create applications that can communicate with LightSwitch using OData. This allows you to create applications, such an Android mobile application, that communicate with the LightSwitch business layer. This provides access to the LightSwitch security and business rules.
In this example, when a user uses the application and calls LightSwitch, they will only see their own Orders (unless they are in the administrator role, then they will be able to see all Orders).
For this example we will start with the LightSwitch application in the article Calling LightSwitch 2011 OData Using Server Side Code. We will build an Android application using App Inventor that will communicate with the LightSwitch application.
We will use App Inventor because it creates applications that run on most Android devices, and is easy to learn, and fun to use.
While it is possible to create mobile applications using the method described in Calling LightSwitch 2011 OData Using Server Side Code, the performance of applications for the end user will not be as fast and as smooth as the performance of a ‘native’ application such as the one described here.
Walk Thru Of The Application
| |
(1) The application allows you to specify the connection settings. These are then stored in the device’s local database. We log in using the normal LightSwitch username and password for each user account.
| (2) If the application detects that the settings are set, it queries the LightSwitch OData feed for all the Orders that the user has access to. |
| |
(3) When the orders have been retrieved, the button will change from Loading… to Choose Order. | (4) Clicking the button will display the orders. |
| |
(5) Clicking on an order will display its details. | |
The LightSwitch Project
We add a page (Android.aspx) to the LightSwitch project using the following code:
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LightSwitchApplication.Mobile
{
public partial class Android : System.Web.UI.Page
{
#region BaseSiteUrl
public static string BaseSiteUrl
{
get
{
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme
+ "://"
+ context.Request.Url.Authority
+ context.Request.ApplicationPath.TrimEnd('/')
+ '/';
return baseUrl;
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
// Get Values
string UserName = Server.UrlDecode(Convert.ToString(this.Request.Form["UserName"]));
string Password = Server.UrlDecode(Convert.ToString(this.Request.Form["Password"]));
string ODataQuery = Server.UrlDecode(Convert.ToString(this.Request.Form["ODataQuery"]));
// Validate
if (Membership.ValidateUser(UserName, Password))
{
// Set the forms authentication cookie that will be used in the OData requests
FormsAuthentication.SetAuthCookie(UserName, false);
// Create DataContext
ODataServiceReference.ApplicationData objApplicationData =
new ODataServiceReference.ApplicationData(new Uri(string.Format(@"{0}applicationdata.svc/", BaseSiteUrl)));
#region if (ODataQuery == "Orders")
if (ODataQuery == "Orders")
{
// Query OData source
var result = from FlowerShopOrders in objApplicationData.FlowerShopOrders
.Expand(x => x.FlowerShopCustomer)
select FlowerShopOrders;
string strResult = "";
foreach (var item in result)
{
strResult = strResult + String.Format("['[{0}] {1}, {2} - {3}",
item.Id,
item.FlowerShopCustomer.LastName,
item.FlowerShopCustomer.FirstName,
item.OrderDate.ToShortDateString());
}
Response.Write(strResult);
Response.End();
}
#endregion
#region if (ODataQuery != "Orders")
if (ODataQuery != "Orders")
{
// Query OData source
var objFlowerShopOrder = (from FlowerShopOrders in objApplicationData.FlowerShopOrders
.Expand(x => x.FlowerShopCustomer)
where FlowerShopOrders.Id == Convert.ToInt32(ODataQuery)
select FlowerShopOrders).FirstOrDefault();
string strResult = "";
strResult = strResult + String.Format("['[{0}] {1}, {2} - {3}",
objFlowerShopOrder.Id,
objFlowerShopOrder.FlowerShopCustomer.LastName,
objFlowerShopOrder.FlowerShopCustomer.FirstName,
objFlowerShopOrder.OrderDate.ToShortDateString());
var colOrderDetails = from OrderDetails in objApplicationData.FlowerShopOrderDetails
.Expand(x => x.FlowerShopOrder)
.Expand(x => x.FlowerShopProduct)
where OrderDetails.FlowerShopOrder.Id == Convert.ToInt32(ODataQuery)
select OrderDetails;
foreach (var OrderDetail in colOrderDetails)
{
strResult = strResult + String.Format("['{0} {1} ${2} ({3})",
"*",
OrderDetail.FlowerShopProduct.ProductName,
OrderDetail.FlowerShopProduct.Price,
OrderDetail.Quantity);
}
Response.Write(strResult);
Response.End();
}
#endregion
}
}
}
}
Note: It is possible to connect to the LightSwitch OData feed directly as demonstrated in: Consuming The Netflix OData Service Using App Inventor. However, when the OData feed requires authentication, you need to call a page in the LightSwitch application and obtain a authorization cookie and pass that in each request. This requires a lot of code in App Inventor so in this example we will use the page above to accept the user name and password and provide the data needed.
However, this page is still calling the LightSwitch Odata feed and the LightSwitch business layer, and all security and business rules.
App Inventor
App inventor is a program that allows you to easily make applications that run on the Android system. This includes the Amazon Kindle Fire. Here are some links to get you started with App Inventor:
Setup
Set up your computer. Run the emulator. Set up your phone. Build your first app.
Tutorials
Learn the basics of App Inventor by working through these tutorials.
Reference Documentation
Look up how specific components and blocks work. Read about concepts in App Inventor, like displaying lists and accessing images and sounds.
You can use the server that is set-up at MIT or download the App Inventor Server source code and run your own server.
You will need to go through the Tutorials to learn how to manipulate the App Inventor Blocks.
The article Consuming The Netflix OData Service Using App Inventor provides an example of creating a App Inventor program.
The Android Program
With App Inventor we create programs using Blocks.
First we create definition Blocks. These Blocks are variables that are used to hold values that will be used in the application. The Text (string) variables have a “text” Block plugged into their right-hand side. The List variables have a “make a list” Block plugged into them.
The first procedure to run is the Screen1.Initialize procedure.
This first checks to see if it has a URL for the LightSwitch application stored in its database. If it does, it hides the Account information screen and calls GetProducts (this calls the LightSwitch application and gets the Orders that the user has access to).
If it does not have a URL for the LightSwitch application stored in its database, it displays the Account information screen.
GetProducts calls the LightSwitch application.
The WebComponentOrders.GotText method receives the response from the LightSwitch application and parses it and creates a List called Orders and sets it as the source of the ListPickerOrders button.
When the user clicks the button they will see a list of the orders.
Another list of just the Order IDs is created (OrderIds). This list will be used to determine what the Order ID is of the Order that is picked with the ListPickerOrders button.
When the user clicks the ListPickerOrders button…
They see a list of the Orders they have access to.
When the user chooses an Order, the ListPickerOrders.AfterPicking method runs and sets the OrderId variable (by selecting the OrderID from the OrderIDs list based on the index of the Order selected in the ListPickerOrders button).
The method then passes the OrderId to the LightSwitch application.
The WebComponentOrder.GotText method runs and parses the result.
The Order details are displayed.
Connecting App Inventor To Your LightSwitch Project
To connect your App Inventor project to your LightSwitch project, you will need to first publish your LightSwitch project.
Next you will need to point the App Inventor Emulator to the location you published your LightSwitch project to. If you published your LightSwitch project to your local computer, ( http://Localhost ), you will find that the App Inventor emulator cannot connect to that address. There will be an address that it can connect to however:
Connect to the internet. This will cause your computer to be assigned an IP address other than localhost.
Start the Android Emulator (if it is not already running).
Open your IIS Manager.
Click on Default Web Site.
Click on Bindings.
Click on the http line and then click Edit.
You will see an IP address that the Android Emulator can connect to.
An Important Note About SSL
All the OData calls contain the username and password sent in clear text.
A production application must run on a webserver that has SSL enabled for all transactions. Otherwise, a hacker with a packet sniffer can easily get the usernames and passwords of your users who are connecting to your site using public Wi-Fi access points or other unsecure networks.
Also See
OData:
Calling LightSwitch 2011 OData Using Server Side Code
Learn How To Make OData Calls In LightSwitch 2011
Accessing Your Visual Studio 2011 LightSwitch Application Using OData
Consume a LightSwitch OData Service from a Windows Phone application
App Invertor:
tAIR - The App Inventor Repository
Download Code
The App Inventor source code (and the LightSwitch project), is available at:
http://lightswitchhelpwebsite.com/Downloads.aspx
5 comment(s) so far...
Michael, This is great, this opens up a whole new line of business apps. I'm going to have to have a look at AppInventor now.
Thank you
Keith
By Keith Craigo on
4/6/2012 9:05 AM
|
@Keith Craigo - Thanks for the feedback. My hope is that you will find App Inventor useful. I do.
By Michael Washington on
4/6/2012 9:05 AM
|
Fantastic, You rock :)
By abuhelweh on
4/8/2012 11:45 PM
|
@abuhelweh - Thank you. I hope it helps.
By Michael Washington on
4/9/2012 4:04 AM
|
Great post! Thanks for sharing.
The codes that you shared is of great help for me especially I will be taking up android subject next semester.
Continue to share your knowledge :)
Developing Android App
By chazy Curtis on
11/8/2012 5:38 AM
|