The latest version of Silverlight has just been released by Microsoft. There
are a lot of new features in this new version for graphics manipulation, pixel
shader effects and 3D. However, one of the most exciting things in this release
is the built-in capability to create line of business applications much more
easily with a number of great features and a few new or enhanced controls.
Silverlight 3 finally gets to the point where it can actually go ahead and
replace traditional Web based LoB apps with a much smarter Rich Internet
Application (RIA). This new article series will show you how you can create a
database driven application in Silverlight 3 using different features and
controls. In this first part, we'll take a look at some of the controls
available in Silverlight 3 and how you can retrieve and update records in a
database.
Direct Hit! |
Applies To: Database developers USP: Create a database driven application using Silverlight 3 Primary Link: http://tinyurl.com/dcs3fj Keywords: Silverlight 3, WCF |
To go along with this article you will need the following installed on your
machine: Silverlight 3 RTW, Visual Studio 2008 SP1 or Visual Web Developer 2008
SP1, Silverlight 3 SDK and Silverlight 3 Controls Toolkit. You can find all of
these from the official Silverlight site at www.silverlight.net. Once all of
these have been installed, open up Visual Studio or Visual Web Developer, called
VS for both from now on. Create a new Silverlight Application project and when
prompted to create a web project, simply accept the defaults and go ahead. For
instance, in my case I created a Silverlight project named SL3DataSample and it
created a SL3DataSample.Web project along with it. Do remember that ASP.NET is
not required to host a Silverlight application. You can do it from any Web page
— HTML, PHP, Java or anything else. However, in our case, we will use the
ASP.NET project to provide a Windows Communication Foundation (WCF) endpoint to
allow data viewing and updating. You can also provide any type of SOAP endpoint
to get this working.
To work with a database, you can either connect to an existing database or
even more simply, if you have SQL Express installed on your machine, simply drop
an MDF file into the App_Data folder of the Web project. Either way, right click
the Web project and add a new Linq to SQL class and name it something similar to
the database. In my case, I used the NorthWind sample database and named the
Linq class as NW.DBML. Now go to the Database Explorer window and drop a table
in the designer pane. I dropped in the Suppliers table from NorthWind. Now comes
an important part. Select the designer pane and in the Properties window, set
the Serialization Mode= Unidirectional. This will allow the data to flow
automatically from the database to the client. Now again in the Web project, add
a new WCF Service item and call it DataService.svc. This will create the
following files: IDataService.cs, DataService.svc and DataService.svc.cs. First
open the IDataService.cs file and add the following by replacing the DoWork
function already present.
Silverlight Datagrid displaying data from the database through WCF. Note that the data is sorted on two columns. |
List
void SaveSupplier(Supplier s);
This creates two methods that make up the contract of the WCF service. Now
open the DataService.svc.cs file and select the iDataService definition and
“Implement Interface...” from the SmartTag menu. Once the method stubs appear you
can go ahead and create the following code:
public List
{
NWDataContext db = new NWDataContext();
var suppliers = from s in db.Suppliers
where s.CompanyName.Contains(Name) || s.ContactName.Contains(Name)select s;
return suppliers.ToList();
}
This method will now return a list of suppliers whose company name or contact
name contains the name searched for. The final step in the Web project is to
change the WCF binding. Search for the IDataService in the Web.config file and
change the binding value to basicHttpBinding to ensure SOAP binding for
Silverlight.
We can now finally go to the Silverlight project and start creating a UI to show
the data. For this, select the MainPage.xaml and drop in a DataGrid control from
the toolbox on the XAML page and add the x:Name=“dgData” attribute. Add a
Service Reference to the WCF and name it DataService. Open the code behind file
for the page and add the following code:
DataServiceClient ws;
public MainPage()
{
InitializeComponent();
ws = new DataServiceClient();
ws.GetSupplierByNameCompleted +=
new EventHandler
ws.GetSupplierByNameAsync("");
}
void ws_GetSupplierByNameCompleted(object sender,
GetSupplierByNameCompletedEventArgs e)
{
dgData.ItemsSource = e.Result;
}
Also add a using SL3DataSamples. DataService; to the top of the page. Run the
page to see the data returned and shown in the Silverlight 3 DataGrid control.
Note that you get a number of features out of the box-for instance sorting
multiple, rearranging the columns and even editing (although the data will not
be saved back to the server for now). Now let's also add some filtering
functions in by modifying the XAML file like this:
/>
Also add the event handler for the button code behind, like this:
private void btnFilter_Click(object sender,
RoutedEventArgs e)
{
ws.GetSupplierByNameAsync(txtNameFilter.Text);
}
Run the page to see full data. Enter some text in the text box and press the
button to filter data. Now we'll add a simple DataForm control to the page to
have master detail functionality and save data back to the server. Drop in a
DataForm from the toolbox just below the DataGrid and name it dfForm and set a
couple of other properties. Also add a SelectionChanged event to the DataGrid
like shown:
Add the following line to the ws_GetSupplierByName Completed Event:
dfForm.ItemsSource = e.Result;
And the following to the dgData_SelectionChanged event:
dfForm.CurrentIndex = dgData.SelectedIndex;
Run the app again to see the result. You can click on a row in the data grid
to see it reflected in the Dataform below. You can also navigate using the
navigation buttons and edit or add entries. To save the data back however, you
need to do two more changes. In the DataService.svc.cs add the following:
public void SaveSupplier(Supplier newSupp)
{NWDataContext db = new NWDataContext();
var q = from s in db.Suppliers
where s.SupplierID == newSupp.SupplierID
select s;
if (q.Count() == 0) // New Supplier - so Insert
db.Suppliers.InsertOnSubmit(newSupp);
else // Existing Supplier - so Modify {Supplier supp = q.First();
supp.SupplierID = newSupp.SupplierID;
supp.CompanyName = newSupp.CompanyName;
supp.ContactName = newSupp.ContactName;
supp.ContactTitle = newSupp.ContactTitle;
supp.Address = newSupp.Address;
supp.City = newSupp.City;
supp.Country = newSupp.Country;
supp.Fax = newSupp.Fax;
supp.HomePage = newSupp.HomePage;
supp.Phone = newSupp.Phone;
supp.PostalCode = newSupp.PostalCode;
supp.Region = newSupp.Region;
}
}
Modify the DataForm to add the properties: CommitButtonContent="Save Data"
EditEnding="dfForm_EditEnding". Also add the event handler as:
private void dfForm_EditEnding
(object sender, DataFormEditEnding EventArgs e)
{ if (e.EditAction == DataFormEditAction.Commit)
{ Supplier s = (Supplier)dfForm.CurrentItem;
ws.SaveSupplierCompleted += new EventHandler
ws.SaveSupplierAsync(s);
}
}
void ws_SaveSupplier Completed(object sender, System.ComponentModel.
AsyncCompletedEventArgs e)
{
MessageBox.Show("Saved Data");
}
Run this version and you will be able to use the DataForm to edit existing
data and add new records and save it back to the server as well! As you can see,
by using these controls you can easily start creating data driven pages.
In the coming issues, we'll see how you can make a scalable, n-tier based
Silverlight 3 line of business application and perform some advanced features
without writing much code.