Using LightSwitch OData Services in a Windows 8 Metro Style Application (Elizabeth Maher)

Using LightSwitch OData Services in a Windows 8 Metro Style Application (Elizabeth Maher)

Rate This
  • Comments 1

One of the exciting new features in Visual Studio 11 Beta is applications you create with LightSwitch will automatically expose Open Data Protocol (OData) services. For a good article covering how OData and LightSwitch work see Enhance Your LightSwitch Applications with OData and Creating and Consuming LightSwitch OData Services by Beth Massi. The ability for LightSwitch application to produce OData service allows other clients to read the data produced by your LightSwitch application. In this walkthrough, we will cover how to read an OData service created by a LightSwitch application in a Windows 8 Metro style application.

For the purposes of this article, the Contoso application will be the LightSwitch application used. Instructions for setting up this sample may be found here: Contoso Construction - LightSwitch Advanced Sample (Visual Studio 11 Beta). We will add a Windows 8 Metro style application to the Contoso solution, change the Metro style application to read the construction project data from the Contoso LightSwitch application, and setup Visual Studio to allow us to debug both the LightSwitch application and Windows 8 Metro style application at the same time. This walkthrough will focus on the development process of creating a LightSwitch application at the same time as creating a Windows 8 Metro style application.  The deployed Windows 8 Metro style application is expected to use the published OData service url.

OData Service from LightSwitch Application

We will be reading the Projects table to get a list of construction projects. To see the data feed from the OData service, you can simply type the service url into Internet Explorer. The url for LightSwitch Applications will be in the form [base url]/[DataSourceName].svc. For a Contoso Construction project that is being debugged, the url will the http://localhost:#####/ApplicationData.svc, where ##### is the current port number being used. To see a list of the projects, add a ‘/Projects’ to the url to make http://localhost:#####/ApplicationData.svc/Projects. Below is a picture of the OData feed in Internet Explorer, when the reading View is turned off.

odataInInternetExplorer

To turn off the reading view in Internet Explorer, choose Tools -> Internet Options. Click the Content tab and click the Settings button under the Feeds and Web Slices section. Uncheck ‘Turn on feed reading view’.

ieReaderOptions

Now that we know the url to get the data information for construction projects, lets create a Windows 8 Metro style application that will list the projects in a touch-friendly user interface.

Creating a Windows 8 Metro Style Application

To complete this walkthrough, you will need a version of Visual Studio 11 Beta that has both the LightSwitch project templates and the Windows 8 Metro project templates. Visual Studio 11 Professional Beta, Visual Studio 11 Premium Beta and Visual Studio 11 Ultimate Beta will all have the necessary features. Download Visual Studio 11 Beta here.

For simplicity, we will be using the Javascript Split Metro Style Application. Click File –> Add New Project. Select the Split Application template found under JavaScript \ Windows Metro style.

addNewProject

Please note, that you need a developer license to create a Metro style application. If creating a Metro style application for the first time, you will be asked to accept the terms of agreement and will be prompted for a Microsoft account information.

Script Libraries

In this walkthrough, we will be using two libraries, JQuery and DataJS. See resource links at the end of this document for more information concerning both libraries. The best way to install these libraries is to use the Package Manager. Open the Package Manager Console by selecting Tools -> Library Package Manager -> Package Manager Console. Type ‘install-package jquery'. Once that command is complete type 'install-package datajs' in the Package Manager Console. The Package Manager Console should look like the following.

packageManager

 

After both packages are successfully installed, the Scripts folder should list all the necessary files.

scriptFolder

Modifying Metro Style Application

Let’s modify the Metro style application project to read the list of construction projects from ContosoConstruction. First thing that must be done is to setup the projects so we can use the DataJS and JQuery library. Open the default.html and add a reference to DataJS and JQuery under the WinJS references by adding the lines

  <!-- jQuery references --> 
  <script src="/Scripts/jquery-1.7.1.js"></script> 
  <!-- datajs references --> 
  <script src="/Scripts/datajs-1.0.2.js"></script> 

Now open js\Default.js to create a variable for OData by adding the line

   var OData = window.OData;

The next thing that must be done is to define the groups that will be displayed on the home page. We will show all projects.

Open the js\data.js file. Replace the sample groups with the following.

    var sampleGroups = [ 
        {
            key: "allProjects", title: "All Projects", subtitle: "All Contoso projects.",
            backgroundImage: darkGray
        },
    ]; 

The next step is to load the actual data. To do this, the code to load the sample data must be replaced. The sample code should look like the following.

// TODO: Replace the data with your real data.
// You can add data from asynchronous sources whenever it becomes available.
sampleItems.forEach(function (item) {
     list.push(item);
});

