Learn WCF RIA Service: Day 3

Learn WCF RIA Service: Day 1

Learn WCF RIA Service: Day 2

Overview of Domain Service Class

On day 2 we ran through creating our first line of business application using RIA services. We did not look deeper much into generated classes. Today we will take a step back and examine Domain Service class. Better understanding on Domain Service class would give us more efficiency to create, share and focus on application logic in between presentation layer and middle layer.

If you go ahead and open solution explorer of project we created on day 2, you will get two projects, one Silverlight and other hosting web project there.

image

If you remember we added Domain Service class to the web project and we enabled metadata for domain services as well. Due to that you are seeing there is a metadata.cs class in solution explorer.

Open SchoolRIAService.cs and first thing you would notice would be as in below image.

image

  1. Attribute EnableClientAccess tells this domain class would be visible to the presentation layer residing at client side.
  2. The class is derived from LinqToEntitiesDomainService. This is generic abstract class and it is part of WCF RIA Service framework.
  3. Generic class is taking data model class as input to create domain service.

Next you move further in the class you will find different CRUD methods for different entities from data model. If you have four entities in data model then you will have 16 methods here. For each entity there would be four methods.

Below four methods would perform CRUD operation for Course entity.

image

In this way you will find CRUD methods for other entities like Departments, OnlineCourses etc

If you remember at time of creating Domain Service class, we checked the check box against entities class to enable editing.

image

Besides different generated methods you can plug application logic in this Domain Service class. You can modify existing application logic also for example modifying logic behind GetCourse() method.

I will conclude day 3 with assumption that by now you have an overview of Domain Service Class.

See you on day 4 Smile

Learn WCF RIA Service: Day 2

Learn WCF RIA Service: Day 1

Building a simple line of business Application using RIA Services

Last day we had enough of theory on RIA Services. Today let us get our hand dirty and launch visual studio. We will keep it simple and easy in flow since it is our first exercise.

Essentially we will fetch data from Person table and bind it to grid view on Silverlight page. Flow diagram of the application we are going to make would be as below diagram.

image

Building Silverlight Application

Start with creating a Silverlight application.

image

Next you will get prompted to choose

  1. Web site to host Silverlight application
  2. Select Silverlight target version

And if you have WCF RIA services installed then you will get a check box to instruct Silverlight whether you want to enable WCF RIA Service for this particular Silverlight application or not ? You want to enable WCF RIA service so check the checkbox Enable WCF RIA Services.

image

We have instructed Silverlight application while creating that we want RIA Service enabled and next we need to create Data Model to be exposed and share data through this model in between presentation layer and middle layer.

Building Data Model

To create data model right click on web project [project with extension .web] and choose option add new item from context menu.

image

Next from Data tab you need to choose ADO.Net Entity Model template. We are going to use ADO.Net Entity Model ORM to create data model. ADO.Net Entity Model creates model with extension edmx. Change name of created edmx file to SchoolModel.edmx.

image

After clicking on add button, you will be prompted to choose the source of data model. Either you can create empty data model or choose a database as a source to create data model. We are going to choose School database residing on my local server as a source of data model. So select Generate from database option and click on next button

image

Now you will be prompted to choose database object. If school database is not listed in drop down then you can create a New Connection else you can choose from the dropdown. Let us proceed with creating a new connection

On clicking of New Connection button, you will be prompted with dialog box to specify database connection properties. Specify different values as of below image and click on Test Connection. After getting successful message click on Ok button.

image

In Data connection dialog box if you want you can change the name of connection setting in web.confg. However I am leaving the default name.

image

Click on next button to get last dialog box to conclude data model creation. Here you need to choose database objects you want to put as mart of data model. You can have tables, views, and stored procedures from database as part of data model. I am selecting all tables and stored procedures as part of data model. If you want you can change namespace name but for sake of simplicity at this point leave everything else as default.

image

On click on Finish button you will get data model created and you will get data model file open in designer surface. Here you can notice mapped between the entities.

