LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Building a Silverlight 3 based RIA Image Management System - 1
by Xianzhong Zhu
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 41090/ 96


With the web development technology maturing, RIAs (Rich Internet Applications) are preferred to by more and more people. After many years of silence, under the situation that Flash nearly dominates the Internet world, Microsoft is unwilling to lag far behind, against many deficiencies of the rival and quickly developed a so-called "Flash killer" technology-- Silverlight.

In the four parts of articles, I’ll show you a basic RIA image management system based upon the popular Silverlight 3 technique, through which we are to explorer the typical routine and necessary skills in creating Silverlight based line-of-business applications.

We are going to, as far as possible, follow the development of software engineering to introduce aspects of the case in this chapter. However, since this case still remains at a level on a simplified version, so for some modules, such as needs analysis and so on, will be simplified or be omitted.

System Functionalities and Architecture

First of all, what needs to be made clear is that the system is the embryonic form of an extremely complex RIA image management system. Flickr is the famous one-line image management software, under the banner of the "Photo Sharing". Of course, their data, and the strong popularity are hard to catch up with to many similar sites. However, I highly recommend interested readers put this chapter in a similar case to study it, and if so, I believe you will have more gains.

System Functionality Module

The online image management system in this article will achieve the following modules:

·         Image Category Management

·         Picture data preview and upload

·         Picture data download and browsing

·         Image Browsing

To simplify the description of the problem, the following diagrams are given to illustrate the functional modules to be achieved in our case.

Figure 1Image category management module

Figure 2Image upload module

Figure 3Image download module

Figure 4Picture browsing module

Next, we are to discuss the system architecture design.

Architecture Design

This image management system uses a typical three-tier.

Figure 5 demonstrates the schematic of different layers of the sample in this article, as well as summarizes the important characteristics of the sample programs.

Figure 5the N-tier structure used in this case

Overall, the case structure of this article has the following important features:

·         SQL SERVER 2008 is used as the server-side data storage.

·         The up-to-date ADO.NET data services technology serves as the data access layer, which will greatly simplify the data access layer design in the Silverlight application, thus enabling developers to focus on the XAML presentation layer and business logic modules.

·         The business logic tier is relatively simple, only corresponding to some business logic tool classes.

·         User interface layer (presentation layer) is mainly composed of XAML-formed Silverlight user controls embedded inside the ASP.NET page. In the XAML page design, the popular data source binding is utilized. Furthermore, in order to reduce as much as possible the coupling of the presentation layer and the business logic tier, we avoid directly using the XAML markup attribute attaching different events to the related handlers, but choose to use the code-behind class to achieve the attachments, which can be easily accomplished through the "+ =" operator and the event delegate provided in C # language.

Figure 6 below gives the general document layout in this sample solution of this article. In fact, this layout is also, in a certain sense, reflects the structure of the entire system.

Figure 6the file layout in the sample solution

With the above goals in mind, now let's shift our attention to the database design.

Database Design

As a simplified version of the online image management system, it does not involve too much data; including categories associated with the image data, as well as the specific image file related attribute data. Based on the two kinds of data, we merely need to design two proper tables, and to determine the relationship between them.

Table Structure

First, we are to list the structures of the two tables--Category and Photo and interpretation of the relevant fields in table forms.

Table 1. Structure for table Category.

Field name





Primary Key



The photo category name



The status of an image category, and used to indicate whether this type of image files are public or not. Note, however, we do not use this field much. I.e., we've just used it in general record operations (such as edit, insert, delete, etc.).


Table 2. Structure for table Photo.

Field name





Primary Key



The title to show in the photo album (usually refers to the name)



The complete path of the image file



The date time to upload the file



Specify the type of the file



The size of the image file (bytes)



Foreign key (relating to field ID of table Category)


Next, let's take a look at the relationships between the above two tables.

Table Relationship

