You are here:   Blog
Register   |  Login

Oct 5

Written by: Michael Washington
10/5/2013 6:28 AM  RssIcon

image

The primary reason you may want to use WCF RIA Services with Visual Studio LightSwitch 2013 is to:

  • Combine more than one entity into a single entity.
  • Eliminate unneeded columns in an entity to improve performance (otherwise large amounts of data, for example pictures, will be transmitted even when they are not shown).
  • Implement calculated fields that allow the resulting values to be searchable and sortable.

The LightSwitch OData services return one Entity collection at a time. This makes grouping and totaling across Entity collections difficult. Using WCF RIA Services provides a clean elegant solution.

The official documentation from Microsoft on creating WCF RIA Services is available at this link.

WCF RIA Services have been covered previously on this site. This article reflects the latest changes in Visual Studio 2013.

The Sample Application

image

We start with the application used in the article: Online Ordering System (An End-To-End LightSwitch Example).

We upgrade it to Visual Studio 2013.

We now want it to display the total for each Order on the Main page.

Create A WCF RIA Service

image

First, Add a New Project to the existing LightSwitch project.

image

Create a Class Library called WCF_RIA_Project.

image

Delete the Class1.cs file that is automatically created.

image

Add a New Item to WCF_RIA_Project.

image

Add a Class called WCF_RIA_Service.cs.

image

The Class file will show in the Solution Explorer.

image

Right-click on References and select Add References to add the following references to the WCF_RIA_Project

image

  • System.ComponentModel.DataAnnotations
  • System.Configuration
  • System.Data.Entity
  • System.Runtime.Serialization
  • System.Web

To add a reference to System.ServiceModel.DomainServices.Server, click the Browse button…

image

Navigate to %ProgramFiles%\Microsoft SDKs\RIA Services\v1.0\Libraries\Server and select it.

Click the Add button.

image

Click OK.

Add the following Using Statements to the class:

image

using System.Data.EntityClient;
using System.Web.Configuration;
using LightSwitchApplication.Implementation;

(LightSwitchApplication will display with a squiggly red line because the class is missing, but it will be added in the next step)

Reference The LightSwitch Object Context

Now, we will add code from the LightSwitch project to our WCF RIA Service project. We will add a class that LightSwitch automatically creates, that connects to the database that LightSwitch uses.

We will use this class in our WCF RIA Service to communicate with the LightSwitch database.

image

Right-click on the WCF_RIA_Project and select Add then Existing Item.

image

Navigate to ..Server\GeneratedArtifacts (in the LightSwitch project) and click on ApplicationDataObjectContext.cs and select Add then Add As Link.

We used “add As Link” so that whenever LightSwitch updates this class, our WCF RIA Service is also updated.

This is how our WCF RIA Service would be able to see any new Entities (tables) that were added, deleted, or changed.

image

The file will show in the project.

Create the Domain Service

Replace the entire code for the WCF_RIA_Service.cs file with the following:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel.DomainServices.Server;
using System.Data.EntityClient;
using System.Web.Configuration;
using LightSwitchApplication.Implementation;
namespace WCF_RIA_Project
{
    // This class is used as the class that is returned
    // This can have any 'shape' you desire
    // Make sure this is outside of the WCF_RIA_Service class
    // but inside the WCF_RIA_Project namespace
    public class EnhancedOrder
    {
        [Key]
        public int ID { get; set; }
        public string UserName { get; set; }
        public DateTime OrderDate { get; set; }
        public decimal? OrderTotal { get; set; }
    }
    public class WCF_RIA_Service : DomainService
    {
        // This Context property is code that connects to the LightSwitch database
        // The code in the Database connection region can be reused as it is 
        #region Database connection
        private ApplicationData m_context;
        public ApplicationData Context
        {
            get
            {
                if (this.m_context == null)
                {
                    string connString =
                        System.Web.Configuration.WebConfigurationManager
                        .ConnectionStrings["_IntrinsicData"].ConnectionString;
                    EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
                    builder.Metadata =
                        "res://*/ApplicationData.csdl|res://*/ApplicationData.ssdl|res://*/ApplicationData.msl";
                    builder.Provider =
                        "System.Data.SqlClient";
                    builder.ProviderConnectionString = connString;
                    this.m_context = new ApplicationData(builder.ConnectionString);
                }
                return this.m_context;
            }
        }
        #endregion
        [Query(IsDefault = true)]
        public IQueryable<EnhancedOrder> GetAllOrders()
        {
            // Get all the Order Details
            var colEnhancedOrder = from Orders in this.Context.Orders
                                   // Shape the results into the 
                                   // EnhancedOrderDetail class
                                   select new EnhancedOrder
                                   {
                                       // The Order ID
                                       ID = Orders.Id,
                                       // The Order Date
                                       OrderDate = Orders.OrderDate,
                                       // The UserName
                                       UserName = Orders.UserName,
                                       // The order Total
                                       OrderTotal =
                                           // Get all order details lines of the Order
                                       (from OrderDetails in Orders.OrderDetails
                                        // Group the products in the Order Details
                                        group OrderDetails
                                        by OrderDetails.OrderDetail_Product into grouping
                                        // Shape a new entity
                                        select new
                                        {
                                            // Create a total property that is the Quantity times the
                                            // Product price
                                            TotalOrder = grouping.Sum(x => x.Quantity)
                                            * grouping.Sum(x => x.Product.ProductPrice),
                                        }).Sum(x => x.TotalOrder) // Add the sum of all the TotalOrders
                                   };
            return colEnhancedOrder;
        }
        // Override the Count method in order for paging to work correctly
        protected override int Count<T>(IQueryable<T> query)
        {
            return query.Count();
        }
    }
}

 

