Accessing Database from Silverlight

Hi All,

I am working on Silverlight 2 Beta 2. I ma trying to bind the data to a DataGrid from the DB using LINQ. When I search in the net all articles are talking about binding the data using WCF Service only.

Without WCF we cannot bind the Data?

 I want to design a DataGrid like below


___________________________________________________
|               |                |               Number of                               |
|               |                |___________________________________|
|Column1  |Column 2 |SubColumn1|SubColumn2|SubColumn3|
|________|________ |__________|__________|____________|
| 1          |  a          | as            | fg             | gh            |
| 2          |  b          | sd            | fg             | fgh           |
| 3          |  c          | df             | fg             | fgf           |
________________________________________________

Total     | Total of this Col | same | same...

Let me know

Thanks

Anandraj.A.

You have only 2 method to bind grid in the silver light 1). WCF and 2). Web service (asmx).
1. Create Interface for Datagrid(classes, methods)
2. Create User Control as a Label
3. You have to design a datagrid as your wish by the user control or any.
4. Place table-data into the Label-User-Control through WCF

Note: Dropdown also possible by User Control


 Hi Anandraj

it is a little tricky at best to get databinding in silverlight,  take a look at these videos should help. ado.net data services made life a little easier (but not much) seems to be the way to go.but im not sure if it works with beta, any reason you are using beta?

http://www.microsoft.com/uk/msdn/screencasts/screencast/308/adonet-data-services-a-basic-silverlight-client.aspx

Im not sure about doing it with silverlight 2 beta either?, I know the datagrid changed at some point from beta to live (i think anyway) so you may hit a problem with that.

Hi anand,

WCF is the most suitable way to bind the data in Silverlight applications. We can use LINQ TO SQL classes to create the data layer mapped over SQL Server tables. Further by creating Silverlight-enabled-WebService we can access above created LINQ classes to access the data and fetching to Silverlight application.

First create a silverlight application.

Secondly,

Now that you have created the Silverlight 3 Application, we would add a LINQ to SQL file that is *.dbml .

LinqToSQLSilverlight2.gif


Thirdly,

To communicate with LINQ to SQL we need to have a service that client can call at any time.

Add Silverlight enabled WCF Service to the Web Project.

LinqToSQLSilverlight7.gif


In the Service.svc.cs add methods as per your requirement.

I have written two methods such as:


#region [GetAllEmployees]


        [OperationContract]
        List<vw_mst_EmployeeDetail> GetAllEmployees()
        {
            using (EmployeeDBDataContext context = new EmployeeDBDataContext())
            {
                var result = from emp in context.vw_mst_EmployeeDetails
                             select emp;


                return result.ToList();
            }
        }


        #endregion


        #region [GetEmployeesByFirstName]


        [OperationContract]
        List<vw_mst_EmployeeDetail> GetEmployeesByFirstName(string firstName)
        {
            using (EmployeeDBDataContext context = new EmployeeDBDataContext())
            {
                var result = from emp in context.vw_mst_EmployeeDetails
                             where emp.FirstName.StartsWith(firstName)
                             select emp;


                return result.ToList();
            }
        }


        #endregion


Fourthly,

After writing the service build the project and get this service's reference in Silverlight 3 Project as shown in below figure.

LinqToSQLSilverlight10.gif


<div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #region [GetAllEmployees]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        [OperationContract]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        List<vw_mst_EmployeeDetail> GetAllEmployees()</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            using (EmployeeDBDataContext context = new EmployeeDBDataContext())</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                var result = from emp in context.vw_mst_EmployeeDetails</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             select emp;</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                return result.ToList();</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #endregion</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #region [GetEmployeesByFirstName]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        [OperationContract]</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        List<vw_mst_EmployeeDetail> GetEmployeesByFirstName(string firstName)</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            using (EmployeeDBDataContext context = new EmployeeDBDataContext())</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            {</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                var result = from emp in context.vw_mst_EmployeeDetails</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             where emp.FirstName.StartsWith(firstName)</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                             select emp;</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">                return result.ToList();</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">            }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        }</div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"></div> <div style="position: absolute; left: -10000px; top: 926px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        #endregion</div>

After you add the service it would create the ServiceReferences.ClientConfig file.

Now it's time to design our Silverlight UI in Blend, I have gone for a simple approach, where simple buttons and textbox would help us getting the result which would be displayed in DataGrid.


LinqToSQLSilverlight11.gif


XAML for your reference is as follows - 