image

In solution explorer you will find SchoolModel.edmx file has been added under the web project.

clip_image001

Building Domain Service

To create data model right click on web project [project with extension .web] and choose option add new item from context menu.

image

Next from Web tab you need to choose Domain Service class template. Change name to SchoolRIAService.cs and click on Add button.

image

In next dialog box go ahead and

  1. Select DataContext or ObjectContext class from the dropdown. You will get SchoolEntities context class in drop down value to choose.
  2. You can edit Domain Service class name. For simplicity leave it as it is.
  3. You have check box to specify Enable Client Access. Check this check box.
  4. You have check box to specify whether you want to expose ODATA Endpoint. For this time uncheck it.
  5. You will get all the entities from the context class listed. You can choose from them to be exposed as RIA Service. I am selecting all the entities and enabling all entities for edit.
  6. Check the box generates associated class for metadata.

image

Click on OK button and give a second to examine web project in solution explorer. You will find three classes added there. We will examine and talk more on these classes in coming days. Today we are just going to see there uses at the presentation layer in Silverlight project.

image

Using Domain Service in Presentation layer or Silverlight client

You have,

  1. Created data model
  2. Create domain service

Now build the web project and add below namespace on MainPage.xaml.cs file.

image

After adding namespaces open MainPage.xaml and drag and drop a data grid on that. Give name of the data grid as grdRIADataGrid. Xaml would be as below,

MainPage.Xaml


<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="DemoDay2.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">

    <Grid x:Name="LayoutRoot" Background="White">
    <sdk:DataGrid x:Name="grdRIADataGrid" />
    </Grid>
</UserControl>

At this point designing of page has been completed. You need to bind data from person table to data grid. For that

1. Create instance of domain service class

clip_image001[5]

2. Load all people to the context of client side proxy

clip_image003

3. Fetch the entities from loaded list of entities and bind as item source of data grid

clip_image004

Code behind would look like as below,

MainPage.xaml.cs


using System.Windows.Controls;
using DemoDay2.Web;
using System.ServiceModel.DomainServices.Client;
namespace DemoDay2
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            SchoolRIAContext proxy = new SchoolRIAContext();
            LoadOperation<Person> loadPerson = proxy.Load(proxy.GetPeopleQuery());
            grdRIADataGrid.ItemsSource = loadPerson.Entities ;
        }
    }
}

Now you run Silverlight project and in data grid you will get the entire person from school database using RIA Service.

clip_image002

Today we followed a simple path and fetched data from database and bind to data grid on at Silverlight client using RIA Service. We have not gone deeper into different aspect of context class. We will discuss then in further days. I will conclude day two with assumption that by now you know,

  1. Why WCF RIA?
  2. Creating simple line of business application using RIA Services

See you on day 3 Smile

Learn WCF RIA Service: Day 1

Learn WCF RIA Service: Day 1

Why WCF RIA Service ?

It is said that, “If you want to have better understanding on a technology; first find why you need that technology? “ And to adhering above saying, we will start our journey of WCF RIA learning with a discussion on “Why WCF RIA Service? “

Most developers are very much accustomed to work with layered architectures. Usually there are three layers;

 

image

 

It is presentation layer talks to business layer and yield UI output to the client. In normal web application UI output at the client talks to presentation layer over Internet. There is extremely close proximity between presentation layer and business layer and so in between business layer and data layer. Somehow UI rendered at client side does not contain any business specific code and takes instruction from presentation layer and render the html output.

When you use Silverlight to create N-tier Rich Internet Application, presentation layer reside at the client side and it talks to middle layer over the Internet.

 

image

 

In Silverlight application portion of business logic such as validations may reside at middle layer and presentation layer or may be at both layers. In most of the time business logic to and fro in between middle layer and presentation layer

 

image

 

