Extension Method

Extension method is a feature in c# 3.0, which allows developer to add functionality in existing class without modifying the existing class or recompiling the existing class or extending the existing class.

  1. It is a new feature of c#3.0
  2. Extension method enables to add new methods to existing type. It does not need creation of derived type to existing type, modifying the original type or recompiling the original type.
  3. It provides ability to programmer to add new methods to existing type.
  4. It can be used to add new methods to existing .Net core classes.
    It is defined as a static method but called with syntax of instance method.
  5. If there is a member method in type class with the same name of extension method then member method will get precedence over extension method.

    For example Show method is member method of Message class. So if there is any extension method called Show on type Message class is created, always Show member method will get precedence over Show extension method for the type Message.
    Compiler Signature

 static class Extensions {
      public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence, Predicate<T> predicate) {
                      foreach (T item in sequence) {
                                                       if (predicate(item))  {
                                                                                      yield  return item;
}}}}

  1. The method is static
  2. The first parameter is decorated with modifier “this” .
  3. First parameter is called as Instance Parameter.
  4. A compile time error will encountered to use this modifer with any other parameter than instance parameter.
  5. No other modifers like ref, out etc are allowed with “this” modifer or instance parameter.
  6. The instance parameter can not be a pointer type.
  7. The method is public .
  8. The instance parameter can not have the type of the type parameter. The below is not possible.

    public static int Obj<T> (this T param)

Restrictions

  1. It could only access public memebers of the target type.
  2. If an extension method conflicts with a member method of target type , always member method is get invoked instead of extension method.

Implementation and Calling

Step1 : Define a static visible class to contain Extension method. 

Step2: Implement the Extension method as static method. 

Step 3: The First parameter of method specifies the type method works on 

Step4 : The First parameter must be preceded by “this” modifer. 

Step 5: At the client code add namespace of extension method with using directive.

 Examples

  1. In first example, I will add an Extension method to existing String class. This extension method will remove all the vowel form the string  

  1. Modify the class with modifier with public and static of the class extensionmethodcontainer. 
  2. Add a extension method with below signature. The First parameter String specifies that this is extension method on the type String.

 public static String RemoveVowel(this String s)

The full code to remove vowel from input string is written in the Extension method.

 

    1 using System;

    2 

    3 using System.Collections.Generic;

    4 

    5 using System.Linq;

    6 

    7 using System.Text;

    8 

    9 namespace ExtensionMethodSample

   10 {

   11 public static class extensionmethodcontainer

   12 {

   13 

   14 public static String RemoveVowel(this String s)

   15 {

   16 string[] vowels = new

   17 

   18 string[] { “A”, “E”, “I”, “O”, “U” };

   19 

   20 if (string.IsNullOrEmpty(s))

   21 return string.Empty;

   22 

   23 List<char> chars = new List<char>(s.ToCharArray());

   24 for (int i = chars.Count – 1; i >= 0; i–)

   25   {

   26        for (int j = 0; j < vowels.Length; j++)

   27             {

   28 

   29                     if (chars[i].ToString().ToLower() == vowels[j].ToLower())

   30 

   31                         chars.RemoveAt(i);

   32              }

   33             }

   34 

   35 return new string(chars.ToArray());

   36 

   37 }

   38 

   39 }

   40 

   41 }

   42 

  1. Client code is here Main class
  2. In main class, user is inputting the string and RemoveVowel extension method is being called on the input string to remove vowel from the string. 

    Note:

    1. Here both Extension method and client is in same namespace, so there is no need to include namespace of the extension method.
    2. Extension method is called as any other member method


      resultString = str.RemoveVowel();

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 namespace ExtensionMethodSample

    6 {

    7 class Program

    8 {

    9 static void Main(string[] args)

   10 {

   11 String resultString;

   12 

   13 Console.WriteLine(“Enter Input String to Remove all Vowel using Extension Method \n”);

   14 

   15 String str = Console.ReadLine();

   16 

   17 Console.WriteLine(“After Removing Vowel Input String is \n”);

   18 

   19 resultString = str.RemoveVowel();

   20 

   21 Console.WriteLine(resultString);

   22 

   23 Console.ReadKey();

   24 }

   25 }

   26 }

   27 }

   28 


 

Happy Coding

Picture Gallery for Windows 7 Phone using WCF REST Service

Objective

In this article I will give you walkthrough of creating a Picture Gallery for Windows 7 phone. I will show how to fetch images from server using WCF REST service. The final output would be like below

Please read this article before going through this article.

In this article, majorly I am going to show you two things

  1. How could we process image from file system of server using REST service and return the jpeg format as response.
  2. How could we consume REST service in Windows 7 phone application? And how could we de- serialize stream at in windows 7 phone application.

Working Diagram

 

If you see above diagram, we are going to perform below steps.

  1. Image files are at some certain location of server.
  2. Using .Net file handling classes, we will fetch those image files.
  3. Using WCF REST service we will return image in form of stream.
  4. We will test the REST service in browser.
  5. We will consume the REST service in Windows 7 phone application.

