Escolar Documentos
Profissional Documentos
Cultura Documentos
(29,268 online)
Sign in
Email Password Remember
me? Lost password?
Home
Articles
Chapters and Sections
Search
Latest Articles
Latest Tips/Tricks
Top Articles
Beginner Articles
Video Articles
Technical Blogs
Post an Article
Post Tip & Trick
Post your Blog
Posting/Update Guidelines
Article Competition
Questions & Answers
Ask a Question about this article
Quick Answers
Ask a Question
View Unanswered Questions
View All Questions...
C# questions
ASP.NET questions
VB.NET questions
C++ questions
C#3.0 questions
Programming Discussions
All Message Boards...
Application Lifecycle>
Design and Architecture
Running a Business
Sales / Marketing
Collaboration / Beta Testing
Work & Training Issues
ASP.NET
C / C++ / MFC>
ATL / WTL / STL
Managed C++/CLI
C#
Database
Hardware & Devices>
System Admin
Hosting and Servers
Java
.NET Framework
Mobile
Sharepoint
Silverlight / WPF
Visual Basic
Web Development>
CSS
Javascript
PHP
Site Bugs / Suggestions
Other Languages>
General Indian Topics
General Chinese Topics
Learning Zones
The Commerce Zone
The Mobile Zone
The Cloud Zone
The Hardware Zone
The Parallelism Zone
The WPF / Silverlight Zone
The SQL Zone
WhitePapers / Webcasts
Solutions Center
Features
Who's Who
CodeProject MVPs
Company Listings
Component & Service Catalog
Competitions
News
Daily Insider
Newsletter archive
Press Releases
Surveys
CodeProject Stuff
CodeProject VS Addin
Help!
What is 'The Code Project'?
General FAQ
Post a Question
Bugs and Suggestions
Site Directory
Advertise with us
About Us
The Lounge
o The Lounge
o Clever Code
o Hall of Shame
o The Soapbox
» Web Development » Silverlight » General
Licence CPOL
First Posted 11 Aug 2008
Views 138,078
Downloads 298
Bookmarked 296 times
Sponsored Links
Download source - 1.66 MB
Table of Contents
Introduction
What We Will Be Covering
Running the Sample Application
Beware ASP.NET Programmers
Why WCF, Can't I Access the DB directory?
Let's Start
Generating LINQ Classes
Creating a Silverlight WCF Service
Adding a Service Reference to the Silverlight Project
Creating the UI
o Adding the Assembly to Use a DataGrid Control
o UI Layout
o ListBox
o DataGrids
Writing Some Code
o Populating the ListBox
o Displaying the Orders of a Customer
o Displaying the Order Details when an Order is Selected
o Removing Some Auto-generated Columns from dgOrderDetails
Checkpoint Reached..Run the Project
Defining Columns
Second Run
Writing Data Back to the DB
Conclusion
History
Introduction
I started using Silverlight a few weeks ago, and it looks really amazing. Combining
the presentation powers of WPF with the strong capabilities of C#, Silverlight looks
very powerful. The main focus of this article will be to retrieve data from a database
and consume it in a Silverlight application. If you are an ASP.NET developer and
want to start exploring Silverlight, then perhaps this is the right place to start since
we will also be looking at similarities between Silverlight and ASP.NET.
We will be developing our first business application in Silverlight. Since almost every
business application has something to do with data and databases, we will be looking
at how data (from a database) can be displayed inside a Silverlight application.
Taking the Northwind database as an example, we will be generating some LINQ
classes, a WCF service for retrieving data, and finally, aListBox and
a DataGrid along with DataTemplates for data presentation. Our output will be a
fairly simple master-detail UI with customers, their orders, and order details. Note
that the source code of this article is written targeting Silverlight 2 RC1.
A small tweak is needed to run the sample project. By default, there will be no
startup project for the solution, so we must manually set DataApplication.Web as
the startup project by bringing up the properties window of the solution.
Beware ASP.NET Programmers
If you are an ASP.NET programmer, it may be important for you to note that the C#
code in the Silverlight project runs on the "client" and not on the server. Perhaps,
you can think of it as JavaScript. Thus, the good thing with Silverlight is that you
now have full control on the client side without knowing or writing any JavaScript (at
least, I am not good at writing JavaScript).
Well, the simple reason is that since the C# code runs on the client, our server
databases will not be accessible directly. Note that we do not have items
like DataSet or DataSource in a Silverlight project. The
namespace System.Data that contains our favorite classes is also absent. But, the
good thing is that there are other alternatives too, e.g., a WCF Service. This article is
going to demonstrate how to use a WCF service for data retrieval.
Let us Start
Now, we are about to add a service to our server project for retrieving data. Before
Silverlight 2 Beta 2, we needed some tweaks with the standard WCF service
template to use in a Silverlight project, but fortunately, Beta 2 and newer versions
give us the "Silverlight-Enabled WCF service" template that handles all things itself.
We are going to add a new Silverlight-enabled WCF Service named DataService to
our ASP.NET project.
We will write three methods in our service, one that returns all the customers, one
that returns orders of a customer, and finally, one that returns order details of a
particular order. Note that the methods must be marked with the
attribute[OperationContract] (this attribute is similar to
a [WebMethod] attribute for an ASMX service). Here is a quick implementation of
the data retrieval methods using very basic LINQ. Add the following to
the DataService.svc.cs file:
Collapse
[OperationContract]
public List<Customer> GetCustomers()
{
DataClasses1DataContext datacontext = new DataClasses1DataContext();
return datacontext.Customers.ToList();
}
[OperationContract]
public List<Order> GetOrders(string customerID)
{
DataClasses1DataContext datacontext = new DataClasses1DataContext();
return (from order in datacontext.Orders
where order.CustomerID == customerID
select order).ToList();
}
[OperationContract]
public List<Order_Detail> GetOrderDetails(int orderID)
{
DataClasses1DataContext datacontext = new DataClasses1DataContext();
return (from orderdetail in datacontext.Order_Details
where orderdetail.OrderID == orderID
select orderdetail).ToList();
}
That's all that was required on the server-side ASP.NET project. We have created
LINQ data classes to get data from the database and a WCF service to return those
LINQ objects. Now, we are ready to consume the service in our client-side Silverlight
project. For this, we need to add a service reference in
the DataApplication project. We can click Discover in the Add Service Reference
popup to have Visual Studio automatically find the newly created WCF service for us.
Creating the UI
We will display our data using the DataGrid control, but Silverlight does not include
a reference to the DataGrid control by default, so we need to add one. This process
is very similar to using a custom control in ASP.NET. Recall that we add a reference
to the appropriate DLL in the project and then add a register tag in the aspx page.
To achieve this in Silverlight, add a new reference (right click on References and
select New Reference) and locate System.Windows.Controls.Data in the list
(this is the assembly that contains the DataGrid).
After this reference is added, we need to assign a namespace to this assembly in our
XAML markup. To do this, add the following to the namespace declaration of the
file Page.Xaml.
Collapse
xmlns:data="clr-
namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
The Visual Studio IDE assists us here as the following screenshot shows:
UI Layout
Collapse
<UserControl xmlns:basics="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls"
x:Class="DataApplication.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data"
Width="Auto" Height="Auto">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="55" x:Name="HeaderRow" />
<RowDefinition Height="*" x:Name="ContentRow"/>
<RowDefinition Height="20" x:Name="FooterRow"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
AutoGeneratingColumn="dgOrderDetails_AutoGeneratingColumn">
</data:DataGrid>
</Grid>
</Grid>
</UserControl>
I will not be explaining the WPF layout in much detail in this article as there are a lot
of resources on The Code Project as well as outside; e.g., this one from Sacha
Barber. We will rather have a quick look on the markup for the ListBox and
the DataGrid.
ListBox
DataGrids
We want to load all the customers into the listbox lstCustomers, for which we are
using the Loaded event of the ListBox. Note that all service calls in Silverlight need
to be asynchronous, so we will register a callback function where we will bind the
incoming data to the ListBox. Notice how we use the txtStatus textbox (recall
we placed this in the bottom row ofLayoutGrid to provide updates to the user).
Collapse
private void lstCustomers_Loaded(object sender, RoutedEventArgs e)
{
DataServiceClient svc = new DataServiceClient();
this.txtStatus.Text = "Loading customers...";
svc.GetCustomersCompleted += new
EventHandler<GetCustomersCompletedEventArgs>(svc_GetCustomersCompleted);
svc.GetCustomersAsync();
}
void svc_GetCustomersCompleted(object sender, GetCustomersCompletedEventArgs e)
{
if (e.Error == null)
{
this.lstCustomers.ItemsSource = e.Result;
this.txtStatus.Text = string.Empty;
}
else
{
this.txtStatus.Text =
"Error occurred while loading customers from database";
}
}
Now, we will write some code to display the orders when a customer in the listbox is
selected. In the SelectionChanged event handler, we will call our WCF service and
bind the data to dgOrders when it is retrieved. This time, we will use anonymous
methods to be more compact.
Collapse
private void lstCustomers_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
Customer selectedCustomer = this.lstCustomers.SelectedItem as Customer;
if (selectedCustomer != null)
{
DataServiceClient svc = new DataServiceClient();
this.txtStatus.Text = "Loading orders...";
svc.GetOrdersCompleted +=
delegate(object eventSender, GetOrdersCompletedEventArgs eventArgs)
{
if (eventArgs.Error == null)
{
this.dgOrders.ItemsSource = eventArgs.Result;
this.txtStatus.Text = string.Empty;
}
else
{
this.txtStatus.Text =
"Error occurred while loading orders from database";
}
};
svc.GetOrdersAsync(selectedCustomer.CustomerID);
}
}
Collapse
private void dgOrderDetails_AutoGeneratingColumn(object sender,
DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column.Header.ToString() == "OrderID")
e.Column.Visibility = Visibility.Collapsed;
}
Now, our small application is ready to be viewed. Run it.. Select some customers,
view orders, edit the data displayed in theDataGrid, sort the DataGrid data by
clicking on the column headers, resize the DataGrid columns, resize the browser
window, do whatever else you want. Wasn't that cool? We will now have a look at
the DataGrid columns and templates.
Defining Columns
If you want to get more, Scott Morris has a nice blog entry on column types here.
So, let's use this knowledge in our application. For the sake of simplicity, we will
define only four columns: we will use aDataGridTextBoxColumn for
columns OrderID and EmployeeID. We will define
a DataGridTemplateColumn forOrderDate with a TextBlock in
its CellTemplate and a DatePicker control in its CellEditingTemplate.
Finally, we will define another TemplateColumn for Frieght. But, this time, we will
define two controls in its CellEditingTemplate: aSlider for
increasing/decreasing the Frieght value, and a TextBlock to show the current
value of the slider. Both these controls will be placed in a horizontal StackPanel as
we can only define a single item in a DataTemplate.
Collapse
<!-- DataGrid for displaying orders of a customer -->
<data:DataGrid x:Name="dgOrders" Grid.Row="0" Grid.Column="1"
AutoGenerateColumns="False"
SelectionChanged="dgOrders_SelectionChanged">
<data:DataGrid.Columns>
<!-- OrderID text column -->
<data:DataGridTextColumn Header="Order ID" Binding="{Binding OrderID}"
/>
Collapse
<ListBox x:Name="lstCustomer">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding NameProperty}"></TextBlock>
<Image Source="{Binding PictureProperty}"></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Note that the above code is just a sample. Since we do not have pictures in our
objects, we cannot use this snippet in our application.
Second Run
Well, this will be too much for this introductory article. But, if you have followed how
the WCF service is used to communicate between the client and the server, you can
easily write data back to the database by creating some functions in the service and
calling them from the Silverlight application. Notice that the data bindings in this
article are two way, that is, changing the value inside a DataGrid actually changes
the value in the bound DataContext item. We just need to send these updates to
our ASP.NET project using the WCF service and handle it there to update the
database. Ronnie Saurenmann presents a couple of videoshere. He uses
a DataSet like approach, keeping the modified and the original copies of data, and
then sending only the relevant records to the server using some helper classes. I
strongly recommend watching his videos.
Conclusion
That's all. I wrote this article to demonstrate how easy it is to build the foundation of
any data application. Let us revise what we learnt: we created a data access layer
using LINQ, and exposed it using a WCF service in our service side ASP.NET project.
We retrieved data using the service client in our Silverlight application, and finally,
used some data templates to have more control over data presentation. I hope this
article created some motivation to start building your future applications in
Silverlight. Happy Silverlighting...
History
License
This article, along with any associated source code and files, is licensed under The
Code Project Open License (CPOL)
Syed Mehroz Alam Syed Mehroz Alam, living in Karachi, Pakistan, is a developer
focusing Microsoft technologies. He has completed his
bachelors as a Computer Systems Engineer in 2006 and is
currently pursuing a Masters degree in Computer Science. He
loves to learn, discover and master all aspects of .NET and
SQL Server. Mehroz has developed rich internet enterprise
applications using Silverlight in addition to the traditional
ASP.NET and Windows Forms applications. He has worked
with all three components of SQL Business Intelligence Studio:
Software Developer
SSIS, SSRS and SSAS for developing BI Solutions and Data
warehouse. He loves to write complex TSQL queries and
Pakistan
evaluate his skills by participating in various TSQL Challenges.
Member His blog can be viewed athttp://smehrozalam.wordpress.com.
Article Top
Sign Up to vote for this article
FAQ
My vote of 5 ffsdf
Great Article. When r more Silverlight articles coming from u? sudipta.india
Re: Great Article. When r more Silverlight articles coming from u? Syed Mehroz Alam
Wow!! rasheed1979
Princess Grace
This article is great! awesome!
Dimaculangan
Last Visit: 6:09 24 Apr '11 Last Update: 23:20 24 Apr '11
General News Question Answer Joke Rant Admin
link | Privacy | Terms of Use | Mobile