There are astronomical amount of data and many business logics involved in creation of large line of business application. There are many clients pulling and pushing data to the server, authorizing and authenticating with server, validating users and data in the server and to accommodate all these as a developer you will have to write complex services and plug them with the clients. Majority of development time goes in creation of service, managing service, configuring endpoints and then working with proxies at the client side. Imaging if all service related work is being automated then as a developer you could give all your time to application logic. WCF RIA Service does the work of automation for you.

To create powerful Silverlight line of business application, application logic must be shared in between middle layer and presentation layer. WCF RIA Service does this for you without duplicating the code in both layers.

 

image

 

WCF RIA Service shares application logic between view [Presentation layer] and data access layer within a trust boundary. WCF RIA Service eliminates WCF or web service to share the application logic between the layers over Internet. WCF RIA Service acts as a plug in between presentation layer and middle layer. It creates a programming view between these layers to work with application logic.

As name suggests WCF RIA Service is based on WCF Service. It abstracts many complexity of WCF Service from you to focus on business or application logic. However it does not restricts you to use powerful features of WCF in your line of business Silverlight application.

We can summarize now that why we need WCF RIA Service as

  1. It helps line of business application to connect with data and of course without writing WCF or Web services.
  2. It helps application logic to be shared in between entities residing in both presentation layer at the client and middle layer at the server and of course without duplicating application logic code.
  3. It helps in tracking changes in entities at both sides.
  4. It helps in avoiding creation of complex services, management of endpoints and proxy management at client side while connecting data from client in rich line of business application.

 

With hope I am concluding day 1 that you have an understanding on WCF RIA Service. And even if you have some doubt let us directly jump to the code and create a basic application on day 2 and see if you are still having doubt in your mind. See at day 2  Smile

 

Working with JavaScript in Silverlight 4.0

In this post I will show you calling of Javascript function from Silverlight. It is very simple and straight forward.

Assume you have a JavaScript function on aspx page as below,

SilverlightTestPage.aspx


<script type="text/javascript" language="javascript" >
         function callmeonPageLoad() {
             alert("Hello Javascript from Silvertlight");
         }
    </script>


You want to call this Javascript function on page load of the Silverlight page then you will have to add namespace

clip_image001

And in the constructor of the page call it as below,

MainPage.xaml.cs


using System.Windows.Controls;
using System.Windows.Browser;

namespace SilverlightApplication7
{
   [ScriptableType]
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("MainPage", this);
            HtmlPage.Window.Invoke("callmeonPageLoad");

        }
    }
}


If you notice above code you would find that MainPage is attributed with ScriptableType.

clip_image002

On running Silverlight application you will be getting output as below,

clip_image004

On your XAML if you have textbox like below,

clip_image005

You want to access and change value of textbox txtName in Javascript then it too is very simple. Create a function Javascript as below,

SilverlightTestPage.aspx


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {

            var txtBlockFromSL = sender.FindName("txtName");
            alert(txtBlockFromSL.text);
            txtBlockFromSL.Text = "Salsa ";
            alert(txtBlockFromSL.Text);


        }
</script>



txtName is name of the Silverlight text box.

And on the page load on aspx page add a param

clip_image001[5]

If you have a function in managed code and you want to access that from javacript .Assume you have function as below,

MainPage.xaml.cs



  [ScriptableMember]
       public void SilverLightFunction(string txtToUPdate)
        {
            txtName.Text = txtToUPdate;
        }





You can call this function from JavaScript as below,


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {


            var host = sender.GetHost();
            host.content.MainPage.SilverLightFunction("Dhananjay");


        }
</script>



This was all about various ways to work with Silverlight and JavaScript. I hope this post was useful. Thanks for reading.

Smooth Streaming in Silverlight

This post is walkthrough on enabling smooth streaming of media over IIS and then stream over Silverlight client. There are very good documentation available on IIS official site to have a better understanding of smooth streaming. So I am not touching theoretical concept behind smooth streaming in this post. However I have shown steps by steps to enable smooth streaming of media over IIS then to stream over Silvelight client.

