Sunday, October 3, 2010

Silverlight On Mobile : Invoke WCF Service and Data Operations in Windows Phone 7

I hope you like my last post on InputScope.Many of you dropped me email and asking about Data representation and Data binding,operations on Windows Phone 7.Till now I kept prime focus on basic structure and functionalities,capabilities of device.Now we are in good position to talk about data,So let’s talk about it today.In past, I have wrote decent amount of articles on Data Binding and CRUD operations using Grid,DataForm in Web version of Silverlight. Thanks for your massive positive response for that.Now let’s see what we can do on Windows Phone 7 with the Silverlight Framework available on it.

I am going to split this article in 2 parts :

  • Adding WCF Service to Windows Phone 7
  • Doing Insert Operation using WCF service with SQL as backend

For this example,I am using a simple table schema in SQL as :

Constraints Field Name Data Type Null / Not Null
PK (Autogen) empno int Not Null
  ename nchar(10) Allow Null
  deptno int Allow Null
  salary int Allow Null

* Data Types are just taken for sake of Demo,In reality I encourage you to choose proper Data Types which are suitable

I am using same Project Template i.e Windows Phone 7 Application, So nothing rest is changed for this. After doing above schema,you can put your records in it or have your own schema instead.Now lets talk about first part which is Adding WCF Service to Windows Phone 7

Adding WCF Service to Windows Phone 7 :

Many of my friends told me that they have some issues on Adding Reference through Visual Studio and also with generation of Config file with WCF. Frankly, I never came across this with my instance of Visual Studio, But by chance if you, then you can try with command line utility “SLSvcUtil.exe” for this purpose like this :

slsvcutil

In normal scenario, You need to add WCF Application Project to your solution like this :

addingwcf

Here goes the Service Code :

Service Contract :

[ServiceContract]
    public interface IService
    {
        [OperationContract]
        bool InsertEmployee(Employee emp);
    }

Operation Contract :

[DataContract]
   public class Employee
   {
       [DataMember]
       public int EmpNo { get; set; }
       [DataMember]
       public string EmpName { get; set; }
       [DataMember]
       public int DeptNo { get; set; }
       [DataMember]
       public int Salary { get; set; }
   }

Implementation :

public bool InsertEmployee(Employee emp)
        {
            bool Inserted = false;
            Conn = new SqlConnection("Data Source=.;Initial Catalog=EmployeeWP;Integrated Security=SSPI");
            Cmd = new SqlCommand();
            Conn.Open();
            Cmd.Connection = Conn;
            Cmd.CommandText = "Insert into  Employees Values (@EmpName,@Salary,@DeptNo)";
                      
            Cmd.Parameters.AddWithValue("@EmpName", emp.EmpName);
            Cmd.Parameters.AddWithValue("@DeptNo", emp.DeptNo);
            Cmd.Parameters.AddWithValue("@Salary", emp.Salary);

            int ins = Cmd.ExecuteNonQuery();
            if (ins > 0)
            {
                Inserted = true;
            }

            Conn.Close();
            return Inserted;
        }

* I am using “Select” query for demo purpose, it might not be in “Best Practice” format, so do the needful in your application or have Stored Procedure. Also Empno is Auto generated field so no parameter for that.

So,part one is over.This is how you can add WCF service to your Windows Phone application. Like Insert I have done here, you can add Update,Delete and Select methods as per your application demands.May be in coming days,I will demonstrate full CRUD operation scenario,but to start with it,its I think sufficient. Also not that,since it’s a demo, I have not hosted it on IIS and working fine for me,In reality, you need to host it as a “Best Practice”

Doing Insert Operation using WCF service with SQL as backend :

This is our second part of article, Here we will create a simple UI and invoke WCF service we created above, We will refer this service and pass data via UI to service and then finally service will do the needful and we will have relevant data in Database.

XAML Code :

Title Panel :

<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Explore .NET with Vikram Pendse" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Add New Employee" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="40"/>
        </StackPanel>

Layout :