Replace the sample code with the following code:

    //Generic function for loading data via a odata url
    function loadData(data, odataUrl, dataLoaded) {
        if (data) {
            return WinJS.Promise.as(data);
        }
        else {
            return new WinJS.Promise(function (complete, error, progress) {
                OData.read(odataUrl,
                function (data) {
                    complete(dataLoaded(data.results));
                },
                function (dataerror) {
                    error(dataerror);
                });
            });
        }
    }


    var projectsODataUrl = "http://localhost:#####/ApplicationData.svc/Projects";
    //TODO: Replace projectsODataUrl with url for deployed OData service
    //  before publishing this application.
    var _projects;
    //Loads projects
    function loadProjects() {
        loadData(_projects, projectsODataUrl, function (results) {
            _projects = results;
            return _projects;
        }).then(function (projects) {
            var items = [];
           
            $.each(projects, function (l, e) {
                var notes;
                if (e.Notes === null) {
                    notes = "";
                }
                else {
                    notes = e.Notes;
                }
                items.push({
                    displayName: e.ProjectName, subtitle: "Estimate: $" +
                        e.OriginalEstimate, description: "", content: notes
                });
            });
            showProjects(items.sort(), sampleGroups[0]);
        });
    }

    //Adds projects to binding list.
    function showProjects(items, itemGroup) {
        items.forEach(function (item) {
            list.push(
                {
                    group: itemGroup, title: item.displayName,
                    subtitle: item.subtitle, description: item.description,
                    content: item.content, backgroundImage: lightGray
                }
              )
        });
    }

    loadProjects();

Preparing for Debugging

Launching Projects Simultaneously

To debug the Metro style application that is connected to a non-published LS OData service it is best to configure both projects to launch simultaneously on F5. To do this, open the Solution Property Pages. Select the Common Properties\Startup Project properties page. Select ‘Multiple start projects’. Set ConstosoConstruction and the Windows 8 Metro style application project to have a startup action of ‘Start’. Make sure that ContosoContruction is listed before the Windows 8 Metro style project in the startup order.

solutionProperties

Setting Capabilities for Metro Style Application

It is also necessary to set the capabilities for the Metro style application. Double-click the package.appxmanifest file of the Metro style application project in Solution Explorer. This will show the interface for modifying package properties. Click the Capabilities tab. Check the ‘Private Networks (Client & Server)’ capability to allow your application to connect to intranet resources. Check the ‘Enterprise Authentication’ capability only if your LS OData service uses Windows Authentication. This capability will allow credentials of the current user to be automatically used, rather than having the user prompted for their credentials.  Note – both of these capabilities are designed for enterprise applications and will not be found in typical application from the Window Store.

packageCapabilities

Getting Current Port Number for LightSwitch Project

You are almost ready to debug. It is important to note that an F5’ed LightSwitch application is not guaranteed to have the same port number every time the application is debugged. Put a breakpoint on the line where the LightSwitch OData url is defined and change it when needed. You can get the port number a few ways. If your LightSwitch application type is set to ‘Web’, you can get the port number out of the url in the browser.

gettingPortNumber

You can also use the task manager to get the port number. Open Task Manager and select the Details tab. Show the ‘Command Line’ column for the process. Find the ‘vslshost.exe’ process and look for the ‘/p:’ in the command line arguments. The ‘/p’ stands for port number. For example the command line might be, "C:\Users\CurrentUser\Documents\Visual Studio 11\Projects\Contoso\ContosoConstruction\bin\Debug\VslsHost.exe" /s /SuppressWarmup /AppBridgeInstanceName:2624 /AppBridgeServiceId:1 /p:13743 /UseMEFCache /GrantedPermissionsForDevelopment:"Microsoft.LightSwitch.Security:SecurityAdministration" /n:"ContosoConstruction" /MainThreadCulture:en-US

The number 13743 would be the port number.

Start Application

You are ready to hit F5! Modify the port number for ContosoContruction OData service, if needed. You should see a single button with the title ‘All Projects’.

title

After clicking the button, all the construction projects for ContosoContruction will be shown. See below for example.

items

Publishing

Each project must be published independently. First publish the LightSwitch application to your production server.  Documentation, including some walkthroughs, explaining publishing a LightSwitch application can be found at http://msdn.microsoft.com/en-us/library/ff852001.aspx.  Once the LightSwitch application is deployed and the production OData service url is known, the url used in the Metro style application must be updated before it is deployed.  See http://msdn.microsoft.com/en-us/library/windows/apps/hh454036(v=vs.110).aspx for documentation regarding packaging your Windows 8 Metro style application using Visual Studio.

Wrap Up

I hope this post has helped you understand how to call LightSwitch OData services from a Windows Metro Style application. For more information, see the links below.

Links

Topic

URL

OData

http://www.odata.org/

JQuery

http://jquery.com/

DataJS

http://datajs.codeplex.com/

Windows 8 Metro Style Application Documentation

http://msdn.microsoft.com/library/windows/apps/

Getting developer license for Windows 8 Consumer Preview

http://msdn.microsoft.com/en-us/library/windows/apps/hh696646(v=vs.110).aspx

Windows 8 Metro Style Application Packages and Deployment http://msdn.microsoft.com/en-us/library/windows/apps/hh464929.aspx

LightSwitch in Visual Studio 11 Beta Resources

http://msdn.microsoft.com/en-us/lightswitch/hh852657

Deployment of LightSwitch Application http://msdn.microsoft.com/en-us/library/ff852001.aspx
Leave a Comment
  • Please add 2 and 3 and type the answer here:
  • Post
  • Hi,

    Can we have a VB/C# example for those who don't know Javascript? :-)

    Thanks!

Page 1 of 1 (1 items)