See smooth streaming video below ,

Essentially there are four majors steps you need to do

  1. Enable Smooth Streaming on IIS
  2. Encode Media File
  3. Publish Encoded file over IIS
  4. Streaming over Silverlight

Enable Smooth streaming on IIS

You need to download and install IIS Media Services. Go to below URL to download and install IIS Media Services.

http://www.iis.net/download/SmoothStreaming

image

After successful installation, you will have a section of Media Services in IIS.

image

Encode Media File

To encode media for IIS smooth streaming you need Microsoft Expression Encoder 4.0 pro. If you don’t have installed that then download and install that. It comes as part of Microsoft Expression.

Step 1

Very first open Microsoft Encoder Pro 4.0. You will get prompted to choose Project type to be loaded. Select Silverlight Project and press Ok.

image

Step 2

In this step you need to choose the media file to be encoded and streamed over IIS. Click on File in menu and select Import.

clip_image001

Choose media file to be encoded and streamed.

clip_image003

Step 3

In right side tab select Preset option. If you are unable to find Preset tab, select windows from menu and check preset.

clip_image004

From Preset tab select Encoding for Silverlight and then select IIS Smooth Streaming. After selecting option of IIS Smooth Streaming, you can choose VBR rate of your choice.

clip_image005

clip_image006

After IIS Smooth streaming type doesn’t forget to click Apply button.

Step 4

There are many options available for you to configure like,

  1. Thumbnails
  2. Security
  3. Template options
  4. Output path
  5. Publish etc

You can set values for above options as per your requirement. I am going to set output path here. Make sure you have created a folder on your local derive to set as output path for the encoded media for the streaming. On my local D drive, I have created a folder called StreamDemo. So set the output path as below

clip_image001[5]

Make sure to check Sub-folder by job ID. Leave Media File name as default name.

Step 5

If you have set the values for everything required then go ahead and click on the Encode button in the bottom.

clip_image002

You should be getting Encoding status message as below.

clip_image003

After successful encoding you will get encoded media playing the browser from the local derive. Now you have encoded media file.

Publish Encoded File over IIS

To stream over IIS, you need to publish encoded media over IIS. Process to publish encoded media is same as publishing any other web site over IIS.

Step 1

Open IIS as administrator and add a new web site

clip_image001[7]

Step 2

In dialog box you need to provide below information

  1. Site name: Give any name of your choice
  2. Port : Choose any available port above 1024
  3. Host Name : Leave it empty
  4. Type : Http
  5. Check the check box start web site immediately.

In Physical path, give the same location Encoded file is saved. In previous step while encoding media for streaming, I save file in location D:\StreamDEmo. So I am going to set Physical Path as D:\StreamDEmo.

clip_image002[5]

Click Ok to create web site in IIS. So we created site StreamingMediaDemo1. Right click on that and select Manage Web Site and then Browse.

clip_image003[5]

On browsing most likely you will get forbidden error message as below,

clip_image005

Append Default.html in URL to play the media.

clip_image006[5]

Media will be played as below,

clip_image007

Now append wildlife.ism/manifest to the URL. This manifest file would be used in Silverlight and other clients to stream media over IIS.

clip_image008

Note: In further post; I will discuss more theory of streaming manifest file.

See Video of above performed steps below ,

Streaming over Silverlight

To Play media on Silverlight download below player from the CodePlex.

http://smf.codeplex.com/releases/view/63434#DownloadId=222617

After download extract the file on locally. You will have to add references of these dll in Silverlight project. Since dll got downloaded from the web, so they would be locked. To use them in the project right click and unblock them.

Step 1

Create a Silverlight project.

clip_image010

Choose the Host application and select the version as Silverlight 4.0

clip_image011

Step 2

Right click and add the reference from the extracted file of pervious step.

clip_image002

The above are DLL of the media player you downloaded from Codeplex.

Step 3

You need to download IIS smooth client and install from below URL.

