Creating a Silverlight Application that inserts data to a database using WCF service


Introduction

In this article, I have created a Silverlight application that asks users to enter choices & moves to specific pages depending on the choices. I have shown here how to use merged resource dictionaries. We can also see how to create controls dynamically. Finally, this application consumes a WCF service to store data in the database using LINQ to SQL.

My application contains four parts:

  1. Creating the database
  2. Creating the Silverlight application
  3. Creating the WCF service
  4. Silverlight application consuming the service
Creating the database:

Step 1: Open the SQL Server Management Studio & connect to the server.

Database1.gif

Step 2:

Add a new database.

Database2.gif

Step 3:

Give a name to the database (In our case it is UrmiDatabase).

Database3.gif

Step 4:

Add a new table to the database.

Database4.gif

Step 5:

Here I have created a table with two columns:

EmpName [nvarchar(50)]
EmpID[nchar(10)]

Database5.gif

Step 6:

Save the table & give it a name (In our case it is Employee).

Database6.gif

You can add some data to the table if you want.

Step 7:

Create one more table (in our case it is Student table) by following the previous steps.

My Student table has two columns

StudentName [nvarchar(50)]
RollNo[int]

Database7.gif

Creating the Silverlight Application:

Step 1:

Open Visual Studio 2010 & create a new Silverlight application. (I have given a name MySilverlightApplication)

ESilverlight1.gif

Step 2: Click OK.

ESilverlight2.gif

Step 3:

Now in MainPage.xaml, add one StackPanel and inside the StackPanel add two radio buttons.

The MainPage.xaml will be

<UserControl x:Class="MySilverlightApplication.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">
<StackPanel Height="38"HorizontalAlignment="Left" Margin="21,20,0,0" Name="stackPanel1"VerticalAlignment="Top" Width="198" Orientation="Horizontal">
<
RadioButton Content="Employee" Height="16" Name="radioButton1" Margin="10"/>
<
RadioButton Content="Student" Height="16" Name="radioButton2" />
</
StackPanel>
</Grid>
</
UserControl>

ESilverlight3.gif


Step 4:

Now right click on the Silverlight project and add a new folder.

ESilverlight4.gif

Step 5:

Give a name to the folder (in my case it is MyResrc)

ESilverlight5.gif

Step 6:

Right click on the folder & add a new item.

ESilverlight6.gif

Step 7:

Add a Silverlight Resource Dictionary & give it a name (in my case it is MyRDictionary.xaml)

ESilverlight7.gif

Step 8:

In MyRDictionary.xaml add the following namespace.

<ResourceDictionary
xmlns:system="clr-namespace:System;assembly=mscorlib"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
</ResourceDictionary>

We are adding this namespace so that in future we can extract string, double etc. as resources.

ESilverlight8.gif

Step 9:

Now go to the MainPage.xaml & set the Background property of the Grid (LayoutRoot) from the property window,

Now the MainPage.xaml is

<UserControl x:Class="MySilverlightApplication.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">
<
StackPanel Height="38"HorizontalAlignment="Left" Margin="21,20,0,0" Name="stackPanel1"VerticalAlignment="Top" Width="198" Orientation="Horizontal">
<
RadioButton Content="Employee" Height="16" Name="radioButton1" Margin="10"/>
<
RadioButton Content="Student" Height="16" Name="radioButton2" />
</
StackPanel>

<Grid.Background>
<
LinearGradientBrushEndPoint="1,0.5"StartPoint="0,0.5">
<
GradientStop Color="Black" Offset="0" />
<
GradientStop Color="#FFC0C3AB" Offset="1" />
<
GradientStop Color="#FFB9BCA5" Offset="1" />
<
GradientStop Color="Gold" Offset="0.066" />
</
LinearGradientBrush>
</
Grid.Background>
</Grid>
</
UserControl>

ESilverlight9.gif

Step 10:

Now go to the App.xaml & the following code.

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MySilverlightApplication.App"
>
 
<Application.Resources>
<ResourceDictionary>
<
ResourceDictionary.MergedDictionaries>
<
ResourceDictionary Source="MyResrc/MyRDictionary.xaml"/>
</
ResourceDictionary.MergedDictionaries>
</
ResourceDictionary>

</Application.Resources>
</
Application>

Now a merged resource dictionary enables you to declare the contents of a resource dictionary by referencing an external file. Here the external file is MyRDictionary.xaml.

Step 11:

Now go to the MainPage.xaml & select the Grid. Then go to the property window & right click on the Background property. Now select Extract Value to Resource.

ESilverlight11.gif

Step 12:

Now give a name to the Key (in my case it is MyBackground) & choose your Dictionary (here it is MyRDictionary.xaml).

ESilverlight12.gif

Step 13:


Now if you go to the MainPage.xaml , you can notice the following change. The Background property has changed automatically.

<UserControl x:Class="MySilverlightApplication.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="{StaticResource MyBackground}">
<
StackPanel Height="38"HorizontalAlignment="Left" Margin="21,20,0,0" Name="stackPanel1"VerticalAlignment="Top" Width="198" Orientation="Horizontal">
<
RadioButton Content="Employee" Height="16" Name="radioButton1" Margin="10"/>
<
RadioButton Content="Student" Height="16" Name="radioButton2" />
</
StackPanel>
</
Grid>
</
UserControl>

Step 14:

Now again select the grid & go to the property window. Right click on the Background property & select Go to Value Definition.

ESilverlight14.gif

Step 15:


You can see the changes to the MyRDictionary.xaml.

<ResourceDictionary
xmlns:system="clr-namespace:System;assembly=mscorlib"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush x:Key="MyBackground"EndPoint="1,0.5"StartPoint="0,0.5">
<
GradientStop Color="Black" Offset="0" />
<
GradientStop Color="#FFC0C3AB" Offset="1" />
<
GradientStop Color="#FFB9BCA5" Offset="1" />
<
GradientStop Color="Gold" Offset="0.066" />
</
LinearGradientBrush>
</ResourceDictionary
>

Step 16:

Now add a new item to the Silverlight project.

ESilverlight16.gif

Step 17:

Add a new Silverlight page to the project (Here it is Page1.xaml)

ESilverlight17.gif

Step 18:

Now just add the highlighted code to Page1.xaml.

<navigation:Page x:Class="MySilverlightApplication.Page1"
 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:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
d:DesignWidth="640" d:DesignHeight="480"
 Title="Page1 Page">
<
Grid x:Name="LayoutRoot"Background="{StaticResource MyBackground}">

</Grid>
</
navigation:Page>

We are not adding any control to this page as we will do it dynamically.

ESilverlight18.gif

Step 19:

Now add one more Silverlight page (Here it is Page2.xaml) by following the steps 16, 17 & 18.

ESilverlight19.gif

Step 20:

Now go to MainPage.xaml.cs & write down the following code.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
using System.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
 
namespace MySilverlightApplication
{
publicpartialclassMainPage : UserControl
    {
public MainPage()
        {
InitializeComponent();
Loaded += newRoutedEventHandler(MainPage_Loaded);
        }
voidMainPage_Loaded(object sender, RoutedEventArgs e)
        {
            radioButton1.Checked += newRoutedEventHandler(RB_Checked);
            radioButton2.Checked += newRoutedEventHandler(RB_Checked);
        }
voidRB_Checked(object sender, RoutedEventArgs e)
        {
RadioButtonrb = e.OriginalSourceasRadioButton;
if (rb.Content.ToString().ToUpper() == "EMPLOYEE")
this.Content = newPage1();
else
this
.Content = newPage2();
 
 
        }
    }
}


Explanation of the code:

In the MainPage constructor we have declared a loaded event handler. In the loaded handler, we have declared one common checked event handler for the two radiobuttons. In the checked event hadler, we are checking the content of the checked radiobutton. According to the content value, we are moving to respective pages.

Step 21:

Add a new item to the Silverlight project.

ESilverlight21.gif

Step 22 :

Add a new class (in our case it is MyLogic.cs).

ESilverlight22.gif

Step 23 :

Add the following code in MyLogic.cs

usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Ink;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;

namespace MySilverlightApplication
{
publicclassMyLogic
    {
publicstaticButton b1;
publicstaticButton b2;
publicstaticTextBox t1;
publicstaticTextBox t2;
publicstaticStackPanel SetForm(string[] args)
        {
StackPanelsp = newStackPanel();
sp.Orientation = Orientation.Vertical;
            t1 = CreateTextbox(sp, args[0]);
            t2 = CreateTextbox(sp, args[1]);
            b1 = newButton();
            b1.Content = "Submit";
            b1.Height = 20;
            b1.Width = 50;
sp.Children.Add(b1);
            b2 = newButton();
            b2.Height = 20;
            b2.Width = 100;
            b2.Content = "Back To Form";
sp.Children.Add(b2);
returnsp;
 
        }
privatestaticTextBox CreateTextbox(StackPanelsp, stringss)
        {
TextBoxtxtbx = newTextBox();
txtbx.Height = 20;
txtbx.Width = 100;
sp.Children.Add(txtbx);
TextBlock txt = newTextBlock();
txt.Text = ss;
sp.Children.Add(txt);
returntxtbx;
 
        }
    }
}


Explanation of the code :

In this class , we are creating the controls dynamically. It has four static members & two static member functions. In the SetForm function we are creating one Stackpanel control, two TextBox controls & two Button controls. Then we are adding the controls to the Stackpanel & returning the Stackpanel control to the caller. This function takes a string array as an argument. This string array actually contains all the fields of the database table where we want to add data.

The CreateTextbox function creates one TextBox control & one TextBlock control. We are defining this function for code optimization.

Step 24:

Now add the following code to Page1.xaml.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
using System.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Navigation;

namespace MySilverlightApplication
{
publicpartialclassPage1 : Page
    {
public Page1()
        {
InitializeComponent();
Loaded += newRoutedEventHandler(Page1_Loaded);
        }
void Page1_Loaded(object sender, RoutedEventArgs e)
        {

StackPanelsp = newStackPanel();
string[] args = { "Employee Name", "Employee ID" };
sp = MyLogic.SetForm(args);
LayoutRoot.Children.Add(sp);
MyLogic.b1.Click += newRoutedEventHandler(b1_Click);
MyLogic.b2.Click += newRoutedEventHandler(b2_Click);
        }
privatevoid b2_Click(object sender, RoutedEventArgs e)
        {
this.Content = newMainPage();
        }
privatevoid b1_Click(object sender, RoutedEventArgs e)
        {
        }

    }
}


Explanation of the code :

Here we are calling the SetForm function which return a StackPanel control. We are attaching the Stackpanel to the Grid control of Page1.xaml. We have defined the click handler of one button also. It simply returns to the MainPage.

Step 25:

Here add the following code to Page2.xaml.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
using System.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;
usingSystem.Windows.Navigation;

namespace MySilverlightApplication
{
publicpartialclassPage2 : Page
    {
public Page2()
        {
InitializeComponent();
Loaded += newRoutedEventHandler(Page2_Loaded);
        }

void Page2_Loaded(object sender, RoutedEventArgs e)
        {

StackPanelsp = newStackPanel();
string[] args = { "Student Name", "Roll No" };
sp = MyLogic.SetForm(args);
LayoutRoot.Children.Add(sp);
MyLogic.b1.Click += newRoutedEventHandler(b1_Click);
MyLogic.b2.Click += newRoutedEventHandler(b2_Click);
        }
privatevoid b2_Click(object sender, RoutedEventArgs e)
        {
this.Content = newMainPage();
        }

privatevoid b1_Click(object sender, RoutedEventArgs e)
        {
        }

    }
}


Now we have finished creating a basic Silverlight application.

Creating the WCF service:

Step 1 :

Right click on MySilverlightApplication.Web & add a new item.

FWCF1.gif

Step 2:

Add a Silverlight enabled WCF service.

FWCF2.gif

Step 3:

Again add a new item to MySilverlightApplication.Web.

FWCF3.gif

Step 4:

Add a LINQ to SQL class .

FWCF4.gif

Step 5:

Go to the server explorer & add a database connection.

FWCF5.gif

Step 6:

Enter the server name, select database name (here it is UrmiDatabase) & click Test Connection.

FWCF6.gif

Step 7:

Drag & drop the Employee & Student table to the middle pane.

FWCF7.gif

Step 8:

Add the following code to service1.svc.cs

using System;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.ServiceModel.Activation;

namespaceMySilverlightApplication.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
publicclassService1
    {
[OperationContract]
publicboolAddEmployee(string nm, stringuid)
        {
try
            {

DataClasses1DataContext context = newDataClasses1DataContext();
Employeeemp = newEmployee();
emp.EmpName = nm;
emp.EmpID = uid;
context.Employees.InsertOnSubmit(emp);
context.SubmitChanges();
returntrue;
            }
catch
            {
returnfalse;
           }

         }

        [OperationContract]
publicboolAddStudent(string nm, intrl)
        {
try
            {

DataClasses1DataContext context = newDataClasses1DataContext();
Studentstd = newStudent();
std.StudentName = nm;
std.RollNo = rl;
context.Students.InsertOnSubmit(std);
context.SubmitChanges();
returntrue;
            }
catch
            {
returnfalse;
            }
 
        }
// Add more operations here and mark them with [OperationContract]
    }
}


Explanation of the code:

Both of the functions create objects of the data model classes & add that object to the data context. Thus insertion of data takes place in the database using LINQ.

Step 9:

Right click on Service1.svc & select View in Browser.

FWCF9.gif

Step 10:

Our service is running now.

Copy the URL.

FWCF10.gif

Silverlight Application consuming the WCF service:

Step 1:

Right click on the Reference of the Silverlight project and add a service reference.

WService1.gif

Step 2:

Paste the URL & click Go.

WService2.gif

Step 3:

Now go back to Page1.xaml.cs & add the button click event handler.

privatevoid b1_Click(object sender, RoutedEventArgs e)
        {
string nm = MyLogic.t1.Text;
stringuid = MyLogic.t2.Text;
Service1Client proxy = newService1Client();
proxy.AddEmployeeCompleted += newEventHandler<AddEmployeeCompletedEventArgs>(proxy_AddEmployeeCompleted);
proxy.AddEmployeeAsync(nm, uid);
        }
privatevoidproxy_AddEmployeeCompleted(object sender, AddEmployeeCompletedEventArgs e)
        {
bool bb = Convert.ToBoolean(e.Result);
if (bb == true)
this.Content = newMainPage();
 
 
 
        }


Explanation of the Code:

The click event handler takes the value entered in the textboxes into string variables. Then it creates proxy object of the service & call the operation contracts.

Step 4:

In Page2.xaml.cs add the following event handler.

privatevoid b1_Click(object sender, RoutedEventArgs e)
        {
string nm = MyLogic.t1.Text;
intrl = Convert.ToInt32(MyLogic.t2.Text);
Service1Client proxy = newService1Client();
proxy.AddStudentCompleted += newEventHandler<AddStudentCompletedEventArgs>(proxy_AddStudentCompleted);
proxy.AddStudentAsync(nm, rl);
        }
privatevoidproxy_AddStudentCompleted(object sender, AddStudentCompletedEventArgs e)
        {
bool bb = Convert.ToBoolean(e.Result);
if (bb == true)
this.Content = newMainPage();

        }

Step 5:

Now rebuild the solution.

WService5.gif

Step 6:

Click the Employee button.

WService6.gif

Step 7:

Enter data to the TextBoxes& click submit button.

WService7.gif

Step 8:

Select the Student radiobutton.

WService8.gif

Step 9:

Enter data to the TextBoxes& click Submit.

WService9.gif

Step 10:

The database has been modified by the changes you made.

WService10.gif

Step 11:

WService11.gif


Similar Articles