Welcome!

Silverlight Authors: Automic Blog, Michael Kopp, AppDynamics Blog, Kaazing Blog, Steven Mandel

Related Topics: Silverlight, Microsoft Cloud, Machine Learning

Silverlight: Blog Feed Post

Business Apps Example for Silverlight 3 RTM

and .NET RIA Services July Update: Part 2: Rich Data Query

Continuing in our discussion of Silverlight 3 and  the brand new update to .NET RIA Services and the update the example from my Mix09 talk “building business applications with Silverlight 3”.

You can watch the original  video of the full session 

The demo requires (all 100% free and always free):

  1. VS2008 SP1 (Which includes Sql Express 2008)
  2. Silverlight 3 RTM
  3. .NET RIA Services July '09 Preview

Also, download the full demo files and check out the running application.

Today, we will talk about Rich Data Query. 

 

Rich Data Query

Next up, let’s talk about data query.  Nearly every business application deals with data.   Let’s look at how to do this with .NET RIA Services.   We will start out in the web project.   For this example I will use an Entity Framework data model, but RIA Services works great with any form of data from plain olld CLR objects to an xml file, to web services to Linq to Sql.   For starters, let’s build an Entity Framework model for our data.   For this walk through, we will start simply…

image

I updated the pluralization of the entity name

Now, how are we going to access this data from the SL client?  Well, traditionally many business applications have started out as 2-tier apps. That has a number of problems around scaling and flexibility… and more to the point it just doesn’t work with the Silverlight\web client architecture.   

image

So developers are thrust into the n-tier world.  .NET RIA Services make it very easy to create scalable, flexible n-tier services that builds on WCF and ADO.NET Data Services. 

image

These .NET RIA Services model your UI-tier application logic and encapsulate your access to varies data sources from traditional relational data to POCO (plain old CLR objects) to cloud services such as Azure, S3, etc via REST, etc.  One of the great thing about this is that you can move from an on premises Sql Server to an Azure hosted data services without having to change any of your UI logic. 

Let’s look at how easy it is to create these .NET RIA Services. 

Right click on the server project and select the new Domain Service class

image_thumb[26]

In the wizard, select your data source.  Notice here we could have chosen to use a Linq2Sql class, a POCO class, etc, etc. 

image_thumb[28]

In the SuperEmployeeDomainService.cs class we have stubs for all the CRUD method for accessing your data.   You of course should go in and customize these for your domain.  For the next few steps we are going to use GetSuperEmployees(), so I have customized it a bit. 

public IQueryable<SuperEmployee> GetSuperEmployees()
{
    return this.Context.SuperEmployeeSet
               .Where(emp=>emp.Issues>100)
               .OrderBy(emp=>emp.EmployeeID);
}

Now, let’s switch the client side.  Be sure to build the solution so you can access it from the client directly.  These project are linked because we selected the “ASP.NET enable” in the new project wizard. 

Drag the DataGrid off the toolbox… notice this works with any control.. 

image_thumb[29]

In HomePage.Xaml add

<data:DataGrid x:Name="dataGrid1" Height="500"></data:DataGrid> 

And in the code behind add MyApp.Web… notice this is interesting as MyApp.Web is defined on the server…  you can now access the client proxy for the server DomainServices locally

image

   1: var context = new SuperEmployeeDomainContext();
   2: dataGrid1.ItemsSource = context.SuperEmployees;
   3: context.Load(context.GetSuperEmployeesQuery());

In line 1, we create our SuperEmployeesDomainContext.. this is the client side of the SuperEmployeesDomainService.  Notice the naming convention here…

In line 2, we are databinding the grid to the SuperEmployees.. then in line 3 we are loading the SuperEmployees, that class the GetSuperEmployees() method we defined on the server.  Notice this is all async of course, but we didn’t have to deal with the complexities of the async world. 

image_thumb[30]

The result!  We get all our entries back, but in the web world,don’t we want to do paging and server side sorting and filtering?  Let’s look at how to do that.