http://www.iis.net/download/smoothclient

Step 4

Right click on Silverlight project and add reference of Microsoft.web.media.smoothstreaming.dll

To locate this file on your local drive browse to C:\Program Files (x86)\Microsoft SDKs\IIS Smooth Streaming Client\v1.5\Silverlight on 64 bit machine.

clip_image004

Step 5

Next we need to design Silverlight page. Open MainPage.xaml and add namespace,

clip_image006

And add a player on the page downloaded to play stream media as below,

clip_image007[6]

Eventually xaml will be as below with a textblock to display message and player

Mainpage.xaml

</span>
<pre><UserControl x:Class="SilverlightStreaming.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:strmmedia="http://schemas.microsoft.com/smf/2010/xaml/player"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Vertical">
            <TextBlock Text="Streaming Media from IIS on Silverlight" Height="22" Width="266" FontSize="12" Foreground="Blue"/>
            <strmmedia:SMFPlayer Name="strmPlayer"
                                 HorizontalAlignment="Stretch"
                                 Margin="0"
                                 VerticalAlignment="Stretch"
                                 Height="261" Width="395"/>
        </StackPanel>
    </Grid>
</UserControl>

Step 6

We need to write some code on page load to create play list of streamed media and play in the player.

See Video of above performed steps below ,

Mainpage.xaml .cs


using System;
using System.Windows.Controls;
using Microsoft.SilverlightMediaFramework.Core.Media;

namespace SilverlightStreaming
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            PlaylistItem item = new PlaylistItem();
            item.MediaSource = new Uri("http://dhananjay-pc:7654/wildlife.ism/manifest");
            item.DeliveryMethod = Microsoft.SilverlightMediaFramework.Plugins.Primitives.DeliveryMethods.AdaptiveStreaming;
            strmPlayer.Playlist.Add(item);
            strmPlayer.Play();
        }
    }
}

Step 7

Before pressing F5 to run application make sure you have put a ClientAccessPolicy.xml file in D:\StreamdMedia location or the Physical path of IIS website streaming the media to avoid cross domain problem.

Press F5 to run the application.

clip_image001[9]

These were what all required to smooth stream media from IIS and play in Silverlight client. I hope this post was useful. I am looking very forward for your comments on the post. Thanks for reading  Smile



**************

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Upload large file of size more than 5 MB from Silverlight to Server location using WCF

This post is based on post File Upload from Silverlight using WCF. So please read it before proceeding with this post

Long back I wrote post on uploading a File from Silverlight to server location using WCF. I found my own post quiet useful. However, when I reread and implemented the code, I mentioned in the post, I found few discrepancies

  1. Code was unable to upload file with sizes in MB
  2. There was a bug in binding configuration

In this post, I am going to rectify above two bugs.

First modify basicHttpBinding as below,

image

Configure Endpoint as below,

image

So far everything is fine and if you run the code, you would able to upload a file maximum of the size 3MB. I tested and I was able to upload document file of size 2.75 MB.

Now question comes, what if we want to upload a file of the size around 10 MB?

For that we need to reconfigure the things in configuration file

  1. Configure service behavior maximum number of items to serialize or deserialize.
  2. Configure HTTP Request length limit.

You need to explicitly configure the behavior of service to the maximum number of items to serialize or deserialize. This can be configured either in code or in configuration file.

MaxItemsInObjectGraph property of DataContractSerilalizer determines number of items can be serizlized or deserizlized.

image

Http Request limit can be configured as below

image

After completing above changes configuration file at service would look like below,


<?xml version="1.0"?>