<!--ContentPanel - place additional content here-->
       <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
           <TextBlock Height="33" Margin="0,39,0,0" TextWrapping="Wrap" Text="Name" VerticalAlignment="Top" Grid.Column="1" HorizontalAlignment="Left" Width="88" d:LayoutOverrides="GridBox" FontSize="21.333"/>
           <TextBlock Height="43" Margin="0,114,0,0" TextWrapping="Wrap" Text="Dept No" VerticalAlignment="Top" Grid.Column="1" HorizontalAlignment="Left" Width="88" FontSize="21.333"/>
           <TextBlock Height="45" Margin="0,189,0,0" TextWrapping="Wrap" Text="Salary" VerticalAlignment="Top" Grid.Column="1" HorizontalAlignment="Left" Width="73" FontSize="21.333"/>
                      
           <TextBox Grid.Column="1" Height="73" Margin="108,22,8,0" x:Name="txtname" TextWrapping="Wrap" VerticalAlignment="Top"/>
           <TextBox Grid.Column="1" Height="73" Margin="108,95,8,0" x:Name="txtdeptno" TextWrapping="Wrap" VerticalAlignment="Top"/>
           <TextBox Grid.Column="1" Height="73" Margin="108,169,8,0" x:Name="txtsal" TextWrapping="Wrap" VerticalAlignment="Top"/>

           <Button Content="Submit" Height="75" Margin="116,0,185,250" x:Name="btnSubmit" VerticalAlignment="Bottom" Click="btnSubmit_Click"/>
       </Grid>
It will look like this :

 

Add Service Reference :

reference

C# Code :

General Declaration :

MyServiceRef.ServiceClient Proxy;
bool IsNewInsertFlag = false;

Constructor :

// Constructor
public MainPage()
{
        InitializeComponent();

       Proxy = new MyServiceRef.ServiceClient();
}

Code to Insert Record :

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
      IsNewInsertFlag = true;
      if (IsNewInsertFlag == true)
     {                
         Proxy.InsertEmployeeCompleted += new System.EventHandler<MyServiceRef.InsertEmployeeCompletedEventArgs>(Proxy_InsertEmployeeCompleted);
        Proxy.InsertEmployeeAsync(new MyServiceRef.Employee (){EmpNo=0,EmpName=txtname.Text,DeptNo=Convert.ToInt32(txtdeptno.Text),Salary=Convert.ToInt32(txtsal.Text)});
      }
}                  

void Proxy_InsertEmployeeCompleted(object sender, MyServiceRef.InsertEmployeeCompletedEventArgs e)
{
     bool Res = e.Result;
     if (Res == true)
     {
         MessageBox.Show("Record Added Successfully !!");
     }
     else 
     {
         MessageBox.Show("Unable to Insert record,Try Again !!"); 
     }
}

Done !, So now hit F5 and put one record to test like this :

InsertIntoAfter Clicking on Submit, It will insert new record and send note on UI like this :

success
So,here is end of our second part and hence the article. You can enhance the UI part as per your design skills and you can add some InputScope,Jazzy background or styles depends on your application. I will surely try to bring more jazz in this app in coming days and will try to cover full functional CRUD. Till that time you guys go ahead and give a try for this. I tried to make things simple,but if you feel or have or want to share more simple way than this, Please do give me feedback so that I will make note of that in my coming articles. I am coming with much more stuff soon including Silverlight 4 and Windows Phone 7,So keep visiting here..lot more to come !

Vikram.

3 comments:

Swamy said...

HI vikram...Very good article I like it thanks so much

joethy said...

thanks :D a very useful article. But i got one error. The type or namespace name 'ServiceClient' does not exist in the namespace 'WindowsPhoneApplication1.ServiceReference1' (are you missing an assembly reference?). may i ask why is that so? :(

Vikram Pendse said...

Joethy,

Source code is well and I re-run and tested,No issues at my end, If you could drop me a line at vikram[dot]pendse[at]puneusergroup[dot]org I can look into more or send across sample code.