First, remove the code we just added to codebehind.

Then, to replace that, let’s add a DomainDataSource. You can just drag it in from the toolbox:

image_thumb[31]

Then edit it slightly to get:

   1: <riaControls:DomainDataSource x:Name="dds" 
   2:         AutoLoad="True"
   3:         QueryName="GetSuperEmployeesQuery"
   4:         LoadSize="20">
   5:     <riaControls:DomainDataSource.DomainContext>
   6:         <App:SuperEmployeeDomainContext/>
   7:     </riaControls:DomainDataSource.DomainContext>
   8: </riaControls:DomainDataSource>

Notice in line 3, we are calling that GetSuperEmployeesQuery method from the DomainContext specified in line 6.  

In line 4, notice we are setting the LoadSize to 20.. that means we are going to download data in batches of 20 at a time.

Now, let’s bind it to a the DataGrid and show a little progress indicator (that you can get in the sample).. 

   1: <activity:Activity IsActive="{Binding IsBusy, ElementName=dds}"
   2:                    VerticalAlignment="Top" 
   3:                    HorizontalAlignment="Left" 
   4:                    Width="900" Margin="10,5,10,0">
   5:     <StackPanel>
   6:         <data:DataGrid x:Name="dataGrid1" Height="300" Width="900"
   7:                        ItemsSource="{Binding Data, ElementName=dds}">
   8:          </data:DataGrid>
   9:          <data:DataPager PageSize="10" Width="900"
  10:                          HorizontalAlignment="Left"
  11:                          Source="{Binding Data, ElementName=dds}" 
  12:                          Margin="0,0.2,0,0" />
  13:      </StackPanel>
  14: </activity:Activity>

In line 6, there is a datagrid, that is bound  to the DDS.Data property (in line 7).  Then we add a DataPager in line 9, that is bound to the same datasource.  this gives us the paging UI.  Notice in line 9 we are setting the display to 10 records at a time.  Finally we wrap the whole thing in an ActivityControl to show progress.

The cool thing is that the ActivityControl, the DataGrid and the DataPager can all be used with any datasource such as data from WCF service, REST service, etc. 

Hit F5, and you see.. 

image_thumb[35]

Notice we are loading 20 records at a time, but showing only 10.  So advancing one page is client only, but advancing again we get back to the server and load the next 20.  Notice this all works well with sorting as well.   And the cool thing is where is the code to handle all of this?  Did i write in on the server or the client?  neither.  Just with the magic of linq, things compose nicely and it i just falls out. 

I can early add grouping..

<riaControls:DomainDataSource.GroupDescriptors>
    <datagroup:GroupDescriptor PropertyPath="Publishers" />
</riaControls:DomainDataSource.GroupDescriptors>

image_thumb[37]

Let’s add filtering… First add a label and a textbox..

<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
    <TextBlock Text="Origin: "></TextBlock>
    <TextBox x:Name="originFilterBox" Width="75" Height="20"></TextBox>
</StackPanel>

and then these filter box to our DomainDataSource….

<riaControls:DomainDataSource.FilterDescriptors>
    <datagroup:FilterDescriptorCollection>
        <datagroup:FilterDescriptor PropertyPath="Origin"
                           Operator="StartsWith">
            <datagroup:ControlParameter PropertyName="Text" 
                           RefreshEventName="TextChanged"
                           ControlName="originFilterBox">
            </datagroup:ControlParameter>
        </datagroup:FilterDescriptor>
    </datagroup:FilterDescriptorCollection>
</riaControls:DomainDataSource.FilterDescriptors>

When we hit F5, we get a filter box, and as we type in it we do a server side filtering of the results. 

image_thumb[40]

Now, suppose we wanted to make that a autocomplete box rather an a simple text box.   The first thing we’d have to do is get all the options.  Notice we have to get those from the server (the client might not have them all because we are doing paging, etc).  To do this we add a method to our DomainService. 