<configuration>

  <system.web>

    <compilation debug="true" targetFramework="4.0" />

    <httpRuntime maxRequestLength="10240" />

  </system.web>

  <system.serviceModel>

    <bindings>

      <basicHttpBinding>

        <binding name="ServicesBinding"

                 maxReceivedMessageSize="2147483647"

                 maxBufferSize="2147483647">

          <readerQuotas

                    maxArrayLength="2147483647"

                    maxBytesPerRead="2147483647"

                    maxDepth="2147483647"

                    maxNameTableCharCount="2147483647"

                    maxStringContentLength="2147483647" />

        </binding>

      </basicHttpBinding>

    </bindings>

    <services>

      <service name="ServiceData.Service1" behaviorConfiguration="ServiceData.Service1Behavior">

        <endpoint address="" binding="basicHttpBinding" contract="ServiceData.IService1" bindingConfiguration ="ServicesBinding" >

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

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

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name ="ServiceData.Service1Behavior">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

          <dataContractSerializer maxItemsInObjectGraph ="2147483647"/>

        </behavior>

      </serviceBehaviors>

    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

  </system.serviceModel>

 <system.webServer>

    <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>

</configuration>

Now you should able to upload a large file as of size 10 MB from Silverlight client to the server location using WCF Smile


**************

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Consuming ODATA in Silverlight 4.0

ODATA is everywhere and so is Silverlight. In this post, I will show, How ODATA can be consumed in Silverlight? “

OData URL

I will be using NorthWind OData URL. You can access that URL from below link.

http://services.odata.org/Northwind/Northwind.svc/

We are going to fetch Customers table from NorthWind DataBase.

Create Project and Add Service Reference

Create a Silverlight project

image

Choose Silverlight 4 as version

clip_image001

Right click on project and add Service Reference

In Address you need to give URL of OData. As we discussed in previous steps, here I am giving OData URL of NorthWind Database hosted by OData.org.

clip_image003

Add below namespaces on MainPage.Xaml.cs page

clip_image004

Please make sure about second namespace. Since, I have added service reference of OData with name ServiceReference1 and name of project is ODatainMangoUpdated.

Globally defined below variables

clip_image006

In constructor of MainPage,

  1. Create instance of NorthWindEntities
  2. Create instance of DataServiceCollection passing context
  3. Write the LINQ query.
  4. Attach event handler LoadCompleted on DataServiceCollection object.
  5. Fetch the result asynchronously

image

On the completed event

  1. Check whether next page exist or not , if yes load automatically
  2. Set the DataContext of layout as result.

image

Design Page and Bind List Box

Here you need to create a ListBox and in Data Template put three TextBlock vertically. Bind the different columns of table to the text blocks

image

For your reference full source codes are given below. Feel free to use them Smile

MainPage.Xaml


<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="ODATAWithSilverLight.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">
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="MainListBox" Margin="0,0,-12,0"
                 ItemsSource="{Binding}"
                 Height="350"
                 Width="250"
                 ScrollViewer.VerticalScrollBarVisibility="Visible">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432">
                        <TextBlock Text="{Binding Path=CompanyName}"
                                          TextWrapping="NoWrap"
                                       />
                        <TextBlock Text="{Binding Path=ContactName}"
                                         TextWrapping="NoWrap"
                                       Margin="12,-6,12,0" />
                        <TextBlock Text="{Binding Path=Phone}"
                                          TextWrapping="NoWrap"
                                       Margin="12,-6,12,0"
                                       />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

MainPage.Xaml.cs


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 ODATAWithSilverLight.ServiceReference1;
using System.Data.Services.Client;

namespace ODATAWithSilverLight
{
    public partial class MainPage : UserControl
    {

        private NorthwindEntities context;
        private readonly Uri ODataUri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
        private DataServiceCollection<Customer> lstCustomers;

        public MainPage()
        {
            InitializeComponent();
            context = new NorthwindEntities(ODataUri);

            lstCustomers = new DataServiceCollection<Customer>(context);
            var result = from r in context.Customers select r;
            lstCustomers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(lstCustomers_LoadCompleted);
            lstCustomers.LoadAsync(result);

        }

        void lstCustomers_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (lstCustomers.Continuation != null)
            {
                lstCustomers.LoadNextPartialSetAsync();
            }
            else
            {
                this.LayoutRoot.DataContext = lstCustomers;
            }

        }

    }
}