Consume The WCF RIA Service

image

Build the solution.

image

In the Solution Explorer (of the LightSwitch project), right-click on the Server project and select Add Data Source.

image

Select WCF RIA Service and click Next.

image

The wizard will look for WCF RIA Services.

This step can take a long time because it wont find any at this point.

image

Eventually the Add Reference button will be enabled.

Click it.

image

Select Solution then Projects and then the WCF_RIA_Project and click OK.

image

The wizard will look for WCF RIA Services.

image

The wizard will find the WCF_RIA_Service in the WCF_RIA_Project.

Click Next.

image

Check the box next to the Entities, and click Finish.

image

The Entity will display.

Consume the WCF RIA Service

We can now add the collection to a screen as we would any other collection.

image

We open the Main screen and select Add Data Item, and select the EnhancedOrders collection.

image

The collection will show in the View Model on the left-hand side of the screen.

We drag and drop it to the design surface.

image

We can change the control type to a Table.

image

We delete unneeded fields.

image

We can allow an Order to be edited by selecting the table and wiring up a method to the Item Tap action.

image

We right-click on the method and select Edit Execute Code.

We use the following code for the method:

 

myapp.Main.EnhancedOrders_ItemTap_execute = function (screen) {
    // Get the Order entity that has the same ID 
    // as the selected EnhancedOrders entity
    myapp.activeDataWorkspace.ApplicationData
        .Orders_SingleOrDefault(screen.EnhancedOrders.selectedItem.ID)
        .execute().then(function (result) {
            // Get the OrderEntity
            var OrderEntity = result.results[0];
            // Open the showAddEditOrder screen
            myapp.showAddEditOrder(OrderEntity, {
                afterClosed: function (AddEditOrderScreen, navigationAction) {
                    // If the user commits a change
                    // refresh the Screen.
                    if (navigationAction === msls.NavigateBackAction.commit) {
                        // Refresh the screen collections
                        screen.EnhancedOrders.refresh();
                        screen.Orders.refresh();
                    }
                }
            });
        });
};
 

 

image

When we run the application the orders will show with their calculated field.

 

image

Note, when you build the project, do not be concerned about the warnings. However, you can get rid of them by following the directions at this link: Getting rid of compilation warnings in an intrinsic ria service.

WCF RIA Services Can Read, Update, Insert, and Delete

See the article: WCF RIA Service: Combining Two Tables for an example.

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have Visual Studio 2013 (or higher) installed to run the code)

20 comment(s) so far...


Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Brilliant !

I've been looking all over for this

Thank you for all your great work fro the Lightswitch community

Mick

By MDL on   10/19/2013 4:27 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Great Article.
I little question, using that estructure, in this case VS is going to publish a WFC_RIA_serviceData.svc file wich grant acces to the information via OData
So, ¿Do you know if you can add more security to that particular file? (QueryInterceptor, filter, etc)...and more important...How?

Regards,

Gabriel

By Gabriel Marazzi on   12/13/2013 5:39 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@ Gabriel Marazzi - See my answer in the official LightSwitch forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/1ffaeadd-abbd-42c4-a712-45f022300b3b/wcf-ria-services-and-odata-security?forum=lightswitch

By Michael Washington on   12/13/2013 6:24 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Michael,