public class Origin
{
    public Origin() { }
    [Key]
    public string Name { get; set; }
    public int Count { get; set; }
}

and the method that returns the Origins…

public IQueryable<Origin> GetOrigins()
{
    var q = (from emp in Context.SuperEmployeeSet
             select emp.Origin).Distinct()
            .Select(name => new Origin
            {
                Name = name,
                Count = Context.SuperEmployeeSet.Count
                    (emp => emp.Origin.Trim() == name.Trim())
            });
    q = q.Where(emp => emp.Name != null);
    return q;
}

Now we need to add the autocomplete control from the Silverlight 3 SDK.  Replace the textbox with this:

<input:AutoCompleteBox  x:Name="originFilterBox" Width="75" Height="30"
                        ValueMemberBinding="{Binding Name}" 
                        ItemTemplate="{StaticResource OriginsDataTemplate}" >
</input:AutoCompleteBox>

Then we just need to add a little bit of code behind to load it up.

var context = dds.DomainContext as SuperEmployeeDomainContext;
originFilterBox.ItemsSource = context.Origins;
context.Load(context.GetOriginsQuery());

Hitting F5 gives us this…

image_thumb[43]

Validating Data Update

Now – that was certainly some rich ways to view data, but business apps need to update data as well.  Let’s look at how to do that.   First replace all the xaml below the DDS with this… it gives us a nice master-details view.

   1: <StackPanel  Style="{StaticResource DetailsStackPanelStyle}">
   2:  
   3:                    <activity:Activity IsActive="{Binding IsBusy, ElementName=dds}">
   4:                        <StackPanel>
   5:                            <StackPanel Orientation="Horizontal" Margin="0,0,0,10">
   6:                                <TextBlock Text="Origin: " />
   7:  
   8:                                <input:AutoCompleteBox  x:Name="originFilterBox" Width="338" Height="30"
   9:                                                    ValueMemberBinding="{Binding Name}" 
  10:                                                    ItemTemplate="{StaticResource OriginsDataTemplate}" />
  11:                            </StackPanel>
  12:  
  13:                            <data:DataGrid x:Name="dataGrid1" Height="380" Width="380" 
  14:                                           IsReadOnly="True" AutoGenerateColumns="False" 
  15:                                           HorizontalAlignment="Left" 
  16:                                           HorizontalScrollBarVisibility="Disabled"
  17:                                           ItemsSource="{Binding Data, ElementName=dds}" 
  18:                                       >
  19:                                <data:DataGrid.Columns>
  20:                                    <data:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
  21:                                    <data:DataGridTextColumn Header="Employee ID"  Binding="{Binding EmployeeID}" />
  22:                                    <data:DataGridTextColumn Header="Origin"  Binding="{Binding Origin}" />
  23:                                </data:DataGrid.Columns>
  24:                            </data:DataGrid>
  25:  
  26:                            <data:DataPager PageSize="13" Width="379" 
  27:                                            HorizontalAlignment="Left"
  28:                                            Source="{Binding Data, ElementName=dds}" 
  29:                                            Margin="0,0.2,0,0" />
  30:  
  31:                            <StackPanel Orientation="Horizontal" Margin="0,5,0,0">
  32:                                <Button Content="Submit" Width="105" Height="28"
  33:                                    />
  34:    
  35:  
  36:                                <!--new emp button here-->
  37:  
  38:  
  39:                            </StackPanel>
  40:  
  41:                        </StackPanel>
  42:                    </activity:Activity>
  43:  
  44:                    <StackPanel Margin="35,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="498" >
  45:                        <dataControls:DataForm x:Name="dataForm1" Height="393" Width="331"
  46:                               VerticalAlignment="Top"       
  47:                               Header="Product Details"
  48:                               CurrentItem="{Binding SelectedItem, ElementName=dataGrid1}" 
  49:                                HorizontalAlignment="Left" >
  50:                            <dataControls:DataForm.EditTemplate>
  51:                                <DataTemplate>
  52:                                    <StackPanel>
  53:                                        <dataControls:DataField>
  54:                                            <TextBox Text="{Binding Name, Mode=TwoWay}" />
  55:                                        </dataControls:DataField>
  56:                                        <dataControls:DataField>
  57:                                            <TextBox Text="{Binding EmployeeID, Mode=TwoWay}" />
  58:                                        </dataControls:DataField>
  59:                                        <dataControls:DataField>
  60:                                            <TextBox Text="{Binding Origin, Mode=TwoWay}" />
  61:                                        </dataControls:DataField>
  62:                                        <dataControls:DataField>
  63:                                            <TextBox Text="{Binding Sites, Mode=TwoWay}" />
  64:                                        </dataControls:DataField>
  65:  
  66:                                        <dataControls:DataField>
  67:                                            <TextBox Text="{Binding Gender, Mode=TwoWay}" />
  68:                                        </dataControls:DataField>
  69:  
  70:                                        <dataControls:DataField>
  71:                                            <TextBox Text="{Binding Publishers, Mode=TwoWay}" />
  72:                                        </dataControls:DataField>
  73:                                        <dataControls:DataField>
  74:                                            <controls:DatePicker Text="{Binding LastEdit, Mode=OneWay}"></controls:DatePicker>
  75:                                        </dataControls:DataField>
  76:                                        <dataControls:DataField>
  77:                                            <TextBox Text="{Binding Issues, Mode=TwoWay}" />
  78:                                        </dataControls:DataField>
  79:                                    </StackPanel>
  80:                                </DataTemplate>
  81:                            </dataControls:DataForm.EditTemplate>
  82:  
  83:  
  84:                        </dataControls:DataForm>
  85:  
  86:  
  87:  
  88:                        <!--Permalink here-->
  89:  
  90:                    </StackPanel>
  91:  
  92:  
  93:                </StackPanel>
   