Run Application

Press F5 to run the application. You should get all the records from Customer table in List box.

image

I Hope this post was useful. Thanks for reading Smile



********************

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

AutoCompleteBox in Silverlight 4.0 with DataSource from SQL Server

In my last article AutoCompleteBox in Silverlight 4.0 , Data Source for Autocomplete Box was an IEnumerable list. In this post we will work with a column value of table from SQL Server as Data Source for Autocomplete Box.

Our approach would be

1. Create WCF Service

2. Exposed data

3. Consume in Silverlight

4. Put data exposed by service as data source of Autocomplete Box.

I have a table called Course in School database. I am going to bind value of the Title column of Course table as source for AutoCompletebox.

Create WCF Service

Right click on web project hosting Silverlight application and add a new item by selecting WCF Service application from Web tab.

1. Very first let us create a Service Contract returning titles as list of string.

clip_image001

Create Data Access layer

Now let us create a Data Access layer using LINQ to SQL class.

a. Right click on web application project and add a new item. Select LINQ to SQL class from Data tab.

clip_image003

Note: I have written many posts on LINQ. You can refer them for better and detail understanding of LINQ. In this post I am going bit faster J

b. Select server explorer option.

c. Either create a new data connection or choose [if listed for your Database server] from server explorer.

clip_image004

d. Drag and drop Course table on dbml file.

Now our Data access layer is in place.

Implement Service

Service contract and Data access layer is in place. Now let us implement the service.

clip_image006

I have done a very simple stuff in above code. I created instance of Data class context and fetching all the titles from courses table.

Test WCF Service

Right click on .SVC class and select show in browser.

Consume WCF Service in Silverlight

Right click on Silverlight application and add service reference. Since WCF Service is in same solution with Silverlight click on Discover to select service.

clip_image007

Now Service is added. We need to make a client side class to bind as data source of Autocomplete box. Add below class in Silverlight project.

clip_image009

Call WCF Service

We know we need to make asynchronous call to WCF from Silverlight. In completed event we can bind Autocompletebox as below.

clip_image011

In above snippet atcTextBox is name of the Autocompletebox.

Drag and Drop AutoCompleteBox on XAML

1. From the tool box select AutoCompleteBox and drop on the XAML page

clip_image012

2. Set the Binding, ValueMemberPath and FilterMode.

clip_image014

3. Set the DataTemplate and bind the TextBlock where user will type the text.

clip_image015

For reference,

MainPage.Xaml


<Grid x:Name="LayoutRoot" Background="White">
<sdk:AutoCompleteBox x:Name="atcTextBox" ItemsSource="{Binding}"
ValueMemberPath="CourseName"
FilterMode="Contains"
IsTextCompletionEnabled="True"
Height="30" Margin="62,22,54,248">
<sdk:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CourseName}" />
</DataTemplate>
</sdk:AutoCompleteBox.ItemTemplate>

</sdk:AutoCompleteBox>

</Grid>

MainPage.Xaml.cs


using System;
using System.Collections.Generic;
using System.Windows.Controls;
using SilverlightApplication4.ServiceReference1;

namespace SilverlightApplication4
{
public partial class MainPage : UserControl
{
List<Courses> lstCourses = null;
public MainPage()
{
InitializeComponent();
Service1Client proxy = new Service1Client();
proxy.GetTitleToBindCompleted += 
new EventHandler<GetTitleToBindCompletedEventArgs>(proxy_GetTitleToBindCompleted);
proxy.GetTitleToBindAsync();

}

void proxy_GetTitleToBindCompleted(object sender, GetTitleToBindCompletedEventArgs e)
{

lstCourses = new List<Courses>();
var res = e.Result;
foreach (var r in res)
{
lstCourses.Add(new Courses { CourseName = r.ToString() });

}

atcTextBox.DataContext = lstCourses;
}
}
}