Window Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 2 October 2010

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

Posted on 23:08 by Unknown

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.

Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • First Windows Phone 7 update February 2011 - Small update but Big start
    After tons of rumors and set of predictions on Windows Phone 7 all over Internet, Microsoft came up with first Windows Phone 7 minor update ...
  • The little Story of “I Unlock Joy” event by Microsoft and Pune User Group
      This post is about recent “I Unlock Joy” event happened in Pune which was conducted by Microsoft and Pune User Group. Little History : ...
  • Silverlight On Mobile : Windows Phone 7 Splash Screen and Customization
    After talking about 3D capabilities on Windows Phone 7 using Silverlight in last article , Now I am moving ahead with small but equally impo...
  • Silverlight 5 : Platform Invoke (PInvoke) in Silverlight
      Two days back Microsoft announced availability of Silverlight 5 RC,I encourage you to download bits from here , My friend Pete Brown alr...
  • Introduction to Speech Capabilities in Windows Phone 8 – Part 1
    After a long..I am writing blog, I hope and I wish I will resume blogging like I use to in past. Lots of things happened in past few months....
  • MCTS : Microsoft Silverlight 4 Development Exam Guide (70-506) by Packt Publishing
      Hello, After a long time I got chance to come back here.I will soon resume blogging in month of August. Last 4-5 months were horrible due...
  • Introduction to Speech Capabilities in Windows Phone 8 – Part 2
    Hope you enjoyed my last article on Speech Capability in Windows Phone 8, Today I am posting another part or you can say little extension t...
  • Silverlight 3 : Insert & Update Data using WCF Service with DataForm and DataGrid
    In my Lap around Silverlight 3 series, I have written a separate article on DataForm in Silverlight 3, This article is a basic extension to ...
  • Mango : Using DeviceStatus in Windows Phone 7.1
    First of all “Thank You” for your wonderful response and comments on my last article on Silverlight Vs HTML5 ,I hope you like the points I ...
  • Silverlight, HTML5 & Windows 8 : Where we are heading to ?
    This is not the post or yet another post on most happening debate of Silverlight and HTML5, This is just a visit to all of them to realize t...

Blog Archive

  • ►  2013 (4)
    • ►  August (1)
    • ►  April (3)
  • ►  2012 (4)
    • ►  July (1)
    • ►  March (2)
    • ►  January (1)
  • ►  2011 (24)
    • ►  December (1)
    • ►  September (4)
    • ►  August (2)
    • ►  July (1)
    • ►  June (4)
    • ►  May (3)
    • ►  April (3)
    • ►  March (1)
    • ►  February (4)
    • ►  January (1)
  • ▼  2010 (21)
    • ►  December (1)
    • ►  November (2)
    • ▼  October (3)
      • Silverlight On Mobile : Launchers in Windows Phone 7
      • Silverlight On Mobile : Using EQATEC Profiler for ...
      • Silverlight On Mobile : Invoke WCF Service and Dat...
    • ►  September (2)
    • ►  August (4)
    • ►  July (5)
    • ►  May (1)
    • ►  April (1)
    • ►  March (1)
    • ►  January (1)
  • ►  2009 (49)
    • ►  December (1)
    • ►  November (5)
    • ►  October (2)
    • ►  September (1)
    • ►  August (5)
    • ►  July (5)
    • ►  June (1)
    • ►  May (5)
    • ►  April (5)
    • ►  March (9)
    • ►  February (4)
    • ►  January (6)
  • ►  2008 (43)
    • ►  December (3)
    • ►  November (9)
    • ►  October (7)
    • ►  September (4)
    • ►  August (2)
    • ►  July (3)
    • ►  June (4)
    • ►  May (3)
    • ►  March (3)
    • ►  February (5)
Powered by Blogger.

About Me

Unknown
View my complete profile