Step 1

On your server or hard disk of your development machine put some images in a particular folder of a particular drive. I am putting some images inside IMAGES folder of D drive.

I do have below images inside D:\Images folder

Step 2

Accessing the File System in service

To access the files and work with file system in .Net we need to add namespace System.IO .

Now if we want to access name of all the files inside a particular folder, we need to access all the files using instance of DirectoryInfo class. So the code to return all the file names is as below,

In above code

  1. I am creating instance of List of string.
  2. I am creating instance of DirectoryInfo class. In constructor, I am passing the location of the directory.
  3. Using GetFiles method of DirectoryInfo class, I am fetching all the files in that particular directory.
  4. I am iterating through FileInfo array and fetching name of all the files.
  5. I am splitting the file name over dot(.) because I do not want extension of the file to be added as file name.
  6. Finally I am adding the file names in list of string and returning it.  

Step 3

In this step, I will create a WCF REST Service. This Service will return Files name and images as stream. So to create WCF REST Service follows below steps

Step 3A

Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application.

Step 3B

Remove all the default code created by WCF. Remove code from IService 1 interface and Service1 class. Remove the code from Web.Config also. Open Web.Config and remove System.Servicemodel codes.

Step 3C

Right click on Service1.svc select View markup and add below code

<%@
ServiceHost
Language=”C#”
Debug=”true”
Service=”FetchingImageinBrowser.Service1″
CodeBehind=”Service1.svc.cs”
Factory=”System.ServiceModel.Activation.WebServiceHostFactory”
%>

 Step 3D
Now I will create Contracts. There would be two service methods. One would be returning FilesName and other would be returning Stream.

 If you see the above Service Contract, you will find

  1. GetImage operation contract is taking file name as input parameter and returning stream. This service method will be accessed through default URI of hosting server slashed with GetImageand then slashed with input parameter.

    http://localhost:53767/Service1.svc/GetImage/MyImage

  2. GetFIlesName operation contract is returning all the files name of a particular directory. This service method will be accessed through below URL.

    http://localhost:53767/Service1.svc/GetFilesName

    In both above case service is hosted on local server on the port 53767.

Step 3E

In this method we will define the service. Already in step 2 I have shown you, how we could fetch name of all the files from a particular directory. The other service method returning stream is below.

If you read the above code, I am opening the input file in FileStream. Then using WebOperationContext class, I am setting the Outgoing response as Image and Jpeg.

For your reference, the full source code for the service is as below

Contract (IService1.cs)

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Runtime.Serialization;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Web;

    7 using System.Text;

    8 using System.IO ;

    9 namespace FetchingImageinBrowser

   10 {

   11     [ServiceContract]

   12     public interface IService1

   13     {

   14 

   15         [OperationContract]

   16         [WebGet(UriTemplate = “GetImage/{imageName}”,

   17             RequestFormat = WebMessageFormat.Xml,

   18             ResponseFormat = WebMessageFormat.Xml)]

   19         Stream GetImage(string imageName);

   20 

   21         [OperationContract]

   22         [WebGet(UriTemplate = “GetFilesName”)]

   23         List<String> GetFilesName();

   24     }  

   25 }

   26   

 

Service Definition (Service1.svc.cs)

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Runtime.Serialization;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Web;

    7 using System.Text;

    8 using System.IO ;

    9 namespace FetchingImageinBrowser

   10 {

   11     public class Service1 : IService1

   12     {

   13 

   14         public Stream GetImage(string imageName)

   15 

   16         {

   17             FileStream fs = null;

   18             string fileName = string.Format(@”D:\Images\{0}.jpg”, imageName);

   19             fs = File.OpenRead(fileName);

   20             WebOperationContext.Current.OutgoingResponse.ContentType = “image/jpeg”;

   21             return fs;

   22 

   23         }

   24 

   25         public List<String> GetFilesName()

   26         {

   27             List<String> lstFileName = new List<string>();

   28             DirectoryInfo dir = new DirectoryInfo(@”D:\Images”);

   29             FileInfo[] files = dir.GetFiles();

   30             foreach (FileInfo f in files)

   31             {

   32                 lstFileName.Add(f.Name.Split(“.”.ToCharArray())[0]);

   33             }

   34             return lstFileName;

   35         }

   36     }

   37 }

   38 

Step 4
Run the service. By default service will be hosted in Cassini server. We can test this service in browser because it is REST service.

When you run URL http://localhost:53767/Service1.svc/GetFilesName , You will get below output. All the files inside the folder is listed in the browser.


When you run URL http://localhost:53767/Service1.svc/GetImage/MyImage, you will get MYImage (name of the image file) in browser like below


So far, we have created the service and tested successfully in the browser. So we are all set to consume the service in Windows 7 Phone application.

Step 5

Since service is up and running, now we can consume the service anywhere. In this tutorial we are going to consume the service in Windows 7 Phone application.