<UserControl

    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" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="Mazeweb.Silverlight.MainPage"

    d:DesignWidth="640" d:DesignHeight="480">

    <Grid x:Name="LayoutRoot">

     <Grid.Background>

     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

     <GradientStop Color="#FFF2F2F8" Offset="0.948"/>

     <GradientStop Color="#FF5B99F2" Offset="0.665"/>

     </LinearGradientBrush>

     </Grid.Background>

     <Grid.RowDefinitions>

     <RowDefinition Height="0.106*"/>

     <RowDefinition Height="0.056*"/>

     <RowDefinition Height="0.838*"/>

     </Grid.RowDefinitions>

        <TextBlock HorizontalAlignment="Center" Text="LINQ TO SQL &amp; SILVERLIGHT 3" 

             TextWrapping="Wrap" FontSize="21.333" TextDecorations="Underline" Margin="0,3,0,19" d:LayoutOverrides="Height"/>

        <StackPanel Margin="0" Height="80" VerticalAlignment="Center" Orientation="Horizontal" 

                    HorizontalAlignment="Center" Grid.Row="1">

            <Button x:Name="btnAll" Height="25" Content="Show All" Click="btnAll_Click" VerticalAlignment="Center" Margin="0,0,0,8" Width="109" />

            <Rectangle Height="25" Width="10"/>

            <TextBox x:Name="txtName" Height="25" TextWrapping="Wrap" Width="164" VerticalAlignment="Center"/>

            <Rectangle Height="25" Width="10"/>

            <Button x:Name="btnSubmit" Height="25" Content="Search" Click="btnSubmit_Click" VerticalAlignment="Center" Margin="0,0,0,8" Width="109" />

        </StackPanel>

        <data:DataGrid x:Name="dgResults" Margin="8,10,8,89" Grid.Row="2" IsReadOnly="True" 

                       AutoGenerateColumns="False">

            <data:DataGrid.Columns>

                <data:DataGridTextColumn Binding="{Binding ID}" Header="ID"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding FirstName}" Header="First Name"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding LastName}" Header="Last Name"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding UserCode}" Header="EmailID"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding DesignationName}" Header="Designation"></data:DataGridTextColumn>

                <data:DataGridTextColumn Binding="{Binding BranchName}" Header="Branch"></data:DataGridTextColumn>

            </data:DataGrid.Columns>

        </data:DataGrid>

    </Grid>

</UserControl>

<div>
</div><div>
</div><div>Finally,</div><div>
</div><div>Now we would write client side code to call the service and display the result.

Following code is for Show All Button Click and displaying the result.
</div><div>
</div><div><div>        private void btnSubmit_Click(object sender, RoutedEventArgs e)</div><div>        {</div><div>            ServiceClient clientService = new ServiceClient();</div><div>            clientService.GetEmployeesByFirstNameCompleted += new EventHandler<GetEmployeesByFirstNameCompletedEventArgs>(clientService_GetEmployeesByFirstNameCompleted);</div><div>            clientService.GetEmployeesByFirstNameAsync(txtName.Text);</div><div>        }</div><div>
</div><div>        void clientService_GetEmployeesByFirstNameCompleted(object sender, GetEmployeesByFirstNameCompletedEventArgs e)</div><div>        {</div><div>            dgResults.ItemsSource = e.Result;</div><div>        }</div><div>
</div><div>        private void btnAll_Click(object sender, RoutedEventArgs e)</div><div>        {</div><div>            ServiceClient clientService = new ServiceClient();</div><div>            clientService.GetAllEmployeesCompleted += new EventHandler<GetAllEmployeesCompletedEventArgs>(clientService_GetAllEmployeesCompleted);</div><div>            clientService.GetAllEmployeesAsync();</div><div>        }</div><div>
</div><div>        void clientService_GetAllEmployeesCompleted(object sender, GetAllEmployeesCompletedEventArgs e)</div><div>        {</div><div>            dgResults.ItemsSource = e.Result;</div><div>        }</div><div>
</div><div>
</div><div>Now, Finally you can test your application successfully running.</div>
</div>


Hope this POST helps.


I wrote an article about connecting a datagrid to a silverlight project here. Perhaps it will be useful.

Hi Dear

You have three option

1: Linq to Sql server

2. WCF Service

3. Web Service

1 thoughts on "Accessing Database from Silverlight"

    Do not start taking any kind of new medicines and mention the fact of taking Rimonabant to a few other physician amoxil who will recommended you one more medication. Every client taking this medicine must know the indications of low blood glucose level, that include irritation, augmentin frustration, food cravings, confusion, drowsiness, tremors, quickly pulsation, fainting, and seizure. Tegretol might likewise be utilized for purposes lipitor not specified in this medication overview. In the therapy of fibrocystic bust condition, Danazol generally creates partial to complete extra resources disappearance of nodularity and complete relief of discomfort and inflammation. Adjustments in the menstruation pattern might occur. Scabies mites normally have an effect on spines of the elbows and knees, locations between the fingers, sides of the genital areas, buttocks and feet, areas around the nipple areas and wrists, prednisone because they favor locations where the skin is the thinnest. It switches over off the mind circuits that inform the person cheap advair diskus to overindulge, in this way making it hard to quit eating even more compared to required regularly. Taking any type of medicines besides Sildenafil should be mentioned to your medical professional prior to you ask him lasix for a prescribed. There is a chance a various amount from methotrexate the one your medical professional planned will be required. The location of the skin to vermox which you use the treatment ought to be clean and dry, as ought to be your hands.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>