Figure 7 gives the relationships between the above two tables Category and Photo. It is clear that between the two is a one-to-many relationship. The snapshot here is derived from the entity data model document PhotoAlbumModel.edmx. Note that, following the end of each of the two entities has a corresponding navigation attribute. Although the navigation attribute is a unique concept provided by ADO.NET data services, which allows using ADO.NET data services to handling master-detail tables and their association relationships, which seems quite different from other forms of data access solutions, but, in fact, it quite resemble the operations with master-detail tables provided by them. Fore further discussion of the navigation attributes, please refer to MSDN, combined with the later modules.

Figure 7-- the one-to-many relationship between table Category and Photo.

As the above image indicates, in the later on module design, we must bear in mind one thing: No matter what kind of data manipulation, we must ensure the association relationship established here is correct to ensure the consistency and effectiveness of cited data.

ADO.NET Data Service Based Database Access

Before delving into the ADO.NET Data Service, let's sum up the typical data access solutions used in Silverlight applications.

Overview of Silverlight Data Access Technology

Experienced ASP.NET developers know, with the use of data access, they can write corresponding logics so that application can connect to various external data sources and further query and process data. With sophisticated data access provided by ASP.NET, developers can quickly accomplish the realization of the above process, almost without writing any code. The reason is that, ASP.NET operating environment is a complete installation of .NET framework, so ASP.NET can invoke ADO.NET to access the database, and then the results are transformed into HTML to be sent to the client.

But, for Silverlight applications, the same problem is not so simple. Because the Silverlight plug-in runs on the client browser, the corresponding micro .NET Framework is not possible to contain huge ADO.NET components. Aiming at this particular structure of Silverlight applications, the realization of Microsoft's technology is first to submit HTTP requests to the server to let the server carry out the task of data access, and then the results are sent back to the client in accordance with the format of the two sides agreed to. Thus, developers can use any SOAP-based technologies or WCF service to obtain data. Once the data are returned to the client, you can process them by calling the corresponding data components.

In summary, Silverlight applications can use the following three typical techniques for data access:

·         Traditional Web Service to access server-side database.

·         Using WCF service shipped with.NET 3.0 framework to access the server database.

·         Through the up-to-date and the most closely Silverlight bound technology--ADO.NET data service, to access the server-side database.

For Web service and WCF solution, readers may refer to the relevant information in MSDN. The sample in this article only shows interest in ADO.NET data service technology. Let's next start the more detailed discussion.

ADO.NET Data Services Technology

ADO.NET Entity Framework is Microsoft's next generation of ADO.NET. This framework, in fact, is not a brand-new and independent infrastructure. It is only another new choice based upon the traditional ADO.NET framework.

On the whole, ADO.NET Entity Framework has the following characteristics:

·         Entity data model that allows of high abstraction for data modeling.

·         Powerful mapping engine that allows developers to easily set up the mapping between the data model and data storage definition.

·         Supporting the use of entity SQL syntax and LINQ to query the definition of EDM data.

·         Object services layer that allows you to choose whether or not to present the results of a query as the row/column records or .NET objects.

·         Opening data provider model, allowing other storage mechanisms to be combined with ADO.NET Entity Framework.

For a simple schematic diagram of the ADO.NET Entity Framework, you can refer to here.

Use ADO.NET Data Services to Access the Server-side Image Data

Next, we are going to give details in the image management system, on how to use ADO.NET data services to access the image data on the server side.

(A) Implement Data Model

1. Right-click the ASP.NET Web Site project in Solution Explorer, point to Add, and then select New Item.

2. In the Add New Item dialog box, select ADO.NET Entity Data Model. Name the data model PhotoAlbumModel.edmx, and then click Add.

3. In the Entity Data Model Wizard, select Generate from Database, and then click Next.

4. In the Generate from Database dialog box, create a connection to the AjaxAlbumDB database. Notice that the entity connection settings that are shown will be added to the Web.config file of the application. The connection will be named AjaxAlbumDBEntities. The data service requires this connection but the Silverlight client will not use it. Click Next.

5. In the Choose Database Objects dialog box, select the two tables Category and Photo in the AjaxAlbumDB database. Then name the model namespace PhotoAlbumModel and click Finish.

This finishes the AjaxAlbumDB data model implementation and opens the Entity Data Model Designer. In the designer, we touch nothing. So you can see an association relationship diagram between two tables Category and Photo, as shown in Figure 7 given previously.