Great job as usual. Can you please elaborate how to move the WCF RIA Service created here over to Azure so that LightSwitch would use it instead? Basically I am trying to create a solution with LightSwitch , WCF RIA and Database all in Azure. Thanks.

By Frank on   12/20/2013 1:07 PM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@Frank - Please make a post on the official LightSwitch Forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

By Michael Washington on   12/20/2013 1:08 PM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Hello Michael,

I have the following use case : I have a button on UI, from which I want to trigger the execution of a sql stored procedure, through a wcf ria ExecuteCommand(cmdName) method.
(in fact I have many such buttons, which trigger many different procedures, and a 'generic' method to call them)

Because providing the procedure name and parameters from java-script screen to call a wcf ria method would pose a security risk
(because client-server communication can be intercepted, and sensible information stolen at server calls)
I therefore only want to send from the screen to wcf ria a signal to execute a command X; after this, in wcf ria I would get all the parameters I need from the lightswitch context, neccesary for the command X, and after this execute the stored proceduce safely.

My problem is getting all the data I need: if in my lightswitch datasource I have queries defined on tables, is there any way to call them in wcf ria ? (I see that my queries defined in lightswitch visual editor are not visible in wcf ria).
for example I have defined a query in lightswitch : AgentsTable.GetCurrentAgent() (that returns a agent entity whose username is the same as Application.User.Name), how whould I call this query in wcf ria ?

Or atleast, is there a way to get Application.User in wcf ria ?

Thanks

By Gabriel Cazan on   4/12/2014 11:32 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Hi Michael,
i followed your instructions here to create a ria webservice.
But sometimes i cannot build the solution.
as soon as i include the ApplicationDataObjectContext.cs as a link the solution will no longer build. when i remove the link to ApplicationDataObjectContext.cs the build runs fine.

you have any ideas what the Problem is?

Regards
Thomas

By DarkSideNRW on   3/30/2014 9:45 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@DarkSideNRW - Sorry no, I use this all the time and it works for me.

By Michael Washington on   3/30/2014 10:05 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@DarkSideNRW - I have same problem. Did you find out what solution was?

By Mark Anderson on   4/12/2014 10:24 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@ Gabriel Cazan - You will want to post to the official LightSwitch forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

By Michael Washington on   4/12/2014 11:34 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

This post appears to apply to Lightswitch HTML projects. Are you aware of any easy to understand instructions for enabling RIA Services for Lightswitch 2013 Desktop ?

By Gustav Scholtz on   4/19/2014 4:43 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@Gustav Scholtz - The WCF RIA service is the same, consuming it is different, but the only change is that you use the Desktop Clint Screen.

By Michael Washington on   4/19/2014 4:47 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Hi Michael,

Thank you very much for this very helpful article. This is what I'm looking for - A 'native' way to feed customize data to LS html client.

But unfortunately, looks like it doesn't work with the latest VS/LS update. Even the sample project doesn't work.

Could you please help to provide the update on this?

Thanks again!

Yelong

By Yelong on   5/6/2014 8:08 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@Yelong - I have the March update and I tested the code and it works.

By Michael Washington on   5/6/2014 1:03 PM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

HI Michael,
I tried your tutorial step by step but was not able to find ApplicationDataObjectContext.cs file in my server project.
Im using VS 2013 -with march 2014 update.

By priyanka on   6/17/2014 9:26 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@priyanka - You have to have at least one table in your project and to build the project for the ApplicationDataObjectContext.cs to exist. That is why the first step in the tutorial is to start with the project created in the End-To-End tutorial :)

By Michael Washington on   6/17/2014 3:07 PM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

Hi Michael,

great article and website - I am a frequent visitor. I have followed this article and built a WCF RIA service which compiles fine. However, when calling any function in the service no data is returned. I am not querying the intrinsic database, but SQL Server 2012. Are there any changes that I need to make to get it to work (other than changing the context connection string) against SQL Server?

Regards,

Alan

By Alan Barnard on   6/30/2014 3:45 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@Alan Barnard - This tutorial only works for querying the intrinsic database.

By Michael Washington on   6/30/2014 3:46 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@Michael, does the LightSwitch with WCF RIA Service support CRUD, how LightSwitch know which method should be invoked(for create/delete/update),is there some sample I can follow?

By ArthurJiang on   7/22/2014 3:46 AM
Gravatar

Re: Creating a WCF RIA Service for Visual Studio LightSwitch 2013

@ArthurJiang - See http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/187/LightSwitch-HTML-Picture-Manager-Using-WCF-RIA-Services.aspx for a CRUD example.

By Michael Washington on   7/22/2014 3:50 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation