Getting Started with Adobe After Effects - Part 6: Motion Blur


Upload Image Close it
Select File

Dinesh's Blog
Browse by Tags · View All
brh 20
#SILVERLIGHT 19
#DOTNET 18
silverlight 18
#ASP.NET 15
Silverlight 4.0 9
bing 7
bing maps 6
wcf services 5
map 5

Archive · View All
August 2010 10
September 2010 3
July 2010 3
June 2010 3
October 2010 1

Getting Started with WCF RIA Services

Oct 2 2010 7:00AM by Dinesh Sodani   

In the previous article I showed different methods to bind Silverlight data grid like binding with Collection object, binding with XML, binding with WCF Data Services. In this article I will demonstrate how to bind the bind the data grid with WCF RIA Services…

WCF Services

.NET offers several different flavors of WCF services that you can choose from based on your particular needs. See the image below…

Windows Communication Foundation

  1. WCF Core Services – Allows full flexibility for building operation-centric services.  This includes industry standard interop, as well as channel and host plug-ability.  Use this for operation-based services which need to do things such as interop with Java, be consumed by multiple clients, flow transactions, use message based security, perform advanced messaging patterns like duplex, use transports or channels in addition to HTTP, or host in processes outside of IIS.
  2. WCF WebHttp/AJAX Services – Is best when you are exposing operation-centric HTTP services to be deployed at web scale or are building a RESTful service and want full control over the URI/format/protocol.
  3. WCF Data Services – Including a rich implementation of OData for .NET, Data Services are best when you are exposing your data model and associated logic through a RESTful interface
  4. WCF Workflow Services – Is best for long running, durable operations or where the specification and enforcement of operation sequencing is important
  5. WCF RIA Services – is best for building an end-to-end Silverlight application

What is RIA?

A Rich Internet Application (RIA) is a Web application designed to deliver the same features and functions normally associated with desktop applications. RIAs generally split the processing across the Internet/network divide by locating the user interface and related activity and capability on the client side, and the data manipulation and operation on the application server side. An RIA normally runs inside a Web browser and usually does not require software installation on the client side to work.

What is WCF RIA Services?

WCF RIA Services simplifies the development of n-tier solutions for Rich Internet Applications (RIA), such as Silverlight applications.WCF RIA Services lets you quickly build N-Tier Silverlight client applications without needing to focus on the service plumbing to get data into and out of your client application from back-end services, logic and data access. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

IC357993

Why WCF RIA Services Needed?

A common problem when developing an n-tier RIA solution is coordinating application logic between the middle tier and the presentation tier. To create the best user experience, you want your RIA client to be aware of the application logic that resides on the server, but you do not want to develop and maintain the application logic on both the presentation tier and the middle tier. RIA Services solves this problem by providing framework components, tools, and services that make the application logic on the server available to the RIA client without requiring you to manually duplicate that programming logic. You can create a RIA client that is aware of business rules and know that the client is automatically updated with latest middle tier logic every time that the solution is re-compiled.

Getting Started

To get started with creating the WCF RIA Services Application you need to install Silverlight 4 Tools for Visual Studio 2010, which installs WCF RIA Services support as well. Let’s create a new Silverlight project in VS2010 named DemoRIAServices.

Create Silverlight Project in VS2010

After you click OK in the new project window, a normal dialog will appear to create a hosting web application project. In that dialog box there is a new a checkbox at the bottom to Enable WCF RIA Services. When this check box is checked it’s create a link between the client project and the server project so that WCF RIA Services can generate the appropriate client code based on the domain services and entities you will create.

VS2010 Enable WCF RIA Services

Database Setup

Let’s create a database called “DataBinding” and create a table called “tblItem” as following:

CREATE TABLE [dbo].[tblItem](
	[ItemNumber] INT NOT NULL,
	[ItemDescription] [varchar](50) NULL,
	[Quantity] [int] NULL
CONSTRAINT [PK_tblItem] PRIMARY KEY CLUSTERED 
(
	[ItemNumber] ASC )
)

Let’s insert a new records in the table

INSERT INTO [tblItem]
           ([ItemNumber]
           ,[ItemDescription]
           ,[Quantity])
VALUES ('1','Item Name1',1),
       ('2','Item Name2',2),
       ('3','Item Name3',3),              
       ('4','Item Name4',4),
       ('5','Item Name5',5),
       ('6','Item Name6',6)

Create Domain Modal Entities

There are number of options to connect with database like Entity Framework, LINQ to SQL… we will use Entity Framework. Let’s create a Entity Modal. Right click on the DemoRIASerices.Web server project and select ADD > New Item. Pick the Data category on the left, and select ADO.NET Entity Data Model and name it TasksModel.edmx.

ADO.NET Entity Data Model

Click Add and you will see the Entity Data Model Wizard. In the first step, leave the option to Generate from database selected and click Next. Create a New Connection in the next step to the DataBinding database you created.

