Thursday, July 16, 2009
kick it on DotNetKicks.com

We have pushed our EntitySpaces Silverlight application up so you can run it and take a look at it. We decided to compile it under the Silverlight 3 toolset so it requires Silverlight 3 to run it. We did this to make sure we are compatible. Silverlight 3 is RTM now and you can download the Visual Studio tools for it HERE but you do not need these to run the demo, just to develop Silverlight 3 applications. There is a lot of code posted in this blog post but we thought you might really want to know how this stuff works, it’s not that hard to understand if you take the time to look at the code. The online demo can be found here ==> DEMO

image

You can add rows and edit rows and then save the data. We are using the Microsoft SQL Northwind database, specifically the Employees table. When you search you can search on the first name or last name fields. The purpose of this demo is not to make a really cool Silverlight UI, but to show how easy it is to use EntitySpaces to write a Silverlight application. There is one glitch when editing data. You need to move off of the selected row for your edits to “take”. This is a Silverlight issue and not an EntitySpaces Issue. The demo is included in our current alpha, however the version shown here is fancier. (It will be in the next release as shown above).

The EntitySpaces Silverlight Demo uses our EntitySpaces proxies on both sides of the conversation. The client side proxies run under Silverlight and our server side proxies run on the server. The Silverlight application hits our WCF service to fetch the data.

The WCF Service

This is what the WCF Service looks like including the Interface. The Interface for the service is shown below. Notice we are returning and taking the EntitySpaces Proxy Stub classes as parameters. However, we pass the EntitySpaces DynamicQuery to the server in string form. The EntitySpaces DynamicQuery is now fully functional under Silverlight and requires only a single 49k assembly which will automatically download with your Siverlight application.

using System.ServiceModel;
 
using BusinessObjects;
 
namespace EntitySpaces.SilverlightApplication.Web
{
    [ServiceContract]
    public interface INorthwind
    {
        [OperationContract]
        EmployeesCollectionProxyStub GetEmployees(string employeesQuery);
 
        [OperationContract]
        EmployeesCollectionProxyStub SaveEmployees(EmployeesCollectionProxyStub collection);
    }
}
 
The implementation class is shown below. Notice in GetEmployees() we deserialize the incoming query (passed as a string) with a single one-line call into a full server side query that we can execute. We then use that query to load our collection, and finally wrap it with a proxy collection and return it. The Save() method is ridiculously simple and powerful. Notice that we merely access the incoming proxies “Collection” property (which is a full EmployeesCollection class) and call save on it. Then we simply return the very same proxy that was sent to us as the incoming parameter. Try clicking the Add button in our demo a few times and then press the Save button. Notice the auto identity columns are immediately reflected in the grid. These are returned automatically via our save method. This is an incredibly powerful and easy way to create Silverlight applications. The row state, including added, modified, and deleted, are automatically maintained for you. All you have to do is call save.
 
using System;
using System.Collections.Generic;
using System.ServiceModel.Activation;
 
using BusinessObjects;
 
namespace EntitySpaces.SilverlightApplication.Web
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Northwind : INorthwind
    {
        #region INorthwind Members
 
        public EmployeesCollectionProxyStub GetEmployees(string serializedQuery)
        {
            List<Type> types = new List<Type>();
            types.Add(typeof(EmployeesQuery));
 
            EmployeesQuery employeesQuery = EmployeesQuery.SerializeHelper.FromXml(
                serializedQuery, typeof(EmployeesQuery), types) as EmployeesQuery;
 
            EmployeesCollection employeesCollection = new EmployeesCollection();
            if (employeesCollection.Load(employeesQuery))
            {
                EmployeesCollectionProxyStub proxy = new EmployeesCollectionProxyStub(employeesCollection);
                return proxy;
            }
 
            return null;
        }
 
        public EmployeesCollectionProxyStub SaveEmployees(EmployeesCollectionProxyStub collection)
        {
            if (collection != null)
            {
                collection.GetCollection().Save();
                return collection;
            }
 
            return null;
        }
 
        #endregion
    }
}


The Silverlight Page

Our Page.xaml file looks like this. A lot of this is just noise like setting up the buttons and such. The part you are interested in is the <data:DataGrid.Columns> section where we manually setup the columns we want to display in the grid. We could have used AutoGenerateColumns=“True” however. For the two date columns we use a DataGridTemplateColumn in order to hookup the fancy date editing control. We also set the EmployeeID column to read only so that users cannot edit the primary key.