(B) Implement Data Service

1. Right-click the ASP.NET Web application project in Solution Explorer, point to Add, and then select New Item.

2. In the Add New Item dialog box, select ADO.NET Data Service. For this sample app, name the service PhotoAlbumDataService.svc, and then click Add. This adds the data service template that contains the required reference to the System.Data.Services library.

3. Visual Studio will open a file named PhotoAlbumDataService.cs that contains the source code that initializes the ADO.NET data service. The type of the template class identifies the data model. Set the type in the DataService declaration to AjaxAlbumDBEntities, as shown in the following example. As you see, the data service class is derived from System.Data.Services.DataService<T>.

4. Modify the config.SetEntitySetAccessRule method as shown in the following code. Authorization to read and write all data is defined by the call to config.SetEntitySetAccessRule("*", EntitySetRights.All). The asterisk applies the rule to all data sets in the data model.

5. Also, we modify the config. SetServiceOperationAccessRule method to grant all access rights in service operations.

Listing 1-- Initialize ADO.NET Data Service

public class PhotoAlbumDataService : DataService<AjaxAlbumDBModel.AjaxAlbumDBEntities>
    //Initialize Service
    public static void InitializeService(IDataServiceConfiguration config)
        //Authorization to read and write all data 
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        //Service operations access configuration
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);

(C) Generating Data Service Client Library

This step will generate data service classes from the running data service. Note these classes represent each of the entities that are defined in the data service.

To do this, please first make sure the data service is running. Then, right-click the Silverlight project and select Add Service Reference. In the Add Service Reference dialog box, we just let Visual Studio discover the base URL of the data service, since the service and Silverlight project are in the same solution. If you click OK, Visual Studio goes and generates all the client side classes for you, adds the related references, and you can start using the service right away.

In our case, such as in the MainPage.xaml.cs, add the following using directive: using System.Data.Services.Client.

Since everything gets ready, let's come to the final phase--implementing the data access on the client side.

(D) Data Client Implementation

1. Open the *.xaml.cs source code files that will access ADO.NET Data Service in the Silverlight project.

2. Add a using directive to System.Data.Services.Client.

3. Add using directives to the PhotoServiceReference Service classes that are generated by Add Service Reference or DataSvcUtil.exe. The generated classes make it possible for the client application to materialize the data that is received from the data service.

Listing 2-- Add necessary using directives

using System.Collections.ObjectModel;
using System.Data.Services.Client;
using ADONET = S2PhotoAlbum.PhotoServiceReference;

4. Create an instance of the data service context of the PhotoServiceReference data service. Then by invoking the relevant methods (such as BeginExecute<(Of <(TElement>)>)(Uri, AsyncCallback, Object)), you can implement your client-side data access.

Listing 3-- Instantiate the proxy DataServiceContext

namespace S2PhotoAlbum
    public partial class MainPage : UserControl
         //Define a variable of DataServiceContext proxy
        ADONET.AjaxAlbumDBEntities proxy;
        public MainPage()
            //others omitted…
            //Define the instantiation of proxy DataServiceContext
            proxy = new ADONET.AjaxAlbumDBEntities(new 
                  Uri("PhotoAlbumDataService.svc", UriKind.Relative));

For details in using the instantiation of proxy DataServiceContext to implement the typical CRUD operations, please refer to the later on modules.

In the next section, we are to preview the main finished line of the RIA image management system, and then set out to develop the first module of the sample system.

System Preview and Homepage Module

In this section, you will preview the main system interfaces so as to have a general understanding of the system.

System Preview

Figure 8 shows the main interface of the system. On this page, in addition to tell about the developing techniques and operational environment, the system also gave a brief description of the overall function. Finally, clicking the hyperlink at the bottom right corner of the page will start up your browser and navigate you to the author's blog page.

Figure 8-- the main interface of the system

Figure 9 shows the run-time screenshots of the image category management module. Through this page, you can browse, add, edit, and delete picture category data, as well as query your interested ones by specifying the picture category name in the Textbox control. This page represents the typical programming module that is associated with the backend data access techniques. Through this module, you can learn how to create data centric solutions under the Silverlight programming environment.

