You are here:   Blog
Register   |  Login

LightSwitch News

Maps for WinRT XAML
8/20/2014 1:41 PM

 

Apr 11

Written by: Michael Washington
4/11/2013 9:43 PM  RssIcon

The current version of the LightSwitch HTML Client does not expose the computed properties created at the Entity level. Here are a few methods you can use.

image

In LightSwitch, we can create a computed column and use the following code for the result:

 

        partial void OrderTotal_Compute(ref decimal? result)
        {
            decimal dOrderTotal = 0.0M;
            // Get OrderDetails that have products
            var colOrderDetails = from OrderDetails in this.FlowerShopOrderDetail
                                  where OrderDetails.FlowerShopProduct != null
                                  select OrderDetails;
            foreach (var order in colOrderDetails)
            {
                dOrderTotal = dOrderTotal + (order.Quantity * order.FlowerShopProduct.Price);
            }
            result = dOrderTotal;
        }

 

When we consume the Entity in the LightSwitch Silverlight client…

image

The value shows.

image

However, when we create a page with the LightSwitch HTML Client we don’t have access to the computed property.

 

Using JavaScript

We can create the computed property using JavaScript.

 image

First, we Add Data Item to the Visual Studio LightSwitch HTML Client screen.

image

We add an Integer property to the screen called TotalOfOrders, and we drag it to the screen layout.

image

We click on the screen element, and in the Properties, we select Edit PostRender Code.

We use the following code:

 

myapp.AddEditFlowerShopOrder.NumberOfDetails_postRender = function (element, contentItem) {
    function updateTotal() {
        // Compute the total for the Order
        contentItem.screen.TotalOfOrders =
            TotalOrders(contentItem.screen.FlowerShopOrderDetail);
    }
    // Set a dataBind to update the value when the collection changes
    contentItem.dataBind("screen.FlowerShopOrderDetail.count", updateTotal)
};
// Function to compute the total for the Order 
function TotalOrders(OrderDetails) {
    // Start with 0
    var TotalAmountOfOrders = 0;
    // Get the data for the collection passed
    var OrderDetail = OrderDetails.data;
    // Loop through each row
    OrderDetail.forEach(function (order) {
        // Add each row to TotalAmountOfOrders
        TotalAmountOfOrders = TotalAmountOfOrders +
            (order.Quantity * order.FlowerShopProduct.Price);
    });
    // Return TotalAmountOfOrders
    return TotalAmountOfOrders;
}

 

 

image

When we run the application, the value will now show.

Note: in this example we only detect that the count of the records has changed. If for example, only the price changed, you would expect that the computed property to change, it would not. Also, if the list were a paged list and there were more records than the current page setting (the default is 45 records per page) it would not update properly.

However, in this example we return the user to the main screen after making any change, when they return to this screen the value is always properly updated.

 

Using WCF RIA Service

The limitation with the method above is that you would not be able to query or sort on the computed value when used in a collection. A WCF RIA Service resolves any limitations.

We follow the article: Shape Your LightSwitch OData Using WCF RIA Services.

Note: With the latest version of Visual Studio LightSwitch HTML Client you need to connect to "ApplicationDataObjectContext.cs", change "ApplicationDataObjectContext" (in the code) to "ApplicationData" and use: "using LightSwitchApplication.Implementation;" in the using statement section.

 

We use the following code for the method:

 

      [Query(IsDefault = true)]
        public IQueryable<EnhancedFlowerShopOrder> GetAllOrders()
        {
            // Get all the Orders
            var colFlowerShopOrders = from Order in this.Context.FlowerShopOrders
                                      // Shape the results into the 
                                      // EnhancedFlowerShopOrder class
                                      select new EnhancedFlowerShopOrder
                                      {
                                          // The Order ID
                                          ID = Order.Id,
                                          // The Order Date
                                          OrderDate = Order.OrderDate,
                                          // The first name of the Customer
                                          FirstName = Order.FlowerShopCustomer.FirstName,
                                          // The last name of the Customer
                                          LastName = Order.FlowerShopCustomer.LastName,
                                          // The order Total
                                          OrderTotal =
                                          // Get all order details lines of the Order
                                          (from FlowerShopOrderDetail in Order.FlowerShopOrderDetail
                                           // Group the products in the Order Details
                                           group FlowerShopOrderDetail 
                                           by FlowerShopOrderDetail.Id into g
                                           // Shape a new entity
                                           select new
                                           {
                                               // Create a total property that is the Quantity times the
                                               // Product price
                                               TotalOrder = g.Sum(x => x.Quantity) 
                                               * g.Sum(x => x.FlowerShopProduct.Price),
                                           }).Sum(x => x.TotalOrder) // Add the sum of all the TotalOrders
                                      };
            return colFlowerShopOrders;
        }

 