<UserControl xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="EntitySpaces.SilverlightApplication.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
    <Grid Background="Black" >
 
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
 
        <Grid Grid.Row="0" Margin="7">
 
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"></ColumnDefinition>
                <ColumnDefinition Width="300"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="240"></ColumnDefinition>
                <ColumnDefinition Width="75"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            
            <HyperlinkButton Grid.Column="0" NavigateUri="http://www.entityspaces.net" TargetName="New"><Image Source="EntitySpaces_Logo.jpg" Grid.Column="0" /></HyperlinkButton>
            <TextBlock Name="SearchTextBlock" Grid.Column ="1" Text="EntitySpaces 2009 Silverlight Demo" Foreground="Yellow" FontSize="14" Margin="10,5,10,5" VerticalAlignment="Center"></TextBlock>
            <ProgressBar Name="WorkingBar" Grid.Column="2" Foreground="Yellow" Background="Black" Value="0" Maximum="100" Margin="2,2,2,2" />
            <TextBox Name="SearchTextBox" Text="Enter Criteria Here" Grid.Column="3" Margin="20,0,20,0" Padding="10,5,10,5" FontSize="14" GotFocus="SearchTextBox_GotFocus"></TextBox>
            <Button Name="SearchButton" Content="Search" Grid.Column="4" FontSize="14" Click="SearchButton_Click"></Button>
        </Grid>
 
 
 
        <Grid Grid.Row="1" Margin="7">
            <data:DataGrid Name="EmployeesDataGrid" AutoGenerateColumns="False" >
 
                <data:DataGrid.Columns>
 
                    <data:DataGridTextColumn Binding="{Binding EmployeeID}" Header="Employee ID" IsReadOnly="True" />
                    <data:DataGridTextColumn Binding="{Binding FirstName}" Header="First Name" />
                    <data:DataGridTextColumn Binding="{Binding LastName}" Header="Last Name" />
                    <data:DataGridTextColumn Binding="{Binding HomePhone}" Header="Home Phone" />
                    <data:DataGridTextColumn Binding="{Binding City}" Header="City" />
 
                    <data:DataGridTemplateColumn Header="Hire Date" Width="160">
                        <data:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding HireDate, Mode=OneWay, Converter={StaticResource ShortDateConverter}}" VerticalAlignment="Center" Margin="2"/>
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellTemplate>
                        <data:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <controls:DatePicker SelectedDate="{Binding HireDate, Mode=TwoWay}" />
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellEditingTemplate>
                    </data:DataGridTemplateColumn>
 
 
                    <data:DataGridTemplateColumn Header="Birth Date" Width="160">
                        <data:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding BirthDate, Mode=OneWay, Converter={StaticResource ShortDateConverter}}" VerticalAlignment="Center" Margin="2"/>
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellTemplate>
                        <data:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <controls:DatePicker SelectedDate="{Binding BirthDate, Mode=TwoWay}" />
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellEditingTemplate>
                    </data:DataGridTemplateColumn>
 
                </data:DataGrid.Columns>
 
            </data:DataGrid>
        </Grid>
 
        <Grid Grid.Row="2" Margin="7">
 
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="75"></ColumnDefinition>
                <ColumnDefinition Width="15"></ColumnDefinition>
                <ColumnDefinition Width="75"></ColumnDefinition>
                <ColumnDefinition Width="15"></ColumnDefinition>
                <ColumnDefinition Width="75"></ColumnDefinition>
            </Grid.ColumnDefinitions>
 
            <Button Name="AddButton" Content="Add" Grid.Row="2" Grid.Column="1" FontSize="14" Click="AddButton_Click" ></Button>
            <Button Name="SaveButton" Content="Save" Grid.Row="2" Grid.Column="3" FontSize="14" Click="SaveButton_Click" ></Button>
            <Button Name="ClearButton" Content="Clear" Grid.Row="2" Grid.Column="5" FontSize="14" Click="ClearButton_Click" ></Button>
        </Grid>
 
    </Grid>
</UserControl>

 

Our Page.xaml.cs file is shown below. Take a look at the SearchButton_Click event. We build the EntitySpaces DynamicQuery and call the service.GetEmployeesAsync() method passing in the query in string form. In the service_GetEmployeesCompleted() method we access our EmployeesCollectionProxyStub class which was returned to us in the “e.Result” variable. However, now we are working with the client side lightweight proxy class. The interesting thing about this approach is that we are NOT using the Visual Studio generated proxies. Our proxies are smart and maintain row state, and they are going to get even smarter. This approach makes EntitySpaces a terrific architecture for building your Silverlight applications. The SaveButton_Click is also incredibly simple. The timer stuff you see is just to make the fancy progress bar work in the demo.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
 