Step 5A

Create a new Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type.

 

Step 5B

In this step, we will design the page.

 

  1. I have divided the Content Grid in two rows with the ratio of 3:1
  2. In first row put a stack panel.
  3. Inside stack panel put a Button and a Combo box.
  4. Register selection changed event with Combo box.
  5. In second row put a Image control.
  6. Set the height and width of the image as Auto.

Step 5C

In this step we will write the code behind to consume the service.

On click event of button, we will call the service and get the entire files name inside the particular directory.

  1. In above code, I am using WebClient to do asynchronous call to REST service.
  2. If you see closely in string I am assigning the same URL we tested in step 4 to fetch file names.
  3. Using DataContractSerializer class we are creating an instance and passing type we are going to de serialize in constructor.
  4. We are reading all the objects in instance of DataContractSerializer and explicitly typecasting it to List<String>.
  5. One by one we are iterating to list and adding each filename (string) as item of combo box.

On changed event of combo box, we will pass the image name as selected item in combo box and fetch the image and set that image as source of image control.

  1. In above code, I am using WebClient to do asynchronous call to REST service.
  2. If you see closely in string I am assigning the same URL we tested in step 4 to fetch particular image.
  3. I am creating instance of BitmapImage.
  4. Setting the source of the image as response from the service.
  5. Setting the source of image control as instance of BitmapImage.

For your reference whole source code is as below,

MainPage.Xaml

   1: <;phoneNavigation:PhoneApplicationPage 

   2:     x:Class="RESTServiceConsuming.MainPage"

   3:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   4:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   5:     xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"

   6:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

   7:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

   8:     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"

   9:     FontFamily="{StaticResource PhoneFontFamilyNormal}"

  10:     FontSize="{StaticResource PhoneFontSizeNormal}"

  11:     Foreground="{StaticResource PhoneForegroundBrush}">;

  12:     <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">

  13:         <;Grid.RowDefinitions>

  14:             <;RowDefinition Height="Auto"/>

  15:             <;RowDefinition Height="*"/>

  16:         <;/Grid.RowDefinitions>       

  17:         <;Grid x:Name="TitleGrid" Grid.Row="0">

  18:             <;TextBlock Text="Windows 7 Phone" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>

  19:             <;TextBlock Text="Picture Gallery" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>

  20:         <;/Grid>       

  21:         <;Grid x:Name="ContentGrid" Grid.Row="1">

  22:             <;Grid.RowDefinitions>

  23:                 <;RowDefinition Height="*" />

  24:                 <;RowDefinition Height="3*" />

  25:             <;/Grid.RowDefinitions>

  26:             <;StackPanel Orientation="Horizontal" Margin="0,0,0,31">               

  27:                 <;Button x:Name="myButton" Height="50" Content="Get FileNames" />            

  28:                 <;ComboBox x:Name="cmbName" Height="50" 

  29:                           SelectionChanged="cmbName_SelectionChanged"

  30:                           Margin="21,0,10,0"

  31:                           Foreground="Black" Width="211" />;

  32:             </StackPanel>

  33:             <;Image Grid.Row="1" x:Name="myImage" 

  34:                    Height="Auto" Width="Auto"

  35:                    ScrollViewer.HorizontalScrollBarVisibility="Auto"

  36:                    ScrollViewer.VerticalScrollBarVisibility="Auto" />;          

  37:         </Grid>

  38:     <;/Grid>   

  39: </phoneNavigation:PhoneApplicationPage>

 
MainPage.Xaml.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Net;

    5 using System.Windows;

    6 using System.Windows.Controls;

    7 using System.Windows.Documents;

    8 using System.Windows.Input;

    9 using System.Windows.Media;

   10 using System.Windows.Media.Animation;

   11 using System.Windows.Shapes;

   12 using Microsoft.Phone.Controls;

   13 using System.Xml;

   14 using System.Runtime.Serialization;

   15 using System.Windows.Media.Imaging;

   16 

   17 

   18 namespace RESTServiceConsuming

   19 {

   20     public partial class MainPage : PhoneApplicationPage

   21     {

   22         public MainPage()

   23         {

   24             InitializeComponent();

   25             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   26             myButton.Click += new RoutedEventHandler(myButton_Click);         

   27 

   28 

   29         }

   30 

   31         void myButton_Click(object sender, RoutedEventArgs e)

   32         {

   33             cmbName.Items.Clear();

   34             cmbName.SelectedIndex = -1;

   35 

   36             string strUriFilesName = http://localhost:53767/Service1.svc/getfilesName&#8221;;

   37             WebClient proxy1 = new WebClient();

   38             proxy1.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy1_OpenReadCompleted);

   39             proxy1.OpenReadAsync(new Uri(strUriFilesName));

   40 

   41         }

   42 

   43         void proxy1_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

   44         {

   45 

   46             DataContractSerializer ds = new DataContractSerializer(typeof(List<string>));

   47             List<string> lstFileName = (List<string>) ds.ReadObject(e.Result);

   48             foreach (string file in lstFileName)

   49             {

   50                 cmbName.Items.Add(file);

   51             }

   52 

   53         }  

   54 

   55 

   56         private void cmbName_SelectionChanged(object sender, SelectionChangedEventArgs e)

   57         {

   58 

   59             if (cmbName.SelectedIndex != -1)

   60             {

   61                 string imageName = cmbName.SelectedItem.ToString();

   62                 WebClient proxy = new WebClient();

   63                 string strUriImage = http://localhost:53767/Service1.svc/getImage/&#8221; + imageName;

   64                 proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);

   65                 proxy.OpenReadAsync(new Uri(strUriImage));

   66             }

   67         }

   68 

   69         void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

   70         {

   71 

   72             BitmapImage img = new BitmapImage();

   73             img.SetSource(e.Result);

   74             myImage.Source = img;

   75 

   76 

   77         }

   78 

   79     }

   80 }