Through line 35, this is pretty much the same as what we had. 

Then in line 38, we add a DataForm control that gives us some nice way to view and edit a particular entity. 

Hit F5

image

This looks like the traditional master-details scenario.

image_thumb[44]

Notice as we change items they are marked as “Dirty” meaning they need to be submitted back to the server.  You can make edits to many items, unmake some edits and the dirty marker goes away. 

Now we need to wire up the submit button. 

   1: private void SubmitButton_Click(object sender, RoutedEventArgs e)
   2: {
   3:     dataForm1.CommitEdit();
   4:     dds.SubmitChanges();
   5: }

We first need to commit the item we are currently editing, then we just submit changes.  This batches up the diffs and sends them back the server.  and our Update method is called.  Notice the dirty bit goes away.

Now, that is cool, but what about Data Validation?  Well, “for free” you get type level validation (if the filed is typed as an int you and you enter a string you get an error). 

image_thumb[46]

Now let’s see if we can add a bit more.  We do that by editing the SuperEmployeeDomainService.metadata.cs on the server.  It is important to do it on the server so that the system does all the validations are done once for a great UX experience and then again on the server for data integrity.  By the time your Update method is called on your DomainService you can be sure that all the validations have been done. 

Here are some of the validations we can apply.. 

[ReadOnly(true)]
public int EmployeeID;
 
public EntityState EntityState;
 
[RegularExpression("^(?:m|M|male|Male|f|F|female|Female)$", 
    ErrorMessage = "Gender must be 'Male' or 'Female'")]
public string Gender;
 
[Range(0, 10000,
    ErrorMessage = "Issues must be between 0 and 1000")]
public Nullable<int> Issues;
 
public Nullable<DateTime> LastEdit;
 
[Required]
[StringLength(100)]
public string Name;

Just rebuilding and running the app gives us great validation in the UI and in the middle tier. 

image_thumb[48]

Notice how I can navigate between the errors and input focus moves to the next one. 

That was updating data, what about adding new data?

To do that, let’s explorer the new Silverlight 3 ChildWindow.

Right click on Views and add new Item Child Window