Entity Data Model Wizards - Create New Database Connection Entity Data Model Wizards - Choose Data Connection

See the connection name is DataBindingEntites. The checkbox selected will the connection string in the web config file. In the next step, Choose Your Database Objects, check the box for Tables to select all the tables and click Finish.

Entity Data Model Wizards - Choose Database Object

Build the solution to make sure all is well. If you forget to build after adding your entity data model, it will not show up when creating the domain service in the next step.

Defining Domain Service

Domain services are WCF services that encapsulate the business logic of an application. A domain service exposes data entities and operations in the server project to the client project in the form of a service layer. When you define a domain service, you specify the data operations that are permitted through the domain service.

Right click on the TaskManager.Web project and select Add > New Item. Select the Web category, and select Domain Service Class. Name the class ItemService.

Create Domain Serivce

When you click Add a new dialog will appear which lets you select a number of option for your service including the most important option of what entities it will expose.

Domain Service - New Domain Service Class

A couple of things to notice here…

  1. DataBindingEntities (Entity Frameworks) is selected in Available DataContext/ObjectContext Classes. If you do not want to use Entity Framework for your database operation you can select “<empty domain service class>”. In that case you need to define your classes and methods.
  2. tblItem entity is selected
  3. Check box of Enable editing is selected which create database manipulation methods for tblItem entity.

When you click OK the Domain Service Class will be created. You can see following two files are added to your TaskManager.Web project.

ItemService.cs

namespace DemoRIASerices.Web
{
    [EnableClientAccess()]
    public class ItemService : LinqToEntitiesDomainService<DataBindingEntities>
    {
        public IQueryable<tblItem> GetTblItems()
        {
            return this.ObjectContext.tblItems;
        }
        public void InsertTblItem(tblItem tblItem)
        {
            if ((tblItem.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(tblItem, EntityState.Added);
            }
            else
            {
                this.ObjectContext.tblItems.AddObject(tblItem);
            }
        }
        public void UpdateTblItem(tblItem currenttblItem)
        {
            this.ObjectContext.tblItems.AttachAsModified(currenttblItem, this.ChangeSet.GetOriginal(currenttblItem));
        }
        public void DeleteTblItem(tblItem tblItem)
        {
            if ((tblItem.EntityState == EntityState.Detached))
            {
                this.ObjectContext.tblItems.Attach(tblItem);
            }
            this.ObjectContext.tblItems.DeleteObject(tblItem);
        }
    }
}

ItemService.metadata.cs

namespace DemoRIASerices.Web
{
    [MetadataTypeAttribute(typeof(tblItem.tblItemMetadata))]
    public partial class tblItem
    {
        internal sealed class tblItemMetadata
        {
            private tblItemMetadata()
            {
            }
            public string ItemDescription { get; set; }

            public int ItemNumber { get; set; }