Now we are ready to run our application. Press F5 and run the application in emulator. After running you will get first screen. Press button to populate the entire files name in the combo box. After selecting a particular file that image would get display as third screen.

I hope this article was informative. Happy Coding.

Consuming basic REST service in Windows 7 mobile application

Objective

In this article I am going to explain how to consume a REST service in windows 7 phone app.

We will achieve this is two steps

  1. Create and Host REST based WCF service
  2. Consume service in W7 phone application.

Create and host REST service

There are many article, I have written discussing REST service. All can be finding here. But again, I am showing it here for benefit of your readers.

What I am going to do is to create a very simple REST service. Service will have one operation contract. This will take one string as input and return greeting message appending the string.

  1. Open visual studio and from File menu select new project. Go to WCF tab and select WCF service application.
  2. Open Web.Config file and inside System.Servicemodel delete any existing endpoint settings.
  3. Right click on your .svc file and select view markup.

Add as a Factory class to the markup of the service System.ServiceModel.Activation.WebServiceHostFactory. after adding markup should look like below

  1. Define the contract. There is one operation contract. This will take a string as input parameter and return a string.

      

    In WebGet attribute all settings are default for XML return and response. URI for the operation will be

    http://hostserver:port/Service1.svc/GetData/[parameter] so if you want to pass your name as parameter then URL would be http://hostserver:port/Service1.svc/GetData/DhananjayKumar

  2. Run the WCF service or right click on .svc file and select view in browser. Once you will run , you will see the below output

    In address bar of browser you can see the URL and XML output would be as below

  3. We are going to host the service for our sample in Cassini server.

    For reference complete code for Web.Config , Contract and Service definition is as below

    Contract (IService1.cs)

  4.     1 using System;

        2 using System.Collections.Generic;

        3 using System.Linq;

        4 using System.Runtime.Serialization;

        5 using System.ServiceModel;

        6 using System.ServiceModel.Web;

        7 using System.Text;

        8 namespace RESTtoConsumeinWindwPhone

        9 {  

       10     [ServiceContract]

       11     public interface IService1

       12     {

       13         [OperationContract]

       14         [WebGet(UriTemplate=“GetData/{a}”,

       15             RequestFormat=WebMessageFormat.Xml  ,

       16             ResponseFormat=WebMessageFormat.Xml,

       17             BodyStyle=WebMessageBodyStyle.Bare)]

       18         String GetData(string a);

       19 

       20 

       21     } 

       22 }

       23 

 

Service Definition (Service1.cs)

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Runtime.Serialization;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Web;

    7 using System.Text;

    8 namespace RESTtoConsumeinWindwPhone

    9 {  

   10     public class Service1 : IService1

   11     {

   12         public String GetData(string a)

   13         {

   14             return “Hello “ + a + “From REST Service “;

   15         }     

   16     }

   17 }

   18  

Web.Config

<?xml version=1.0?>
<configuration>
<system.web>
<compilation debug=truetargetFramework=4.0 /> </system.web> <system.serviceModel><behaviors><serviceBehaviors><behavior>
<serviceMetadata httpGetEnabled=true/>

<serviceDebug includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled=true />

</system.serviceModel>

<system.webServer>

<modules runAllManagedModulesForAllRequests=true/>

</system.webServer>

</configuration>

Consuming REST service in Window 7 Phone application

Very first create Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type.

  1. In content grid place a textbox and a button.
  2. User will eneter text and on clcik event we will pass this text to service and display retrun string into a message box. I am not designing the page very much it’s a very simple page.

     

    MainPage.Xaml.cs

<phoneNavigation:PhoneApplicationPage

x:Class=”RESTServiceConsuming.MainPage”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:phoneNavigation=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”
xmlns:d=http://schemas.microsoft.com/expression/blend/2008

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

mc:Ignorable=”d” d:DesignWidth=”480″ d:DesignHeight=”800″

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”>
<Grid x:Name=”LayoutRoot” Background=”{StaticResource PhoneBackgroundBrush}”>
<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<Grid x:Name=”TitleGrid” Grid.Row=”0″>