Figure 9-- the CRUD implementation of image category data

Figure 10 shows the run-time screenshot relating to upload and download image files, which is one of the most used parts in typical online image management systems. Note here, taking into account the system performance requirements, we've used the Silverlight-specific memory management technology, i.e. Isolated Storage, in the realization of this module.

Figure 10-- Upload and download snapshot

Image browser module is the most complex subsystem module, which is also a necessary part of any online image system. With the traditional image browsing techniques, through the use of multi-reference version of Silverlight technology, two-dimensional graphics and animation technology can be a very flexible way of browsing image data to display. Figure 11 gives the related snapshot, where you can click the thumbnail in the navigator bar to jump to appreciate your target image.

Figure 11-- Click the bottom thumbnail image to view it in the full-screen mode (non clicking happens now)

Nearly with all the necessary information in our mind, in the next section, we start to roll our sleeves to construct the application module by module.

Create the Sample Solution

Start Visual Studio 2008, open the "File" menu, and from the pop-up "New" sub-menu select "Project" option, then the "New Project" dialog box will appear. In the dialog box, select the template namely "Silverlight Application", enter the application name "S2PhotoAlbum", and click "OK" button.

As soon as you close the above dialog box, another dialog box "Add Silverlight Application" will appear before you. Here we select "ASP.NET Web Site" as the host project type.

From the beginning of the next section, we are going to create XAML pages and write the related background C# code.

Home and Welcome Page module

To simplify the problem and due to the time constraint, the image management system does not add a user registration and login module. Therefore, as soon as the system is activated, you can see the system's home page and welcome page module and directly use all the functionalities provided in the system. The home page and welcome page in the module are implemented through two Silverlight user controls, i.e. MainPage.xaml and Welcome.xaml.

(1) XAML Markup Code Page Design

First, we will explorer the layout design of the main page-- MainPage.xaml. Figure 12 gives the related snapshot (in Microsoft Expression Blend 3) for page MainPage.xaml.

Figure 12-- the design time snapshot of page MainPage.xaml

In this sample application, we simply use a few custom buttons on the left side of the page as navigation toolbar. The header at the top just shows a logo image, while the footer lies at the bottom line, and the most part on the right corresponds to a large and empty Grid control, used as a container control of the sub XAML pages (Silverlight controls).

Now, let's look at the related XAML markup code for page MainPage.xaml.

Listing 4-- the main XAML markup code for page MainPage.xaml