image_thumb[50]

Let’s wire it up to show the default window. First add a button to the main form to display the childwindow we just created.

<Button Content="Add New" 
        Width="105" Height="28"
        Margin="5,0,0,0" HorizontalAlignment="Left"
        Click="AddNew_Click" ></Button>

Then wire it up..

private void AddNew_Click(object sender, RoutedEventArgs e)
{
    var w = new AddNewWindow();
    w.Show();
}

image_thumb[51]

Notice it already has a OK and Cancel buttons and a close box that work great right out of the box.  We just need to add a DataForm.  Because we are bound to the same model, the DataForm will pick up all the same features as the update one we just looked at.

<dataControls:DataForm x:Name="newEmployeeForm" Height="393" Width="331"
                       VerticalAlignment="Top"    
                       CommandButtonsVisibility="None"
                       Header="Add New Super Employee"
                        HorizontalAlignment="Left" >
    <dataControls:DataForm.EditTemplate>
        <DataTemplate>
            <StackPanel>
                <dataControls:DataField>
                    <TextBox Text="{Binding Name, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding EmployeeID, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding Origin, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding Sites, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding Gender, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding Publishers, Mode=TwoWay}" />
                </dataControls:DataField>
                <dataControls:DataField>
                    <controls:DatePicker Text="{Binding LastEdit, Mode=OneWay}"></controls:DatePicker>
                </dataControls:DataField>
                <dataControls:DataField>
                    <TextBox Text="{Binding Issues, Mode=TwoWay}" />
                </dataControls:DataField>
            </StackPanel>
        </DataTemplate>
    </dataControls:DataForm.EditTemplate>
</dataControls:DataForm>

Now, in code behind we need to write this up by adding a class level field..

public SuperEmployee NewEmployee { get; set; }

..initializing the instance in the constructor

 
            NewEmployee = new SuperEmployee();
            NewEmployee.LastEdit = DateTime.Now.Date;
            this.newEmployeeForm.CurrentItem = NewEmployee;

..handling the OK button

private void OKButton_Click(object sender, RoutedEventArgs e)
{
    newEmployeeForm.CommitEdit();
    this.DialogResult = true;
}

image_thumb[54]

Great… now let’s commit this change locally.

void addNewWindow_Closed(object sender, EventArgs e)
{
    var win = sender as AddNewWindow;
    var context = dds.DomainContext as SuperEmployeeDomainContext;
    if (win.DialogResult == true)
    {
        context.SuperEmployees.Add(win.NewEmployee);
    }
}

From this, the Submit button will send this change to the server.

Read the original blog entry...

More Stories By Brad Abrams

Brad Abrams is currently the Group Program Manager for the UI Framework and Services team at Microsoft which is responsible for delivering the developer platform that spans both client and web based applications, as well as the common services that are available to all applications. Specific technologies owned by this team include ASP.NET, Atlas and Windows Forms. He was a founding member of both the Common Language Runtime, and .NET Framework teams.

Brad has been designing parts of the .NET Framework since 1998 when he started his framework design career building the BCL (Base Class Library) that ships as a core part of the .NET Framework. He was also the lead editor on the Common Language Specification (CLS), the .NET Framework Design Guidelines, the libraries in the ECMA\ISO CLI Standard, and has been deeply involved with the WinFX and Windows Vista efforts from their beginning.

He co-authored Programming in the .NET Environment, and was editor on .NET Framework Standard Library Annotated Reference Vol 1 and Vol 2 and the Framework Design Guidelines.

IoT & Smart Cities Stories
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. The IoT Global Network is a platform where you can connect with industry experts and network across the IoT community to build the successful IoT business of the future.
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, Esmeralda Swartz, CMO at MetraTech; Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems; Seema Jethani, Director of Product Management at Basho Technologies; Victoria Livschitz, CEO of Qubell Inc.; Anne Hungate, Senior Director of Software Quality at DIRECTV, discussed what path they took to find their spot within the tec...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...