<TextBlock Text=”MY APPLICATION” x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

<TextBlock Text=”page title” x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>

</Grid>

<Grid x:Name=”ContentGrid” Grid.Row=”1″>

<Button x:Name=”myButton” Height=”75″ Content=”Call REST service” Margin=”99,197,124,381″ />

<TextBox x:Name=”myTxtBox” Height=”31″ HorizontalAlignment=”Left” Margin=”20,96,0,0″
Text=” “ VerticalAlignment=”Top” Width=”434″ FontFamily=”Verdana” Foreground=”#FFCB4B4B” FontSize=”32″ />

<TextBox x:Name=”myTxtBoxDisplay” Height=”31″ HorizontalAlignment=”Left” Text=” “ VerticalAlignment=”Top” Width=”434″ FontFamily=”Verdana” Foreground=”#FFCB4B4B” FontSize=”20″ Margin=”20,319,0,0″ />

</Grid>

</Grid>
</phoneNavigation:PhoneApplicationPage>


Now I will be consuming REST service on click event of button.

  1. Using WebClient class will make the asynchronous calls.
  2. On returning of the response as stream using DataContractSerliazer , I will de serialize the returned stream.

  3. While constructing the URL to be called append input parameter. I am taking input parameter here from textbox.

MainPage.xaml.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Net;

    5 using System.Windows;

    6 using System.Windows.Controls;

    7 using System.Windows.Documents;

    8 using System.Windows.Input;

    9 using System.Windows.Media;

   10 using System.Windows.Media.Animation;

   11 using System.Windows.Shapes;

   12 using Microsoft.Phone.Controls;

   13 using System.Xml;

   14 using System.Runtime.Serialization;

   15 

   16 

   17 namespace RESTServiceConsuming

   18 {

   19     public partial class MainPage : PhoneApplicationPage

   20     {

   21         public MainPage()

   22         {

   23             InitializeComponent();

   24             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   25 

   26             myButton.Click += new RoutedEventHandler(myButton_Click);

   27         }

   28 

   29         void myButton_Click(object sender, RoutedEventArgs e)

   30         {

   31             WebClient proxy = new WebClient();

   32             string strUri = http://localhost:50841/Service1.svc/GetData/&#8221;+myTxtBox.Text;

   33             proxy.OpenReadCompleted+=new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);

   34             proxy.OpenReadAsync(new Uri(strUri));

   35         }

   36 

   37         void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

   38         {         

   39 

   40             DataContractSerializer ser = new DataContractSerializer(typeof(string));

   41             String str = ser.ReadObject(e.Result).ToString();

   42             myTxtBoxDisplay.Text = str;          

   43 

   44 

   45         }

   46 

   47 

   48     }

   49 }


Press F5 to get the result


So, in this article I explained about how to consume a REST service in Win7 mobile app. In later articles I shall explain image and streaming through REST service in Win7 mobile app. Thanks for reading. I hope it was useful. Happy Coding.

Country Application for Window 7 mobile

Objective

In this article, I am going to show you a Country Application. User will select country from drop down and details of selected country will be displayed.

Expected Output


 

We will achieve this in three steps

  1. Create XML file for country and corresponding details. And create entity class.
  2. Design phone page
  3. Write code behind to handle selection change event and query XML file using LINQ
     

Very first create Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type.

 

Creating entity class and XML file as Data source

Right click and add a new item in the project. Select XML file. Then copy paste the below code in that XML file. This XML file contains details of countries. Give a proper name to XML file. Name I am giving here is CountryDetail.XML.

CountryDetail.xml

<?xml version=1.0encoding=utf-8 ?> <Countries>

 
 <Name>USA</Name>
 <Capital>Washinton DC</Capital>
 <Language>English</Language>

<Currency>Dollars</Currency>
</Country>

<Country>
<Name>England</Name>

<Capital>London </Capital>

<Language>English</Language>

<Currency>Pounds</Currency>

</Country>

<Country>

<Name>France</Name>

<Capital>Paris </Capital>

<Language>French</Language>

<Currency>Euro</Currency>

</Country>

<Country>

<Name>Germany</Name>

<Capital>Berlin </Capital>

<Language>German</Language>

<Currency>Mark</Currency>

</Country>

<Country>

<Name>Russia</Name>

<Capital>Moscow </Capital>

<Language>Russian</Language>

<Currency>Not Availaible</Currency>

</Country>

<Country>

<Name>Spain</Name>

<Capital>Madrid </Capital>

<Language>Spanish</Language>

<Currency>Not Availaible</Currency>

</Country>

<Country>

<Name>Turkey</Name>

<Capital>Ankara </Capital>

<Language>Not Availaible</Language>

<Currency>Not Availaible</Currency>

</Country>

<Country>

<Name>Norway</Name>

<Capital>Oslo </Capital>

<Language>Not Availaible</Language>

<Currency>Not Availaible</Currency>

</Country>

<Country>