<!--Main Canvas-->
<Grid x:Name="_rootMain">
    <StackPanel x:Name="LayoutRoot" Orientation="Vertical" HorizontalAlignment="Center">
        <StackPanel x:Name="logoContainer" Height="100" Width="800" 
            Background="#FF423442" HorizontalAlignment="Center" >
            <Image Source="images/logo.jpg"></Image>
        <Grid x:Name="gridBody" Background="#FF574C5B" Height="450" 
                <RowDefinition />
                <ColumnDefinition Width="165" />
                <ColumnDefinition  Width="2" />
                <ColumnDefinition  Width="615" />
            <ListBox  x:Name="listCatalog" Margin="2,2,2,2"  Grid.Row="0" 
            Grid.Column="0" Background="#FF5C4141" Width="160" 
            HorizontalAlignment="Left" >
                <Button Height="32"  Width="130" x:Name="btnHome" Content="Home" 
                  Style="{StaticResource NewButtonTemplate}" FontSize="10.667" 
                  Background="#FFFFFFFF" Foreground="#FF06A500"/>
                <Button Height="32"  Width="130" x:Name="btnCata" 
                  Content="Category Management" 
                  Style="{StaticResource NewButtonTemplate}" 
                  FontSize="10.667" Foreground="#FF06A500"/>
                <Button Height="32" Width="130" x:Name="btnDownUp"  
                  Content="Upload &amp; Download"  
                  Style="{StaticResource NewButtonTemplate}" FontSize="10.667" 
                <Button Height="32"   Width="130" x:Name="btnBrow_Select" 
                  Content="Select Category"  
                  Style="{StaticResource NewButtonTemplate}" FontSize="10.667" 
                <Button Height="32"   Width="130" x:Name="btnBrow" 
                  Content="Image Browser"  
                  Style="{StaticResource NewButtonTemplate}" FontSize="10.667" 
                          Content="FullScreen/Window Switch"
                          Style="{StaticResource ToggleButtonStyle}" 
                         Visibility="Visible" Foreground="#FF00CBFF" />
            <basics:GridSplitter Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" 
            BorderThickness="1" BorderBrush="Blue" HorizontalAlignment="Stretch" 
            <Grid x:Name="gridRight"  Grid.Row="0" Grid.Column="2"  
                  Background="#FF5C4141"  Margin="2,2,2,2"  >
        <Canvas x:Name="footer" Height="50" Width="800" Background="#FF4C4C4C">
            <TextBlock Width="246.5" Text="By Xianzhong (WeiFang China) "  
                  FontSize="20" Foreground="#FF00FB75" 
                  HorizontalAlignment="Center" Height="32" 
                  Canvas.Top="18.909" Canvas.Left="288"/>
            <HyperlinkButton Style="{StaticResource CustHyperlink}" 
                  Content="HyperlinkButton" Height="51" TargetName="Contace me" 
                  FontSize="20" Width="144" HorizontalAlignment="Right" 
                  Foreground="#FF46FF00" Canvas.Left="648" VerticalAlignment="Top" 
                  Margin="0,0,0,0" Canvas.Top="5"/>

As is seen, the page itself is a user control (UserControl), at the top of which is a StackPanel control which contains an Image control. The Listbox control at the left side contains several Button controls used as the navigator bar. The footer part uses a Canvas control as the layout container.

Another thing to take notice of is that the above hyperlink control, button controls, full-screen/window switch control are all defined in the main application App.xaml within the Resources property. For more details about the Resources property in Silverlight apps, again please refer to MSDN.

Next, we will discuss the relevant background related programming.

(2) Background Code Design

Due to space limitations, we still will not give detailed explanation of all the code, but to focus on clarifying the whole process and crucial skills in Silverlight programming (for the other modules in this article are also the case).

In this section, we plan to explain the following three questions:

·         Sub .xaml pages switching principle inside a parent container control

·         Full-screen and window mode switching principle

·         Several .xaml pages switching principle

(a) Sub .Xaml Pages Switching Principle

When you are running the sample app you may notice that when you click the button controls on the left side a corresponding sub .xaml control will be loaded into the Grid control on the right side of the page and display the related contents. How to achieve this target?

In fact, the sub .xaml controls switching principle here is very simple. As is known, each page is a UserControl control in essence. So we can search through the control levels to find out the Grid control named gridRight. First, we can empty subset of its original control set, and then by invoking the Add() method we can fill the subset of control gridRight with our favorite .xaml control.

For example, the following code achieved the result to load the upload/download XAML page into the parent control gridRight.

Listing 5-- clear original sub controls and replace with new target .xaml control

void btnDownUp_Click(object sender, RoutedEventArgs e)
    gridRight.Children.Clear();//clear original sub controls
    //load current XAML control
    gridRight.Children.Add(new S2PhotoAlbum.XAMLs.UploadDownload());

(b) Full-Screen and Window Mode Switching Principle

Similar to other applications, in Silverlight applications, it is commonly required to provide the functionality to switch between the full-screen mode and window mode. In the Silverlight application, how to achieve it?

The principle here is still simple. We can resort to control ToggleButton which is defined in the namespace System.Windows.Controls.Primitives to meet our request.

As the parent control of controls CheckBox and RadioButton, ToggleButton provide the functionality to switch between two-state and three-state.

First of all, in the constructor of page MainPage, we create the following code:

Listing 6-- initialization for full-screen and window state switching related stuff

public Page()
//(others omitted)
    //specify the button Click event handler
    FullScreenButton.Click += new RoutedEventHandler(OnToggleFullScreen);
    //also setup the FullScreenChanged event handler
    if (Application.Current != null)
        Application.Current.Host.Content.FullScreenChanged += OnFullScreenChanged;