using EntitySpaces.SilverlightApplication.NorthwindClient;
using Proxies;
 
 
namespace EntitySpaces.SilverlightApplication
{
    public partial class Page : UserControl
    {
        private NorthwindClient.NorthwindClient service = new NorthwindClient.NorthwindClient();
        private Proxies.EmployeesCollectionProxyStub employees;
        private Storyboard Timer = new Storyboard();
        private int RecordsAdded;
 
 
        public Page()
        {
            InitializeComponent();
            Timer.Completed += new EventHandler(Timer_Completed);
            Timer.Duration = TimeSpan.FromMilliseconds(2);
        }
 
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Proxies.EmployeesQueryProxyStub q = new Proxies.EmployeesQueryProxyStub("emp");
 
                q.Select(q.EmployeeID, q.FirstName, q.LastName, q.HomePhone, q.HireDate, q.BirthDate, q.City);
                q.Where(
                    q.FirstName.Like("%" + SearchTextBox.Text + "%") |
                    q.LastName.Like("%" + SearchTextBox.Text + "%"));
                q.OrderBy(q.LastName.Ascending);
 
                service.GetEmployeesCompleted += new EventHandler<GetEmployeesCompletedEventArgs>(service_GetEmployeesCompleted);
                service.GetEmployeesAsync(Proxies.EmployeesQueryProxyStub.SerializeHelper.ToXml(q));
 
                WorkingBar.Value = 0;
                Timer.Begin();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.StackTrace);
            }
        }
 
        void service_GetEmployeesCompleted(object sender, GetEmployeesCompletedEventArgs e)
        {
            WorkingBar.Value = 100;
            Timer.Stop();
            
            if (e.Result != null)
            {
                employees = e.Result;
                EmployeesDataGrid.ItemsSource = employees.Collection;
            }
        }
 
        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            SearchTextBox.Text = "";
            employees = null;
            EmployeesDataGrid.ItemsSource = null;
        }
 
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (employees == null) return;
 
                WorkingBar.Value = 0;
                Timer.Begin();
 
                service.SaveEmployeesCompleted += new EventHandler<SaveEmployeesCompletedEventArgs>(service_SaveEmployeesCompleted);
                service.SaveEmployeesAsync(employees);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.StackTrace);
            }
        }
 
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (employees == null)
            {
                employees = new EmployeesCollectionProxyStub();
                EmployeesDataGrid.ItemsSource = employees.Collection;
            }
 
            if (RecordsAdded++ < 5)
            {
                EmployeesProxyStub newEmp = new EmployeesProxyStub();
                newEmp.FirstName = "Scott";
                newEmp.LastName = "Schecter";
 
                employees.Collection.Add(newEmp);
            }
        }
 
        void service_SaveEmployeesCompleted(object sender, SaveEmployeesCompletedEventArgs e)
        {
            try
            {
                WorkingBar.Value = 100;
                Timer.Stop();
 
                RecordsAdded = 0;
 
                employees = e.Result;
                EmployeesDataGrid.ItemsSource = employees.Collection;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.StackTrace);
            }
        }
 
        private void SearchTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (SearchTextBox.Text == "Enter Criteria Here")
            {
                SearchTextBox.Text = "";
            }
        }
 
        void Timer_Completed(object sender, EventArgs e)
        {
            WorkingBar.Value++;
            Timer.Begin();
 
            if (WorkingBar.Value > 100)
            {
                WorkingBar.Value = 1;
            }
        }
    }
}

Rather than repeat of bunch of content from previous posts, here are two posts that will help you further understand how we created the entire solution.

1) How we generated the lightweight client side proxies.

2) How we built the application and informed Visual Studio to use our proxies rather than generate proxies for us.

Be sure when you execute the “Generated Master” template to check the “Serializable Queries” checkbox on the advanced tab. Again, the demo is included in the latest alpha. We are even adding a new checkbox that will “scrunch” the XML when it goes over the wire so that your packets are much smaller. The XML will send all of your fields as “a1”, “a2”, “a3” and so on rather than “EmployeeID”, “FirstName”, “LastName”. This will make a big difference when sending large chunks of data from client to server and back again. Of course, we only send the columns that actually have data (non null/default) so your XML will be very tiny. This will not impact your proxies, they of course will still have your nice property names.

Well, that’s it for now. We are not only working on Silverlight and Proxies, we are also working through the Q3 Wish List as well.

EntitySpaces

From Mobile Devices to large scale enterprise solutions in need of serious transaction support, EntitySpaces can meet your needs. Whether you’re writing an ASP.NET application with Medium Trust requirements, a Silverlight application, a Mono application, or a Windows.Forms application, the EntitySpaces architecture is there for you. EntitySpaces is provider independent, which means that you can run the same binary code against any of the supported databases. EntitySpaces is available in both C# and VB.NET. EntitySpaces uses no reflection, no XML files, and sports a tiny foot print of less than 200k. Pound for pound, EntitySpaces is one tough, dependable .NET architecture.

EntitySpaces LLC
Persistence Layer and Business Objects for Microsoft .NET
http://www.entityspaces.net

Comments are closed.