<Name>Canada</Name>

<Capital>Ottawa </Capital>

<Language>English</Language>

<Currency>Dollars</Currency>

</Country>

<Country>

<Name>Mexico</Name>

<Capital>Mexico </Capital>

<Language>Spanish</Language>

<Currency>Peso</Currency>

</Country>

<Country>

<Name>China</Name>

<Capital>Bejing </Capital>

<Language>Chinnes</Language>

<Currency>Not Availaible</Currency>

</Country>

<Country>

<Name>Japan</Name>

<Capital>Tokyo </Capital>

<Language>Jaopanese</Language>

<Currency>Yen</Currency>

</Country>

<Country>

<Name>India</Name>

<Capital>New Delhi </Capital>

<Language>Hindi</Language>

<Currency>Ruppies</Currency>

</Country>

<Country>

<Name>Australia</Name>

<Capital>Canberra </Capital>

<Language>English</Language>

<Currency>Dollars</Currency>

</Country>

</Countries>

<Country>

 Now we will create an entity class corresponding to data source XML file. Right click and Add new class in the project. I am giving name of the class as Country.

Country.cs

    1 using System;

    2 using System.Net;

    3 using System.Windows;

    4 using System.Windows.Controls;

    5 using System.Windows.Documents;

    6 using System.Windows.Ink;

    7 using System.Windows.Input;

    8 using System.Windows.Media;

    9 using System.Windows.Media.Animation;

   10 using System.Windows.Shapes;

   11 

   12 namespace Countries

   13 {

   14     public class Country

   15     {

   16 

   17         public string Name { get; set; }

   18         public string Capital { get; set; }

   19         public string Language { get; set; }

   20         public string Currency { get; set; }

   21 

   22     }

   23 }

Design Phone Page


 

  1. Divide content grid in four rows
  2. In first row put a combo box. Inside combo box put an Item Template and a Data template. Inside Data template put a text box. And Bind this text box with the Name property of Country entity class.

     

  3. In second, third and fourth row put a stack panel with orientation horizontal. Put one text block and one text box. Text box will display corresponding details.

    Full XAML for design is as below,

    MainPage.xaml

<phoneNavigation:PhoneApplicationPage
x:Class=”Countries.MainPage”

xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

xmlns:phoneNavigation=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”

xmlns:d=http://schemas.microsoft.com/expression/blend/2008

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

mc:Ignorable=”d” d:DesignWidth=”480″ d:DesignHeight=”800″

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”>

<Grid x:Name=”LayoutRoot” Background=”{StaticResource PhoneBackgroundBrush}”>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<Grid x:Name=”TitleGrid” Grid.Row=”0″>

<TextBlock Text=”Windows 7 phone” x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

<TextBlock Text=”Country App” x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>

</Grid>

<Grid x:Name=”ContentGrid” Grid.Row=”1″ Background=”{StaticResource PhoneBackgroundBrush}” Margin=”30,0,0,0″>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<Grid x:Name=”ContentGrid2″>

<ComboBox x:Name=”cmbName” Height=”75″ SelectionChanged=”cmbName_SelectionChanged” Margin=”21,0,10,0″ Foreground=”Black”>

<ComboBox.ItemTemplate>

<DataTemplate>

<TextBlock Text=”{Binding Name}” />

</DataTemplate>

</ComboBox.ItemTemplate>

</ComboBox>

</Grid>

<Grid x:Name=”ContentGrid1″ Grid.Row=”1″>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto” />

<RowDefinition Height=”60″ />

<RowDefinition Height=”60″ />

<RowDefinition Height=”60″ />

</Grid.RowDefinitions>

<TextBlock x:Name=”txtCountryName” VerticalAlignment=”Top” Grid.Row=”0″ Height=”100″ FontSize=”72″ Text=”INDIA” Margin=”21,30,25,0″
HorizontalAlignment=”Stretch” />

<StackPanel Orientation=”Horizontal” Grid.Row=”1″>

<TextBlock Text=”Capital” Height=”50″ Width=”139″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>

<TextBox x:Name=”txtCapital” Height=”50″ Width=”336″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>
</StackPanel>
<StackPanel Orientation=”Horizontal” Grid.Row=”2″>
<TextBlock Text=”Language” Height=”50″ Width=”139″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>

<TextBox x:Name=”txtLanguage” Height=”50″ Width=”336″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>

</StackPanel>

<StackPanel Orientation=”Horizontal” Grid.Row=”3″>

<TextBlock Text=”Currency” Height=”50″ Width=”139″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>

<TextBox x:Name=”txtCurrency” Height=”50″ Width=”336″ VerticalAlignment=”Top” HorizontalAlignment=”Center” FontSize=”26″
/>

</StackPanel>

</Grid>

</Grid>

</Grid>
</phoneNavigation:PhoneApplicationPage>

Code Behind

Very first we will create a function. This function will query the XML file using LINQ to XML and return IEnumerable list of entity class Country.

 

 

