Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘WCF RIA’

Bind Silverlight Grid view with WCF Service

Posted by Viral Sarvaiya on September 17, 2010

Hello friends….

Here I demonstrate how to bind the grid view of the Silverlight with WCF Service.

You already know what is the Silverlight and WCF. My one post that demonstrate the use of the WCF Service with Silverlight, for more info about that check

Setp 1 : Create New Silverlight Project( here I give name of the project is “SilverlightGridTest”)

In the Visual Studio 2008 or 2010, file menu -> New -> project.

Select Silverlight application, give name as SilverlightGridTest and open the project.

Then check the checkbox true of the host the Silverlight application in web site.

Now you have 2 project in the solution.

Step 2: Database information


Name VARCHAR(256),

Phone VARCHAR(50),

City VARCHAR(50)


make one procedure named “GetAllPersonInfo” and write the following Statement in the procedure

Select *from person order by name;

Step 3: Create WCF Service

Right click to SilverlightGridTest.web project, select add -> new item.

Choose Silverlight in left panel and choose Silverlight-enable WCF Service. Then give name “DataService.svc”

So Service has been added to project.

Here we have interface IDataService.cs and DataService will implements that so in our IDataService.cs code is as below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SilverlightGridTest.Web



public interface IDataService



PersonDetails GetPersonDetails();



public class PersonDetails


List<Personinfo> _PersonList = new List<Personinfo>();


public List<Personinfo> PersonIndex


get { return _PersonList; }

set { _PersonList = value; }




public class Personinfo



public string Name { get; set; }


public string Phone { get; set; }


public string City { get; set; }



In the “DataService.svc.cs” file write the following.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data;

namespace SilverlightGridTest.Web


public class DataService : IDataService


public PersonDetails GetPersonDetails()


DatabaseHandler dbObj = new DatabaseHandler();

DataTable dataTablePersonInfo = dbObj.GetPersonInfo();

PersonDetails PersonDataMessage = new PersonDetails();

for (int iTagCounter = 0; iTagCounter < dataTablePersonInfo.Rows.Count; iTagCounter++)


Personinfo PersonInfo = new Personinfo();

PersonInfo.Name = dataTablePersonInfo.Rows[iTagCounter]["Name"].ToString();

PersonInfo.Phone = dataTablePersonInfo.Rows[iTagCounter]["Phone"].ToString();

PersonInfo.City = dataTablePersonInfo.Rows[iTagCounter]["City"].ToString();



return PersonDataMessage;




Now add the new class name “DatabaseHandler.cs” for the operation on the database. Means this function will get the data from the database.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections.ObjectModel;

namespace SilverlightGridTest.Web


public class DatabaseHandler


private string _gConnectionString = ConfigurationManager.ConnectionStrings["Database"].ToString();

public DataTable GetPersonInfo()


SqlConnection sqlConnect = new SqlConnection(_gConnectionString);


DataTable dbTbl = new DataTable();

//Get data

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "GetAllPersonInfo";

cmd.Connection = sqlConnect;

cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter oAdapter = new SqlDataAdapter(cmd);



return dbTbl;




Step 4: Web.Config Settings

Database Connection string


<add connectionString="packet size=4096;server=ServerName;persist security info=False;database=DatabaseName;uid=UserName;pwd=Password;" />


Service Settings





<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="false" />







<binaryMessageEncoding />

<httpTransport />




<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />


<service behaviorConfiguration="SilverlightGridTest.Web.TestServiceBehavior" name="SilverlightGridTest.Web.DataService">

<endpoint address="" binding="basicHttpBinding" contract="SilverlightGridTest.Web.IDataService" />

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />




Step 5: Add clientaccesspolicy.xml and crossDomain.xml file.

This will complete the coding in the SilverlightGridTest.Web .

Build the application.

Now move to SilverlightGridTest.

Add the service reference and add the service which we develop above.

Step 6: Mainpage.xaml file.

Now in the Mainpage.xaml file put the grid control.

<UserControl x:Class="SilverlightGridTest.MainPage"








d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">

<sdk:DataGrid x:Name="AllPerson" GridLinesVisibility="All" AutoGenerateColumns="False" >


<sdk:DataGridTextColumn Binding="{Binding Name}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" />

<sdk:DataGridTextColumn  Binding="{Binding Phone}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="Phone"/>

<sdk:DataGridTextColumn  Binding="{Binding City}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="City"/>





Step 7 : Mainpage.xaml.cs file

Make the object of the service client, coding as follow.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using SilverlightGridTest.DataService;

namespace SilverlightGridTest


public partial class MainPage : UserControl


public DataServiceClient objDataService;

public MainPage()



objDataService = new DataServiceClient();

objDataService.GetPersonDetailsCompleted += new EventHandler<GetPersonDetailsCompletedEventArgs>(objDataService_GetPersonDetailsCompleted);