image

When we consume the Entity, the property shows up  in the screen designer like a normal field.

 

image

The computed value shows up in a list…

image

… and in a detail record.

 

 

Special Thanks

A special thanks to Stephen Provine for his assistance.

 

Download Code

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

(you must have Visual Studio 2012 Update 2 installed to run the code)

12 comment(s) so far...


Gravatar

Re: Computed Properties With the LightSwitch HTML Client

Hi Michael

I have migrated my project and created a RIA service. After adding "ApplicationDataObjectContext.cs" and "using LightSwitchApplication.Implementation;" still getting the below error

Error 1 The type or namespace name 'ApplicationDataObjectContext' could not be found (are you missing a using directive or an assembly reference?) F:\Samples\Visual_Studio_2012\LightSwitchHtmlRia\WcfRiaService\RiaDomainService.cs 19 17 WcfRiaService

Can you please help me out to solve this?

Your reply appreciated.

Thanks

By Rashmi on   4/11/2013 10:08 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@Rashmi - Download the code for this article and compare it to your own.

By Michael Washington on   4/11/2013 10:13 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

it has only trouble using RIA Service! After get data, if you update some items, the computed fild doesn´t refresh automaticly. You need to press F5 to refresh the screen

By Roberto Filho on   5/1/2013 5:35 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@Roberto Filho - The WCF RIA Service is searchable and sortable. This is why I show two different methods.

By Michael Washington on   5/1/2013 5:36 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

So...basically computed properties are pretty much useless when using the HTML client (at least for displaying data)? We may as well just compute them *on the client*?

By Stuart Dobson on   6/2/2013 5:12 AM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@Stuart Dobson - For now, but that may change in a future release.

By Michael Washington on   6/2/2013 5:13 AM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

I'm using VS2013.

I'm also missing the ApplicationDataObjectContext.cs in my generatedArtifacts folder.

Does this mean that I can't use WCF RIA? I want to use it because I have to deal with data from multiple databases.

Great site and great book. I hope there is a solution.

Of course, I suppose I could copy yours and edit it since it obviously won't get overwritten but I don't particularly like that solution.

By BillRossPaxEDI on   11/22/2013 1:09 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@BillRossPaxEDI - If you are using Visual Studio 2013 see: http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/2226/Creating-a-WCF-RIA-Service-for-Visual-Studio-2013.aspx

By Michael Washington on   11/22/2013 2:12 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

My assumption is that the file ApplicationDataObjectContext.cs is always that name and not application specific, yes? Because I have a "MyAppDataObjectContext.cs in that folder and it looks very similar to yours.

By BillRossPaxEDI on   11/22/2013 3:14 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@BillRossPaxEDI - If you have an attached data source the name may be different. I am not sure because I don't use attached data sources. My tutorial should work as described.

By Michael Washington on   11/22/2013 3:21 PM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

Assuming you wanted to calculate an average, picture a situation where you have x(count)students and y(totalmarks obtained). you want to get the mean score for a particular course/unit.( TOTAL MARKS OBTAINED FOR THE PARTICULAR COURSE/UNIT) divided by (TOTAL COUNT OF STUDENTS). How would you go about this in lightswitch 2013 c#. Please

By Moses Maina on   1/9/2014 8:41 AM
Gravatar

Re: Computed Properties With the LightSwitch HTML Client

@Moses Maina - You will want to make a post in the Official LightSwitch forums at: http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=lightswitch

By Michael Washington on   1/9/2014 8:42 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