This function is using LINQ to XML to query against XML file. Using XDocument class, I am loading the XML file. Then querying xml file using LINQ to XML and saving result in VAR.Then on the selection changed event of combo box calling the above function and checking for the selected country in combo box and binding. Do not forget to add reference of using
System.Xml.Linq;

 

So, full code is as below

MainPage.Xaml.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Net;

    5 using System.Windows;

    6 using System.Windows.Controls;

    7 using System.Windows.Documents;

    8 using System.Windows.Input;

    9 using System.Windows.Media;

   10 using System.Windows.Media.Animation;

   11 using System.Windows.Shapes;

   12 using Microsoft.Phone.Controls;

   13 using System.Xml.Linq;

   14 

   15 namespace Countries

   16 {

   17     public partial class MainPage : PhoneApplicationPage

   18     {

   19         //IEnumerable<Country> countrydt = null;

   20         public MainPage()

   21         {

   22             InitializeComponent();

   23 

   24             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   25             cmbName.SelectionChanged += new SelectionChangedEventHandler(cmbName_SelectionChanged);

   26 

   27             cmbName.ItemsSource = GetCountryDetails();

   28             cmbName.SelectedIndex = 0;

   29         }

   30 

   31 

   32 

   33        List<Country>  GetCountryDetails()

   34         {

   35             XDocument xmlDocument = XDocument.Load(“CountriesDetail.xml”);

   36 

   37           var   countrydt = from r in xmlDocument.Descendants(“Country”)

   38                             select new Country

   39                             {

   40                                 Capital = r.Element(“Capital”).Value,

   41                                 Currency = r.Element(“Currency”).Value,

   42                                 Language = r.Element(“Language”).Value,

   43                                 Name = r.Element(“Name”).Value,

   44 

   45                             };

   46           return countrydt.ToList();

   47 

   48         }     

   49 

   50        private void cmbName_SelectionChanged(object sender, SelectionChangedEventArgs e)

   51        {

   52 

   53            string cntName = ((Country)cmbName.SelectedItem).Name.ToString();

   54            List<Country> country = GetCountryDetails();

   55            foreach (Country c in country)

   56            {

   57 

   58                if (c.Name == cntName)

   59                {

   60                    txtCountryName.Text = c.Name;

   61                    txtCapital.Text = c.Capital;

   62                    txtCurrency.Text = c.Currency;

   63                    txtLanguage.Text = c.Language;

   64                }

   65            }

   66 

   67        }

   68 

   69 

   70     }

   71 }

   72 

Press F5 to run the application, change the country name and get the details

 

 

I hope this article was useful. Thanks for reading. Happy coding.

Image Viewer for Windows 7 Mobile

Objective

This article will give step to step illustration of creating a simple Image Viewer for Windows 7 mobile.

Step 1

Create a new Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type.

 

Step 2

In this step I will create an entity class for images to be displayed. This class will contain two properties. Filename property for the name of the image and image property for the image source. To create just right click on the project and add a class.

Photo.cs

    1 namespace PhotoApplication

    2 {

    3     public class Photo

    4     {

    5         public string FileName { get; set; }

    6         public ImageSource Image { get; set; }

    7 

    8     }

    9 }


Step 3

Design the page as below. Add below controls in content grid.

  1. Add a list box. Set the height as 520 and width as 450.
  2. Add Item Template for List box.
  3. Add Data template inside item template
  4. Inside Data template add a stack panel with horizontal orientation.
  5. Inside Stack panel put an Image control and bind source of this control to image property of Photo class.
  6. Inside Stack panel put a text block and bind text property of this control to Filename property of Photo class.

    MainPage.Xaml

<phoneNavigation:PhoneApplicationPage
x:Class=”PhotoApplication.MainPage”

xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

xmlns:phoneNavigation=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”

xmlns:d=http://schemas.microsoft.com/expression/blend/2008

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

mc:Ignorable=”d” d:DesignWidth=”480″ d:DesignHeight=”800″

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”>

<Grid x:Name=”LayoutRoot” Background=”{StaticResource PhoneBackgroundBrush}”>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<Grid x:Name=”TitleGrid” Grid.Row=”0″>

<TextBlock Text=”Windows 7 phone” x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

<TextBlock Text=”Media” x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>

</Grid>

<Grid x:Name=”ContentGrid” Grid.Row=”1″>

<ListBox x:Name=”lstImage” Width=”450″ Height=”520″>

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=”Horizontal”>

<Image
Source=”{Binding Image}” Width=”150″ Stretch=”Uniform” HorizontalAlignment=”Center” />

<TextBlock Text=”{Binding FileName}” TextWrapping=”Wrap” />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

</Grid>
</phoneNavigation:PhoneApplicationPage>

Step 4

Right click on project and add few images in project. I am adding 5 jpeg images. To add images right click on project and click add existing item then select images from local computer. See below the images added in project

Step 5

Right a function to convert filename into Bitmap image. The below function GetImage() will take filename as input and return an image source.

 