void objDataService_GetPersonDetailsCompleted(object sender, GetPersonDetailsCompletedEventArgs e)


AllPerson.ItemsSource = e.Result.PersonIndex;




Step 8: Run the application.

You will get the data will display in the grid as below

Enjoy coding…..

Posted in ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , , , , , , | 14 Comments »

WCF Duplex client for Silverlight

Posted by Viral Sarvaiya on September 9, 2010

WCF services offer the functionality to send data down to a Silverlight client. The Silverlight client polls the service at a regular interval to check if data is available for transfer.

Here are some great examples of how to implement duplex communication between WCF web services and Silverlight clients:

Posted in ASP.NET, Silverlight | Tagged: , , , , , , , , , | 1 Comment »

Security for WCF RIA Services

Posted by Viral Sarvaiya on June 11, 2010

The following checklist is a starting point for ensuring secure usage of a domain service.

  1. Minimize the data and operations exposed by a domain service. This is the first line of defense against information disclosure and denial of service.
    1. Expose only those entities that are needed by the client. This approach may require that you separate server logic and validation from client logic and validation, if it enables you to reduce the number exposed entities. For example, an expense report application that does not need the Employee entity on the client should not expose it through a domain service.
    2. Shape entities to avoid exposing sensitive data. You can use the ExcludeAttribute attribute or presentation model to reduce the data that is available to a client. For example, if birth date and Social Security number are not required in an application, exclude them from the shape that is visible to the client.
    3. Require query methods to take parameters that are needed in your application, instead of relying on data filtering capabilities in LINQ. For example, if expense reports are shown for a given employee, you should require an employee ID as a parameter in the query method and you should not provide a method that gets all expense reports. This approach minimizes the potential of data harvesting for all employees.
    4. Create query methods that provide only the data needed for specific scenarios in your application. This approach means that you might provide multiple query methods that return portions of the data instead of a single query method that returns all of the data. For example, if products are shown by category or supplier, you can provide two methods that accept category or supplier information, instead of a single method that returns all of the products.
    5. Filter data to provide only the data normally required for your application. For example, you might have a query method that returns only orders that were fulfilled in the past year.
    6. Restrict the number of results that can be returned from a query to minimize accidental or deliberate overloading of the server. You use the ResultLimit property on the QueryAttribute to throttle the numbers of results that can be returned. For example, if a large number of products can be returned, enforce paging on the client by throttling the results to 20. Also, consider using the OutputCacheAttribute attribute for output caching to reduce the load on the middle tier and database.
    7. Minimize the number of operations for each exposed entity. For example, if an order application only needs to add or modify orders, you should expose query, insert, and update operations on the orders entity, but not delete operations. In addition, you should expose only query operations for the products entity but not any data modification operations.
    8. Whenever possible, use named update methods that restrict which members can be updated.
  2. Restrict data and operation access to authenticated users and users in specific roles.
    1. Avoid anonymous access whenever possible by using the RequiresAuthenticationAttribute attribute. When you must allow anonymous access, limit it to the smallest set of domain services and the smallest subset of operations within those domain services.
    2. Add the operation-specific RequiresRoleAttribute attribute whenever possible. Consider each operation separately in a domain service. For example, all users may need to query the products entity, but only users in the administrator role need to update it.
    3. Consider using the AuthorizationContext property to provide a customized authorization model.
    4. Treat any data sent by a client as suspicious. A malicious client (even one that is authenticated and authorized) can provide tampered values for current and original values in a change set. Your application logic should not assume that these values are trustworthy. Instead, consider potential threats from tampered original values.
  3. Use the https protocol for Forms authentication. Sending passwords in clear text is a significant vulnerability, but it can be mitigated by using https.
  4. Expose the minimum number of endpoints. By default, RIA Services creates a binary endpoint for a domain service. Add additional endpoints only if you have clients that specifically need the endpoints. Disable any endpoints that are not in use.

For More Details :

Posted in RIA WCF | Tagged: , , , , , , , , | Leave a Comment »

WCF RIA Services

Posted by Viral Sarvaiya on June 11, 2010

WCF RIA Services simplifies the development of n-tier solutions for Rich Internet Applications (RIA), such as Silverlight applications. 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.

The following illustration shows a simplified version of an n-tier application. RIA Services focuses on the box between the presentation tier and the data access layer (DAL) to facilitate n-tier development with a RIA Services client.

RIA Services n-tier applicationRIA Services adds tools to Visual Studio that enable linking client and server projects in a single solution and generating code for the client project from the middle-tier code. The framework components support prescriptive patterns for writing application logic so that it can be reused on the presentation tier. Services for common scenarios, such as authentication and user settings management, are provided to reduce development time.

For More Details :

Posted in RIA WCF | Tagged: , , , , , | 1 Comment »

%d bloggers like this: