Click here to Skip to main content
15,867,986 members
Articles / Database Development / SQL Server / SQL Server 2008

Silverlight Application with WCF Service and Child Windows as Popups - Part 1

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
13 May 2011CPOL4 min read 36.1K   1.9K   11   7
Silverlight application for scheduling a meeting

Introduction

In this application, I create a meeting scheduler using which one can schedule a meeting and call other colleagues to attend the meeting. This application uses the WCF services to fetch and save records. I have also used Silverlight child window to get the saved contacts to send mail to them. Child window is used as popup for adding contacts in the scheduler forms. This application is very useful for all those to just started learning Silverlight and have confusion with the basics of its interaction with database only through WCF services or webservices.

Tools and Technologies Used to Develop this Application

  • Visual Studio 2010
  • C# 4.0
  • Silverlight 4
  • SQL Server 2008
  • WCF Services

Step by Step Description of this Application

Create a new Silverlight application in Visual Studio 2010 File->New->Project -> select Silverlight in Visual C# -> select Silverlight Application. Rename it to Meetingschedule and click on ok. A popup window is prompted, click ok for that too.

You can see two projects in the solution explorer; one is the Silverlight project and another is the web project which is used to consume the Silverlight application.

Now our main purpose is to design the form in MainPage.xaml in Silverlight application. Below, you can see the XAML code for the form design, also how this design should be seen in the browser.

XML
<!--<UserControl x:Class="MeetingSchedule.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" Height="500" Width="450" xmlns:
    sdk=<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
	http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk</a> 
    xmlns:toolkit=
	<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">
	http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit</a> 
    Margin="300,100,0,0">

    <Grid x:Name="LayoutRoot" HorizontalAlignment="Center" 
	Background="#9BEFD7C7" OpacityMask="#FF13B9D8">
        <Grid.RowDefinitions>
            <RowDefinition Height="60*" />
            <RowDefinition Height="52*" />
            <RowDefinition Height="50*" />
            <RowDefinition Height="48*" />
            <RowDefinition Height="52*" />
            <RowDefinition Height="52*" />
            <RowDefinition Height="80*" />
            <RowDefinition Height="52*" />
            <RowDefinition Height="54*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="123*" />
            <ColumnDefinition Width="258*" />
            <ColumnDefinition Width="19*" />
        </Grid.ColumnDefinitions>
        <TextBlock Height="60" HorizontalAlignment="Left"
        Name="textBlock1" Text="Meeting Schedule"
                   VerticalAlignment="Top" Grid.ColumnSpan="2"
                   Width="381" Padding="10" Foreground="#FF087B08"
                   FontFamily="Times New Roman" FontSize="40"
                   TextAlignment="Center" FontWeight="Bold"
                   FontStretch="Condensed" ></TextBlock>
        <TextBlock Grid.Row="1" Height="42" HorizontalAlignment="Right"
        Name="textBlock2" Text="Agenda of Meeting" VerticalAlignment="Top" Width="123"
        Padding="5,10,0,0" Foreground="#FF185218" 
	FontSize="11" FontFamily="Arial Black" />
        <TextBox Grid.Column="1" Height="23" Grid.Row="1" HorizontalAlignment="Left"
        Margin="10,10,0,9" Name="txtAgenda" Width="240" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0"
        Name="txtLocation" VerticalAlignment="Top" Width="240"
        Grid.Column="1" Grid.Row="2" />
        <TextBlock FontFamily="Arial Black" FontSize="11"
        Foreground="#FF185218" Height="42" HorizontalAlignment="Right"
        Name="textBlock3" Padding="15,10,0,0" Text="Location"
        VerticalAlignment="Top" Width="123" Grid.Row="2" />
        <TextBlock FontFamily="Arial Black" FontSize="11"
        Foreground="#FF185218" Height="42" HorizontalAlignment="Right"
        Name="textBlock4" Padding="15,10,0,0" Text="Start Time"
        VerticalAlignment="Top" Width="123" Grid.Row="3" />
        <TextBlock FontFamily="Arial Black" FontSize="11"
        Foreground="#FF185218" Height="42" HorizontalAlignment="Right"
        Name="textBlock5" Padding="15,10,0,0" Text="End Time"
        VerticalAlignment="Top" Width="123" Grid.Row="4" />
        <TextBlock FontFamily="Arial Black" FontSize="11"
        Foreground="#FF185218" Height="42" HorizontalAlignment="Right"
        Name="textBlock6" Padding="15,10,0,0" Text="Contacts"
        VerticalAlignment="Top" Width="123" Grid.Row="5" />
        <TextBlock FontFamily="Arial Black" FontSize="11"
        Foreground="#FF185218" Height="42" HorizontalAlignment="Right"
        Name="textBlock7" Padding="15,10,0,0" Text="Meeting Details"
        VerticalAlignment="Top" Width="123" Grid.Row="6" />
        <TextBox Height="66" HorizontalAlignment="Left" AcceptsReturn="True"
        Margin="10,6,0,0" Name="txtDetails" VerticalAlignment="Top"
        Width="240" Grid.Column="1" Grid.Row="6" />
        <Button Content="Schedule" Grid.Row="7" Height="30"
        HorizontalAlignment="Left" Margin="12,9,0,0" Name="btSchedule"
        VerticalAlignment="Top" Width="111" Click="btSchedule_Click" />
        <sdk:Label Grid.Column="1" Grid.Row="7" Height="28"
        HorizontalAlignment="Left" Margin="0,11,0,0" Name="lblMessage"
        VerticalAlignment="Top" Width="250" />
        <TextBox Height="52" HorizontalAlignment="Left" AcceptsReturn="True"
        Margin="10,0,0,0" Name="txtContacts" IsReadOnly="True"
        VerticalAlignment="Top" Width="240" Grid.Column="1" Grid.Row="5" />
        <toolkit:BureauBlueTheme Grid.Column="1" Grid.ColumnSpan="2"
        Grid.Row="8" Height="50" HorizontalAlignment="Left" Margin="228,62,0,0"
        Name="bureauBlueTheme1" VerticalAlignment="Top" Width="100" />
        <sdk:DatePicker Grid.Column="1" Grid.Row="3" Height="26"
        HorizontalAlignment="Left" Margin="10,6,0,0" Name="dateStart"
        VerticalAlignment="Top" Width="145" />
        <toolkit:TimePicker Grid.Column="1" Grid.Row="3" Height="22"
        Value="4:00 PM" HorizontalAlignment="Left" Margin="160,6,0,0"
        Name="timeStart" VerticalAlignment="Top" Width="95" Grid.ColumnSpan="2" />
        <sdk:DatePicker Height="26" HorizontalAlignment="Left"
        Margin="10,6,0,0" Name="dateEnd" VerticalAlignment="Top"
        Width="145" Grid.Column="1" Grid.Row="4" />
        <toolkit:TimePicker Height="22" HorizontalAlignment="Left"
        Value="5:00 PM"  Margin="160,10,0,0"  Name="timeEnd"
        VerticalAlignment="Top" Width="95" Grid.Column="1" Grid.Row="4" />
        <Button Content="+" Grid.Column="1" Grid.Row="5"
        HorizontalAlignment="Left" Margin="256,0,0,0" Name="button1"
        Width="34" FontFamily="Arial Black" FontSize="28" Click="button1_Click" />

    </Grid>

</UserControl>

-->

Click to enlarge image

Image 2

Creating Child Window for Popup for Adding Contacts to the Main Page

Create a new folder in Silverlight project and name it view, then right click on it -> click on add ->New items-> select Silverlight child window and rename it popup and click on add.

Following is the XAML and design for the popup.xaml childwindow to show all the contacts from database. In this, a datagrid with all template columns is used to show all contacts and a checkbox (in header too) is used to check those records which should be included in the meeting.

Click to enlarge image

Image 4

All designing is completed for scheduling a meeting. Now our next task is to fetch records from the database and fill the datagrid in the child window. For this, we have used the WCF service because Silverlight does not support ADO.NET, so we cannot directly interact with the database.

Database Accessing with WCF Services and Consuming WCF Services in Silverlight Application

For adding a WCF service to the web project which consumes the Silverlight application, follow the steps given below.

Right click on web project whatever name you gave to it, in my case it is meetingSchedule.web, then a pop up window is opened. Click on Silverlight under Visual C# -> select Silverlight-enabled WCF Service. Then click on ok button. A WCF service is now added to your project which interacts with Silverlight.

You can write method to save records and fetch records from Silverlight application using this Service1.Svc WCF service. I have written two methods in it; one for filling datagrid in childwindow of Silverlight and the other is saved data from mainpage for scheduling the meeting, which is later used to send mail to all added contacts.

Following is the code in the WCF service to fill the Datagrid.

Add the following namespaces to WCF service:

C#
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
C#
namespace MeetingSchedule.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = 
		AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        /// <summary>
        /// This class is used as datatype for generic list for 
        /// sending the data over the network
        /// </summary>
        [DataContract]
        public class contacts
        {
            [DataMember]
            public string FName { get; set; }
            [DataMember]
            public string LName { get; set; }
            [DataMember]
            public string Address { get; set; }
            [DataMember]
            public string Email { get; set; }
        }

/// <summary>
        /// This Method is used to show all contacts 
        /// in the gridview of silverlight popups
        /// </summary>
        /// Created By: Balwant
        /// <returns></returns>
  [OperationContract]
        public List<contacts> fetchContacts()
        {
        List<contacts> allContact= new List<contacts>();
        SqlConnection con = new SqlConnection();
        con.ConnectionString = 
	WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select FirstName,LastName,Address,Email from Contact";
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var contacts = new contacts
                {
                    FName = dt.Rows[i]["FirstName"].ToString(),
                    LName = dt.Rows[i]["LastName"].ToString(),
                    Address = dt.Rows[i]["Address"].ToString(),
                    Email = dt.Rows[i]["Email"].ToString()
                };
                allContact.Add(contacts);
            }
        }

       return allContact;
}

Following is the code to save the meeting schedule data from Silverlight using WCF service to database:

C#
[OperationContract]
        public string saveSchedule(string agenda, string location, 
	DateTime StartTime, DateTime EndTime, string contacts, string details)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = WebConfigurationManager.ConnectionStrings
				["ConnectionString"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            con.Open();
            cmd.Connection = con;
            cmd.CommandText = "insert into Meeting values
		(@Title,@Location,@StartTime,@EndTime,@Contact,@Details,@CreatedDate)";
            cmd.Parameters.AddWithValue("@Title", agenda);
            cmd.Parameters.AddWithValue("@Location", location);
            cmd.Parameters.AddWithValue("@StartTime", StartTime);
            cmd.Parameters.AddWithValue("@EndTime", EndTime);
            cmd.Parameters.AddWithValue("@Contact", contacts);
            cmd.Parameters.AddWithValue("@Details", details);
            cmd.Parameters.AddWithValue("@CreatedDate", System.DateTime.Now);
            cmd.ExecuteNonQuery();
            return "Record is saved successfully, 
		Thanks for submitting schedule for meeting.";
        }

How to Consume this WCF Service in our Silverlight Application

Adding service reference: Right click on Silverlight project and click on add service reference->Click on Discover, this will discover all the WCF services. Please see below:

Image 5

All those methods we have created will be available to us in our Silverlight project after we add WCF service to our project.

Use WCF Service Method in our Silverlight Project

For showing records in the datagrid of child window, we use fetchContacts() methods result in our .CS page. Below is the code for it:

C#
use this namespace to access WCF service
using MeetingSchedule.ServiceReference1;
 public Popup()
        {
            InitializeComponent();
            ServiceReference1.Service1Client newclient = 
			new ServiceReference1.Service1Client();
            newclient.fetchContactsCompleted += 
		new EventHandler<fetchcontactscompletedeventargs>
			(newclient_fetchContactsCompleted);
            newclient.fetchContactsAsync();
          //  this.Closed += new EventHandler(Popup_Closed);
        }
void newclient_fetchContactsCompleted(object sender, fetchContactsCompletedEventArgs e)
        {

            //throw new NotImplementedException();
            dataGrid1.ItemsSource = e.Result;
        }

Now the Datagrid is filled with data from the database using WCF service methods.

Show the Popup on Button Click

The main page CS file code for it is:

C#
private void button1_Click(object sender, RoutedEventArgs e)
       {
         Popup  myPopUp = new Popup();
          myPopUp.Show();
           //myPopUp.Closed += new EventHandler(myPopUp_Closed);

       }

Conclusion

In this article, I have explained how to use WCF service to fetch records from database and shown data in datagrid and popup childwindow from main page.

This application is not complete yet, but this is the basis for this application. The second part will explain how to add contacts from child windows to the main page which are checked, saving the data from my own page, sending mail to all selected contacts. This will be pending till the next article.

Image 6

Thanks and do read the next part of this article within a few days. I am compiling the second part.

History

  • 10th May, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer IDS Ltd
India India
MCA from GNDU Amritsar 2010 batch pass out.Having 1.3 Years of experience in .net programming with C#.
Earlier worked with Logic Lab Technologies

Comments and Discussions

 
QuestionErrors I am getting When I run your app Pin
Member 1003596018-Jun-13 23:26
Member 1003596018-Jun-13 23:26 
GeneralMy vote of 4 Pin
crcklssp23-Jun-12 0:11
crcklssp23-Jun-12 0:11 
QuestionMy vote of 5* Pin
Nasenbaaer23-Sep-11 10:02
Nasenbaaer23-Sep-11 10:02 
GeneralHelpful ! Pin
ricemaster00026-May-11 17:28
ricemaster00026-May-11 17:28 
GeneralSource Code Missing Pin
Member 438652011-May-11 22:52
Member 438652011-May-11 22:52 
GeneralMy vote of 2 Pin
Perry Bruins11-May-11 18:55
Perry Bruins11-May-11 18:55 
GeneralRe: My vote of 2 Pin
Balwant.mnd12-May-11 21:12
Balwant.mnd12-May-11 21:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.