Right a function to initialize the collection of images. Function GetPhotos() will return an observableCollection of Photo class . This collection can directly be bind to the itemsource of list box control.

 On the Main Page load bind the itmesource to collection.

MainPage.Xaml.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Net;

    5 using System.Windows;

    6 using System.Windows.Controls;

    7 using System.Windows.Documents;

    8 using System.Windows.Input;

    9 using System.Windows.Media;

   10 using System.Windows.Media.Animation;

   11 using System.Windows.Shapes;

   12 using Microsoft.Phone.Controls;

   13 using System.Collections.ObjectModel;

   14 using System.Windows.Media.Imaging;

   15 

   16 namespace PhotoApplication

   17 {

   18     public partial class MainPage : PhoneApplicationPage

   19     {

   20         public MainPage()

   21         {

   22             InitializeComponent();

   23 

   24             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   25 

   26             lstImage.ItemsSource = GetPhotos();

   27 

   28         }

   29 

   30 

   31         public ObservableCollection<Photo> GetPhotos()

   32         {

   33             ObservableCollection<Photo> photos = new ObservableCollection<Photo>()

   34                                                  {

   35                                                      new Photo(){FileName=“A.jpg”,Image=GetImage(“A.jpg”)},

   36                                                      new Photo(){FileName=“B.jpg”, Image = GetImage(“B.jpg”)},

   37                                                      new Photo(){FileName=“C.jpg”,Image = GetImage(“C.jpg”)},

   38                                                      new Photo(){FileName=“D.jpg”,Image = GetImage(“D.jpg”)},

   39                                                      new Photo(){FileName =“E.jpg”,Image =GetImage(“E.jpg”)}

   40                                                  };

   41             return photos;

   42 

   43         }

   44 

   45         private ImageSource GetImage(string fileName)

   46         {

   47             return new BitmapImage(new Uri(fileName, UriKind.Relative));

   48         }   

   49 

   50 

   51     }

   52 }

   53 

Press F5 to get the output

 

Thanks for reading. I hope it was useful. Happy Coding.

Media player for Windows 7 Mobile

Objective

This article will give step to step illustration of creating a simple media application for Windows 7 mobile.

Step 1

Create a new Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type.

 

Step 2

Design page.

  1. Divide content grid in two rows
  2. In first row put a media element control
  3. In second row put a button.

     MainPage.Xaml

<phoneNavigation:PhoneApplicationPage
x:Class=”PhotoApplication.MainPage”

xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

xmlns:phoneNavigation=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”

xmlns:d=http://schemas.microsoft.com/expression/blend/2008

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

mc:Ignorable=”d” d:DesignWidth=”480″ d:DesignHeight=”800″

FontFamily=”{StaticResource PhoneFontFamilyNormal}”

FontSize=”{StaticResource PhoneFontSizeNormal}”

Foreground=”{StaticResource PhoneForegroundBrush}”>

<Grid x:Name=”LayoutRoot” Background=”{StaticResource PhoneBackgroundBrush}”>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<!–TitleGrid is the name of the application and page title–>

<Grid x:Name=”TitleGrid” Grid.Row=”0″>

<TextBlock Text=”Windows 7 phone” x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

<TextBlock Text=”Media” x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>

</Grid>

<!–ContentGrid is empty. Place new content here–>

<Grid x:Name=”ContentGrid” Grid.Row=”1″>

<Grid.RowDefinitions>

<RowDefinition Height=”*” />

<RowDefinition Height=”Auto” />
 </Grid.RowDefinitions>
<Button x:Name=”btnPlay” Content=”Play” Height=”50″ Width=”100″ Grid.Row=”1″ />

<MediaElement x:Name=”mediactrl” HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Stretch=”Uniform” Grid.Row=”0″/>

</Grid>

</Grid>
</phoneNavigation:PhoneApplicationPage>

Step 3

Right click on project and add an existing .wmv in project. I am adding a.wmv file here.

Step 4

Now in code behind just write below code to play the media file

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Net;

    5 using System.Windows;

    6 using System.Windows.Controls;

    7 using System.Windows.Documents;

    8 using System.Windows.Input;

    9 using System.Windows.Media;

   10 using System.Windows.Media.Animation;

   11 using System.Windows.Shapes;

   12 using Microsoft.Phone.Controls;

   13 

   14 namespace PhotoApplication

   15 {

   16     public partial class MainPage : PhoneApplicationPage

   17     {

   18         public MainPage()

   19         {

   20             InitializeComponent();

   21 

   22             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   23             btnPlay.Click += new RoutedEventHandler(btnPlay_Click);

   24         }

   25 

   26         void btnPlay_Click(object sender, RoutedEventArgs e)

   27         {

   28 

   29             mediactrl.Source = new Uri(“a.wmv”, UriKind.Relative);

   30             mediactrl.Play();

   31         }

   32 

   33 

   34     }

   35 }

Press F5 to get output

 

I hope this article was useful. Thanks for reading. Happy coding.