//(others omitted)

The following code corresponds to the above two event handlers.

Listing 7

// switch between the full-screen and window mode
private void OnToggleFullScreen(object sender, RoutedEventArgs e)
    Application.Current.Host.Content.IsFullScreen = 
// the FullScreenChanged event handler
private void OnFullScreenChanged(object sender, EventArgs e)
    //if app quits full-screen mode, then cancel checking button ToggleButton
    if (!Application.Current.Host.Content.IsFullScreen && 
      FullScreenButton != null)
        FullScreenButton.IsChecked = false;

Finally, let's pay special attention to the whole .xaml pages switching technique.

(c) Several .Xaml Pages Switching Principle

Our target here is that the current screen is one XAML page, and it should be replaced by another XAML page. How to achieve it?

When the user clicks on the "Image Browser" button, page MainPage.xaml should be turned into another XAML page--PhotoViewer.xaml which does not serves as a part of Page.xaml page like the a case discussed above.

Since currently Silverlight did not provide a similar mechanism to meet our request, we need to do it by ourselves referring to the case a solution used above and further generalize it. What we need to do is monitor the process of page switching. In this end, we designed three relevant classes to complete the above task:

·         TransitionCompletedEventArgs: responsible for monitoring the events of switching between the two old and new XAML controls.

·         TransitionBase: an abstract base class to take charge of XAML controls transition, whose derivation classes, such as FadeTransition, RotateTransition, WipeTransition and CompositeTransition) are able to finish the actual task of the old and new XAML pages transition (or switch) through class TransitionCompletedEventArgs.

·         NavigationHelper: a helper class, with the help of the above two classes, further encapsulates (or simplifies) switching manipulation between XAML pages.

Due to limited space, we are only going to discuss the realization of class NavigationHelper and detailed notes.

Listing 8-- source code for class NavigationHelper

public static class NavigationHelper
///variable root represents the root element of the XAML file
private static Grid root;
///assign value to variable root
///(here refer to the Grid control, which maybe varies in other cases)
static NavigationHelper()
    root = Application.Current.RootVisual as Grid;
///using specified dynamic transition effect achieve the target of switching 
///between the old and the new XAML controls 
public static void Navigate(TransitionBase transition, UserControl newPage)
    UserControl oldPage = root.Children[0] as UserControl;
    root.Children.Insert(0, newPage);
    transition.TransitionCompleted += transition_TransitionCompleted;
    transition.PerformTranstition(newPage, oldPage);
///make direct replacement (this simple case of above)
public static void Navigate(UserControl newPage)
    UserControl oldPage = root.Children[0] as UserControl;
///when the transition completes, the following event is triggered, where the old XAML is removed
private static void transition_TransitionCompleted(object sender, TransitionCompletedEventArgs e)

Finally, we take a look at how to use the above-mentioned classes to navigate the application pages.

Listing 9

void btnBrow_Click(object sender, RoutedEventArgs e)
    TransitionBase transition = new CompositeTransition(
        new FadeTransition(TimeSpan.FromSeconds(1)),
        new RotateTransition());
    NavigationHelper.Navigate(transition, new S2PhotoAlbum.XAMLs.PhotoViewer());

It is clear that the first line of code specifies the effect of dynamic transition, and using the static method Navigate of the helper class NavigationHelper to switch to the current page PhotoViewer using the specified transition effect.

In the last section, let's say a few words about the welcome page.

Welcome Page Design

As shown in Figure 8 given above, when the system successfully starts up, what appears before you is a simple system development introduction page. This page is named Welcome.xaml, which is loaded into page MainPage.xaml at the very beginning of the app is launched.

This welcome page is really simple and no more explanations shall be repeated.


In this first part of the long article, we described the fundamental works in constructing a Silverlight 3 based RIA Image Management System, as well as examined the first module-- the main page related programming. In subsequent parts we will continue to explore other modules.

©Copyright 1998-2020  |  Page Processed at 2020-07-05 4:32:35 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search