            public Nullable<int> Quantity { get; set; }
        }
    }
}

Rebuild the solution to make sure all is well and to generate the client side code. If you Show All Files in the DemoRIASerices project, you will see a Generated_Code folder with a DemoRIASerices.Web.g.cs file in it. This contains the generated code. See the image below.

Load Data at Client - DomainDataSource Method

WCF RIA Service provides drap and drop method to display the data of the entity in the Silverlight page. Open MainPage.xaml in the designer. Open the Data Sources window (Data menu > Show Data Sources). It will take a moment the first time you open it after the client code generation. But it will show the entities for the types returned by the domain service listed in the Data Sources window.

Domain Context

Now drag and drop the entity tblItem of ItemContext from the Datasource widnow to Mainpage.xaml page. A DataGrid will be generated with appropriate columns for each of the properties on the entity type, and a DomainDataSource will also be declared and hooked up to the GetTblItems method on the ItemContext class. Your MainPage.Xaml page will be as following:

<UserControl x:Class="DemoRIASerices.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" 
    xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices"
    xmlns:my="clr-namespace:DemoRIASerices.Web"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <riaControls:DomainDataSource AutoLoad="True"  
               d:DesignData="{d:DesignInstance my:tblItem, CreateList=true}" 
               Height="0" LoadedData="tblItemDomainDataSource_LoadedData" 
               Name="tblItemDomainDataSource" QueryName="GetTblItemsQuery"
               Width="0">
            <riaControls:DomainDataSource.DomainContext>
                <my:ItemContext />
            </riaControls:DomainDataSource.DomainContext>
        </riaControls:DomainDataSource>
        <sdk:DataGrid AutoGenerateColumns="False" Height="206" HorizontalAlignment="Left"
        ItemsSource="{Binding ElementName=tblItemDomainDataSource, Path=Data}" 
        Margin="12,37,0,0" Name="tblItemDataGrid" 
        RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" 
        Width="348">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn x:Name="itemDescriptionColumn" 
                    Binding="{Binding Path=ItemDescription}" Header="Item Description" 
                    Width="SizeToHeader" />
                <sdk:DataGridTextColumn x:Name="itemNumberColumn" 
                    Binding="{Binding Path=ItemNumber, Mode=OneWay}" Header="ItemNumber"
                    IsReadOnly="True" Width="SizeToHeader" />
                <sdk:DataGridTextColumn x:Name="quantityColumn" 
                    Binding="{Binding Path=Quantity}" Header="Quantity" 
                    Width="SizeToHeader" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </Grid>
</UserControl>

Build and run the application. You should see something like the following.

WCF RIA Service - Output

Load Data at Client  - EntityQuery & LoadOperation Method

The above method binds the data grid on page load. To bind the data grid with EntityQuery & LoadOperation Method make the AutoLoad property of DomainDataSource to false. The add following code in the MainPage’s constructor after InitializeComponent method.

using System.ServiceModel.DomainServices.Client;
DemoRIASerices.Web.ItemContext t = new DemoRIASerices.Web.ItemContext();
tblItemDataGrid.ItemsSource = t.tblItems;
EntityQuery<DemoRIASerices.Web.tblItem> s = t.GetTblItemsQuery();
LoadOperation<DemoRIASerices.Web.tblItem> op = t.Load(s); 

Build and run the application. You should see same output as above.

Let’s create search functionality so that we can search via Item Number. For that modify the Mainpage.xaml to add the TextBox to enter Item Number to be search and a search Button. Then create a GetTblItemsByItemNumber method in ItemService.cs file in the DemoRIASerices.Web project

public IQueryable<tblItem> GetTblItemsByItemNumber(int itemnumber)
{
   return this.ObjectContext.tblItems.Where(i => i.ItemNumber == itemnumber); 
}

Then on the search button’s click event write the following;

using System.ServiceModel.DomainServices.Client;
DemoRIASerices.Web.ItemContext t = new DemoRIASerices.Web.ItemContext();
tblItemDataGrid.ItemsSource = t.tblItems;
EntityQuery s = t.GetTblItemsByItemNumberQuery(txtItemNumber.Text == "" ? 0 : 
Convert.ToInt32(txtItemNumber.Text));
LoadOperation op = t.Load(s); 

Now Build and run the application … if you search for the Item number it will display the result as following:

WCF RIA Service - IQueryable Output

Custom Domain Service

So far we created Domain Service vai Entity Framework. Let’s create our custom domain service so that entity framwork is not used. Add a new Item in DemoRIASerices.Web project for Domain Service Class and make sure to select “<empty domain service class>”

Now let’s create a Item class as following:

public class Item
{
    [Key]
    public int ItemNumber { get; set; }
    public string ItemDescription { get; set; }
    public Nullable Quantity { get; set; }
}

Notice there the ItemNumber is marked as [Key]… that means the Item Number is the Key element.Then create a method which returns list of Items as following:

using System.Data;
using System.Data.SqlClient;
[EnableClientAccess()]
public class DomainService1 : DomainService
{
    public List<Item> GetItemsFromDatabase()
    {
        SqlConnection sqlConnection = new SqlConnection(connectionString);
        DataSet objSet = new DataSet();
        SqlCommand sqlCommand = new SqlCommand();
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandText = "Select * FROM tblItem";
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
        sqlDataAdapter.SelectCommand = sqlCommand;
        sqlDataAdapter.Fill(objSet);

        List<Item> lstResult = new List<Item>();
        Item objEmployee;

        if (objSet.Tables.Count > 0)
        {
            foreach (DataRow dr in objSet.Tables[0].Rows)
            {
                objEmployee = new Item();
                objEmployee.Quantity = Convert.ToInt32(dr["Quantity"]);
                objEmployee.ItemDescription = dr["ItemDescription"].ToString();
                objEmployee.ItemNumber = Convert.ToInt32(dr["ItemNumber"]);
                lstResult.Add(objEmployee);
            }
        }
        return lstResult;
    }
}

Below code will bind the datagrid with custom domain sevice..

DemoRIASerices.Web.DomainService1 s = new DemoRIASerices.Web.DomainService1();
tblItemDataGrid.ItemsSource = s.Items;
EntityQuery i = s.GetItemsFromDatabaseQuery();
LoadOperation iop = s.Load(i); 

Hope you enjoy the post… in the next article we will see the different way to format the data gird and its column…

Tags: brh, #DOTNET, #SILVERLIGHT, wcf services, Windows Communication Foundation, #WCF, web services and wcf serices, #ASP.NET, Silverlight 4.0 New Features, Data Binding, DataGrid, Custom Domain Service, Load Operation, Domain Service, Domain DataSource, Entity Query, Domain Modal Entities, WCR RIA Services, RIA,


Dinesh Sodani
30 · 6% · 1807
0
Liked
 
0
Lifesaver
 
0
Refreshed
 
0
Learned
 
0
Incorrect



Submit

Your Comment


Sign Up or Login to post a comment.

    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]