Win Visual Studio 2010 with MSDN subscription in 5 minutes

Winner Announced :

Name:Mamta Dalal
City: Mumbai, India. Congrats Mamta …. I hope you will take this and write more articles to help the community ..

Closing date: 25th July 2010

Winner announced :  26th July 2010  [1 winners]

In order to celebrate Visual studio 2010 and .Net 4.0 launch. Microsoft is giving away “Visual Studio ultimate with MSDN activation “.

Image taken from MSIGEEK blog MSIGEEK

As being MVP, I got an opportunity to give away this subscription card to deserving developers.  So, here is a contest to celebrate Visual Studio 2010 launch.

To win this contest, you have to answer 3 simple questions

1. Why do you deserve Visual Studio 2010 MSDN Activation card?

……………………………………………….

2. If you win, what application you would love to make?

…………………………………………………………….

3. How this blog can be improved better?

……………………………………………………………….

Rules:


  1. Register your Name, Email address and City in comment of this blog.

Format of your comment would be like below,

Name : Dhananjay Kumar

Email : Dhananjay.kumar@abc.com

City  :  XXXXXXXXXXXXXXXXXXX

I have participated in this and your comment.


2. Send your answer to Dhananjay.kumar@ust-global.com

Format of your answer would be,

Subject:  MSDN Subscription answers

Q 1 :                            ….. Your answer …..

Q2:                             ………….Your answer ……

Q3:.                           …………….. Your answer……..

Note:  IF you are sending answer in mail and not registering yourself in comment then you will not be considered.

Understanding Web Role and Worker Roles through images

Objective

In this article, I am going to explain about Web Role and Worker role using images.

Windows Azure mainly helps as a service

1. Storage

2. Computation

3. Mange the application.

clip_image002

These three functions of Windows Azure , make sure application is

1. Running

2. Scalable

3. Secure

4. Maintainable

5. Reliable

clip_image004

So , to perform all functions there are different service in window azure

clip_image006

Compute service can performed with the instances of the application

Web Role Instance

clip_image008

clip_image010

clip_image012

Worker Role Instance

clip_image014

clip_image016

Hosting WCF service in Windows Azure and consuming in Window 7 phone app

Objective

This article will give step by step walkthrough of hosting a WCF service in windows azure and then consuming that in windows7 phone application.

Expected output

clip_image001

Step 1

Open Visual Studio 2010 as an administrator. Select File -> New -> Cloud Service. Click on Windows Azure cloud service template. Give name of the cloud service. After creating the cloud service select the type of role. There are many roles to choose from. For our purpose, we will choose ASP.Net Web Role.

clip_image002

Now examine the solution explorer. There should be 2 projects. Called WebRole1 and CloudServices1. These names may different basis of the name you given at time of creation of cloud service project in step1.

clip_image004

Step 2

Creating the WCF Service

Right click on WebRole1 project and add new item then select WCF service from the WEB project template.

Modify contract and service implementation as per you. For my purpose , I am making it simple service as below.

Contract

IService1.svc

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WebRole1

{

[ServiceContract]

public interface IService1

{

[OperationContract]

string GetMessage();

}

}

Service Implementation

Service1.svc.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WebRole1

{

public class Service1 : IService1

{

public string GetMessage()

{

return "Hello From Cloud to Windows7 phone ";

}

}

}

Change the Binding to basicHttpBinding. Make sure to do this.

Note : make sure you have set WebRole1 as startup project .

Step 3

Running on Local Development Fabric (Press F5)

Run the application. This will run on the local development fabric. When we install azure SDK, local development fabric got installed. And when we run the cloud service local development fabric get started and host the application. This provides exactly the same environment as of azure in the cloud. This local development fabric could be used to debug the application before hosting into the cloud.

Running the application on local development fabric

See the URL in address bar of browser, in my case this is

http://localhost:9375/Service1.svc

clip_image006

Step 4

Publishing to cloud (azure)

Right Click on Cloud Service 1 project and select Publish.

clip_image008

It will open the azure site and ask for the login.

clip_image010

If first time, you are login to azure site for publishing browse to account section to redeem your token.

clip_image012

Now either create a project for windows azure or select existing project. I have already a project created with the name of DJProject . I am selecting that.

clip_image014

Since, I have already hosted in the project before. So I am getting the upgrade option. First time, you won’t get upgrade option. First time on creation of Windows azure project it will ask you to give an URL for your project . Just give an URL, which you will use to access your application across.

clip_image016

Click on upgrade option . It will ask for the package file and config file. Browse to CloudService1\bin\publish folder. CloudService1 is name of the application. It may be different in your case , depending on what name you have given in step1.

clip_image017

clip_image019

After uploading package and configuration file , give a label name and click on deploy.

clip_image021

It will take some time for deployment. After successfully deployment you will see a green sign against Web Role saying it is in ready state. You could directly click on Web site URL to test your application on cloud.

clip_image023

Now when you open the URL , you will get the same page as output you got on the local development fabric. And now you successfully hotsed in cloud.

clip_image025

Step 4

Consuming the service hosted in Windows Azure in Windows 7 phone application

1. Create a Windows 7 phone application

clip_image027

2. Design the content grid as below; Put a button and a text block.

clip_image028

3. While adding service reference first adds URL of the service hosted on local development fabric. Copy the URL from Step 3 and right click on Console application and select Add service reference. In service URL paste the URL from step 3.

clip_image029

clip_image030

After clicking OK, you can see ServiceReference1 is being added to the project.

4. Call the service hosted in local development fabric like below on the click event of button

clip_image032

Output

clip_image001[1]

Open the ServiceReferenceClient.config and modify the address to address of service in azure.

clip_image034

Again run the application and you will get the same output.

clip_image001[2]

For your reference Full source code is given below,

MainPage.xaml

<phoneNavigation:PhoneApplicationPage

x:Class="WindowsPhoneApplication5.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" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>

<TextBlock Text="WCF" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>

</Grid>

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

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

<Button x:Name="btnGetData"

Height="100"

Content="Get Data"

Margin="34,27,64,525" />

<TextBlock x:Name="txtData"

Height="100" FontStyle="Italic"

FontSize="20"

Margin="34,276,49,276" />

</Grid>

</Grid>

</phoneNavigation:PhoneApplicationPage

MainPage.Xaml.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Phone.Controls;

using WindowsPhoneApplication5.ServiceReference1;

namespace WindowsPhoneApplication5

{

public partial class MainPage : PhoneApplicationPage

{

public MainPage()

{

InitializeComponent();

SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

btnGetData.Click += new RoutedEventHandler(btnGetData_Click);

}

void btnGetData_Click(object sender, RoutedEventArgs e)

{

//throw new NotImplementedException();

Service1Client proxy = new Service1Client();

proxy.GetMessageCompleted += new EventHandler<GetMessageCompletedEventArgs>(proxy_GetMessageCompleted);

proxy.GetMessageAsync();

}

void proxy_GetMessageCompleted(object sender, GetMessageCompletedEventArgs e)

{

txtData.Text = e.Result.ToString();

}

}

}

Conclusion

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

Walkthrough on Creating WCF Data Service (ODATA) and Consuming in Windows 7 Mobile application

Note : Now you can consume ODATA in very simpler way  updated post can be read  at below link

https://debugmode.net/2011/06/11/consuming-odata-in-windows-phone-7-1-or-mango-phone/

 

Objective

In this article, I will discuss

1. How to create WCF Data Service

2. How to remove digital signature on System.Data.Service.Client and add in Windows7 phone application.

3. Consume in Windows 7 phone application and display data.

You can see three video here:

Creating WCF Data Service:

http://dhananjaykumar.net/2010/06/08/wcfdataservicevideo/

Fixing the Bug of OData Client library for Windows7 Phone: http://dhananjaykumar.net/2010/07/01/videofixingodataclientlibraryissue/

Consuming WCF Data Service in Windows7 Phone :

http://dhananjaykumar.net/2010/07/06/videodatainw7phone/

Expected Output

clip_image001

Flow Diagram

clip_image002

Step 1: Create WCF Data Service

Let us say, we have a table called Student of below structure below in our data base

clip_image003

In Student table RollNumber is a primary key.

Let us create WCF Data Service which will expose the above table as REST service

Create a Web Application

Create a new project and select ASP.Net Web Application project template from Web tab. Give a meaning full name to the web application.

clip_image005

Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

1. Using ADO.Net Entity model.

2. Using LINQ to SQL class.

3. Custom Data Model.

For our purpose, I am going to use ADO.Net Entity model to create the data model. So to create an entity model

1. Right click on web application and add a new item

2. Select ADO.Net Entity model from Data tab.

clip_image007

3. Since we have table in data base. So we are going to choose option, select from database.

clip_image008

4. Either choose the data base from drop down or create a new data connection.

clip_image009

In above connection string StudentDBEntities is name of the connection string. If we want, we can change this connection string as per our requirement.

If your required data base is not listed in drop down then, you can create a new data connection. To create new data connection click on New Connection

clip_image010

You can give the data base server name and press refresh. After pressing Refresh, you can choose the data base from the drop down. After selecting the data base click on Test Connection to test connection established successfully or not?

5. Select tables, views and stored procedure from data base you want to make as the part of your data model. Since we are having only one table so we are selecting one table.

clip_image011

If you want you can change name of the data model. By default it is name of the data base appended by the term model. Click on Finish button to complete and create the data model.

6. Now we can see that StudentDataModel.edmx has been created in the designer.

clip_image012

Since there is only one table, so there is only one table model at design surface.

Now we have created the data model which can be exposed as WCF Data Service. Now you can see in solution explorer, you have StudentModel.edmx and StdentModel.Designer.cs files.

clip_image013

Creating WCF Data Service

1. Right click on Web Application project and add a new item.

2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.

clip_image015

3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer. When we click on .svc.cs file, we can see the code generated for us.

clip_image017

Very first we need to put data source name. To do so uncomment the first commented line and put the data source name. In our case name of the model, which we created in 2nd step is the data source. Our data source name is StudentDBEntities

clip_image018

Now we need to set access rules for entity or entity set. Since we have only one table, so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source we could put *.

clip_image020

clip_image021

So we are setting the access rule that, on the entity in data source perform all the operations.

Run the WCF Data Service

Just press F5 to run the WCF Data Service. Data Service will be hosted in the default ASP.Net server called Cassini.

On running you can see, one table is listed. That table is Student

clip_image023

The above is the data in ATOM message format.

Note: If your browser is not showing the expected result, make sure Feed reading of browser is off. To do from menu of IE and select tool and then Internet Option then Content

clip_image024

clip_image025

So, to fetch all the records of entity Students

http://b263ltrv:3803/WcfDataService1.svc/Students

clip_image027

Step 2: Create Proxy of WCF Data Service

Download the ODATA client library for Windows 7 phone from below link and save the dll somewhere.

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=b251b247-70ca-4887-bab6-dccdec192f8d

1. Open command prompt in administrator mode.

2. Navigate to folder C:\Windows\Microsoft.Net\FrameWork\V4.0. Version of framework may vary depending on .Net framework, you are working on.

3. Once navigated to this particular folder, run the below command to create proxy class. We will add this proxy class in Windows 7 mobile application.

4. Run the below command in command prompt to create the proxy class

clip_image028

Explanation of command

a. There is space between all /out , /uri and /version

b. We are redirecting the output to D drive and Abc folder. So make sure ABC folder exist in the D drive.

c. Student.cs is name of proxy class. You can give any name of your choice here. Once command will run successfully, you will get Student.cs class in ABC folder of D drive.

d. After uri tag give the uri of wcf data service, which you created in previous step.

So, after successful execution of this command, you will get below message in command prompt.

clip_image030

Once you navigate to D drive and ABC folder, you will see Student.cs file there. Make sure the path you are giving in OUT parameter, that folder exists and you will get your proxy class in that particular folder.

Step 3: Removing digital signature from ODATA Client library for Windows7 phone

Note: I would like to thank Tim for his solution and this article has been referred to his this http://timh.me/bAfFvh

You can see video for this step

http://dhananjaykumar.net/2010/07/01/videofixingodataclientlibraryissue/

Background

When you download ODATA or WCF Data Service client library for Windows 7 phone and extract the System.Data.Service.Client.dll to some location and add this reference to your project. After adding this reference, when you run your application in emulator, you get DEPLOYEMNT FAILED error. This article, will explain how to fix this bug and continue using WCF Data Service client library for Windows 7 phone application.

Assumption

I have assumed here that you have downloaded, ODATA or WCF Data Service client library for Windows 7 phone from below line

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=b251b247-70ca-4887-bab6-dccdec192f8d

After download from here, run this, you will get the below screens

clip_image031

clip_image032

Extract the dll in a particular directory. Let us say you are extracting that in D:\DemoFolder. So, in this folder, you will have below three files.

clip_image033

So, here you are having System.Data.Service.Client.dll library. You need to add this as reference in your Windows7 Phone application to Consume WCF Data Service.

Working

Now when you add this reference in your windows7 phone application and try to run the application, you will find you are not getting any compile time error but your application is not loading. You may get below error message. You will get deployment error message.

clip_image034

clip_image035

Solution

To solve this deployment error, you need to follow below steps

1. Download power shell script from http://storage.timheuer.com/wp7ctpfix.ps1

2. Save the power script in the same folder where you have put your DLL.

3. Open the power script window, and run the script. see the video here

Command to be run

1. Navigate to folder, where you copied and pasted ODATA client library DLL and Power shell script, you downloaded in previous step.

2. Once you navigate to folder, you will able to see power scrip file you downloaded in previous steps.

Now just run the below command

.\wp7ctpfix.ps1 .\System.Data.Services.Client.dll

clip_image037

Now a new dll will get created in the same folder. Add this dll in your Windows7 phone application and you would be able to use the client library

Step 4: Consume Service in Windows 7 phone

1. Create a new Windows Phone Application

clip_image039

2. Right click on the project and add existing item. Then navigate to folder where you created WCF Data Service proxy class. In our case it is Student.cs. We created this in step 2.

clip_image040

3. Right click on the project and add reference. Navigate to folder where you saved System.Data.Service.Client dll after removing the digital signature. (See the step 3)

clip_image041

4. Create entity class. We have to create StudentEntityclass

clip_image043

5. Design the phone page. There will be a button and a list box. We are binding the list box with StudentEntity class, we created in previous step.

clip_image045

6. Declare the global variables. And make sure you have added the namespace System.Data.Service.Client

clip_image046

7. Initializes them inside constructor of MainPage

clip_image048

clip_image049

8. On click event of the button

clip_image051

Here asynchronously we are calling the function DataLoaded

DataLoaded function will look like

clip_image053

Here, making the List<StudentEntity > as data context for the ListBox.

So when you run the Windows 7 phone application in emulator, you will get below output

clip_image001[1]

For Reference full source code is as below,

MainPage.Xaml

<phoneNavigation:PhoneApplicationPage

x:Class=“ConsumingODATA.MainPage”

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

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

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

xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

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=“ODATA” 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=“4*” />

</Grid.RowDefinitions>

<Button x:Name=“myButton” Height=“100” Content=“Get Data” Grid.Row=“0” Background=“Azure”

Foreground=“Black”/>

<ListBox Grid.Row=“1” x:Name=“MyList”

ItemsSource=“{Binding}” Height=“458”

HorizontalAlignment=“Left” Margin=“20,39,0,0” VerticalAlignment=“Top” Width=“435” >

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=“Horizontal” >

<TextBlock Text=“{Binding RollNo}” Foreground=“Red” Margin=“20” />

<TextBlock Text=“{Binding Name}” Margin=“20” />

<TextBlock Text=“{Binding Subject}” Margin=“20” />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

</Grid>

</phoneNavigation:PhoneApplicationPage>


MainePage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Phone.Controls;

using System.Data.Services.Client ;

using StudentDBModel;

namespace ConsumingODATA

{

public partial class MainPage : PhoneApplicationPage

{

StudentDBEntities studentEntities = null ;

List<Student> lstStd  = null ;

List<StudentEntity> lstResultStd = null ;

public MainPage()

{

InitializeComponent();

SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

studentEntities = new StudentDBEntities(new Uri (http://b263ltrv:3803/WcfDataService1.svc/&#8221;));

lstResultStd = new List<StudentEntity>();

lstStd = new List<Student>();

myButton.Click += new RoutedEventHandler(myButton_Click);

}

void myButton_Click(object sender, RoutedEventArgs e)

{

var query = studentEntities.CreateQuery<Student>(“Students”);

query.BeginExecute(ar=>

{

GetData(ar);

},query);

}

public void GetData(IAsyncResult result)

{

DataServiceQuery<Student> query = result.AsyncState as DataServiceQuery<Student>;

lstStd = query.EndExecute(result).ToList();

Dispatcher.BeginInvoke(()=>

{

foreach(var r in lstStd)

{

lstResultStd.Add(new StudentEntity{RollNo=r.RollNumber ,

Name = r.Name ,

Subject = r.Subject });

}

this.MyList.DataContext = lstResultStd ;

});

}

}

}

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

Video on consuming WCF Data Service (OData) in Windows 7 Phone Application

MainPage.Xaml

<phoneNavigation:PhoneApplicationPage

x:Class=“ConsumingODATA.MainPage”

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

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

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

xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

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=“ODATA” 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=“4*” />

</Grid.RowDefinitions>

<Button x:Name=“myButton” Height=“100” Content=“Get Data” Grid.Row=“0” Background=“Azure”

Foreground=“Black”/>

<ListBox Grid.Row=“1” x:Name=“MyList”

ItemsSource=“{Binding}” Height=“458”

HorizontalAlignment=“Left” Margin=“20,39,0,0” VerticalAlignment=“Top” Width=“435” >

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=“Horizontal” >

<TextBlock Text=“{Binding RollNo}” Foreground=“Red” Margin=“20” />

<TextBlock Text=“{Binding Name}” Margin=“20” />

<TextBlock Text=“{Binding Subject}” Margin=“20” />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

</Grid>

</phoneNavigation:PhoneApplicationPage>

MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Phone.Controls;

using System.Data.Services.Client ;

using StudentDBModel;

namespace ConsumingODATA

{

public partial class MainPage : PhoneApplicationPage

{

StudentDBEntities studentEntities = null ;

List<Student> lstStd  = null ;

List<StudentEntity> lstResultStd = null ;

public MainPage()

{

InitializeComponent();

SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

studentEntities = new StudentDBEntities(new Uri ("http://b263ltrv:3803/WcfDataService1.svc/"));

lstResultStd = new List<StudentEntity>();

lstStd = new List<Student>();

myButton.Click += new RoutedEventHandler(myButton_Click);

}

void myButton_Click(object sender, RoutedEventArgs e)

{

var query = studentEntities.CreateQuery<Student>("Students");

query.BeginExecute(ar=>

{

GetData(ar);

},query);

}

public void GetData(IAsyncResult result)

{

DataServiceQuery<Student> query = result.AsyncState as DataServiceQuery<Student>;

lstStd = query.EndExecute(result).ToList();

Dispatcher.BeginInvoke(()=>

{

foreach(var r in lstStd)

{

lstResultStd.Add(new StudentEntity{RollNo=r.RollNumber ,

Name = r.Name ,

Subject = r.Subject });

}

this.MyList.DataContext = lstResultStd ;

});

}

}

}

StudentEntity.cs

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace ConsumingODATA

{

public class StudentEntity

{

public string RollNo { get; set; }

public string Name { get; set; }

public string Subject { get; set; }

}

}

Student.cs

//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:4.0.30319.1

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------

// Original file name: Student.cs

// Generation date: 7/5/2010 6:06:44 PM

namespace StudentDBModel

{

/// <summary>

/// There are no comments for StudentDBEntities in the schema.

/// </summary>

public partial class StudentDBEntities : global::System.Data.Services.Client.DataServiceContext

{

/// <summary>

/// Initialize a new StudentDBEntities object.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public StudentDBEntities(global::System.Uri serviceRoot) :

base(serviceRoot)

{

this.OnContextCreated();

}

partial void OnContextCreated();

/// <summary>

/// There are no comments for Students in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public global::System.Data.Services.Client.DataServiceQuery<Student> Students

{

get

{

if ((this._Students == null))

{

this._Students = base.CreateQuery<Student>("Students");

}

return this._Students;

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private global::System.Data.Services.Client.DataServiceQuery<Student> _Students;

/// <summary>

/// There are no comments for Students in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public void AddToStudents(Student student)

{

base.AddObject("Students", student);

}

}

/// <summary>

/// There are no comments for StudentDBModel.Student in the schema.

/// </summary>

/// <KeyProperties>

/// RollNumber

/// </KeyProperties>

[global::System.Data.Services.Common.DataServiceKeyAttribute("RollNumber")]

public partial class Student

{

/// <summary>

/// Create a new Student object.

/// </summary>

/// <param name="rollNumber">Initial value of RollNumber.</param>

/// <param name="name">Initial value of Name.</param>

/// <param name="subject">Initial value of Subject.</param>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public static Student CreateStudent(string rollNumber, string name, string subject)

{

Student student = new Student();

student.RollNumber = rollNumber;

student.Name = name;

student.Subject = subject;

return student;

}

/// <summary>

/// There are no comments for Property RollNumber in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string RollNumber

{

get

{

return this._RollNumber;

}

set

{

this.OnRollNumberChanging(value);

this._RollNumber = value;

this.OnRollNumberChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _RollNumber;

partial void OnRollNumberChanging(string value);

partial void OnRollNumberChanged();

/// <summary>

/// There are no comments for Property Name in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string Name

{

get

{

return this._Name;

}

set

{

this.OnNameChanging(value);

this._Name = value;

this.OnNameChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _Name;

partial void OnNameChanging(string value);

partial void OnNameChanged();

/// <summary>

/// There are no comments for Property Subject in the schema.

/// </summary>

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

public string Subject

{

get

{

return this._Subject;

}

set

{

this.OnSubjectChanging(value);

this._Subject = value;

this.OnSubjectChanged();

}

}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]

private string _Subject;

partial void OnSubjectChanging(string value);

partial void OnSubjectChanged();

}

}

Video on Picture Gallery for Windows 7 Phone using WCF REST Service

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

10 namespace PictureService2

11 {

12

13 [ServiceContract]

14 public interface IService1

15 {

16 [OperationContract]

17 [WebGet(UriTemplate="/GetFiles")]

18 List<string> GetFilesName();

19

20

21 [OperationContract]

22 [WebGet(UriTemplate="/GetImage/{imageName}")]

23 Stream GetImage(string imageName);

24

25

26 }

27

28

29

30 }

31


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

10 namespace PictureService2

11 {

12

13 public class Service1 : IService1

14 {

15

16 public List<string> GetFilesName()

17 {

18 DirectoryInfo info = new DirectoryInfo(@"D:\Images");

19 var res = from r in info.GetFiles() select r.Name.Split(".".ToCharArray())[0];

20 return res.ToList();

21 }

22 public Stream GetImage(string imageName)

23 {

24 FileStream fs = null;

25 string name = string.Format(@"D:\Images\{0}.jpg", imageName);

26 fs = File.OpenRead(name);

27 WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

28 return fs;

29 }

30

31 }

32 }

33

Windows 7 phone Application

MainPage.xaml


1 <phoneNavigation:PhoneApplicationPage

2 x:Class="PictureGallery.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

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

14 <Grid.RowDefinitions>

15 <RowDefinition Height="Auto"/>

16 <RowDefinition Height="*"/>

17 </Grid.RowDefinitions>

18

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

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

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

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

23 </Grid>

24

25 <!--ContentGrid is empty. Place new content here-->

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

27 <Grid.RowDefinitions>

28 <RowDefinition Height="*"/>

29 <RowDefinition Height="3*"/>

30 </Grid.RowDefinitions>

31 <StackPanel Orientation="Horizontal" Grid.Row="0">

32 <Button x:Name="myButton" Content="GetImagesName" Height="50" />

33 <ComboBox x:Name="cmbName" Height="50" Width="211" Foreground="Black" />

34 </StackPanel>

35 <Image Grid.Row="1" x:Name="myImage" Height="Auto" Width="Auto" />

36 </Grid>

37 </Grid>

38

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.Runtime.Serialization;

14 using System.Windows.Media.Imaging;

15

16

17 namespace PictureGallery

18 {

19 public partial class MainPage : PhoneApplicationPage

20 {

21 public MainPage()

22 {

23 InitializeComponent();

24

25 SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

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

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

28

29 }

30

31 void cmbName_SelectionChanged(object sender, SelectionChangedEventArgs e)

32 {

33 if (cmbName.SelectedIndex != -1)

34 {

35 string serviceURI = string.Format("http://localhost:19612/Service1.svc/GetImage/{0}", cmbName.SelectedItem.ToString());

36 WebClient proxy1 = new WebClient();

37 proxy1.OpenReadCompleted += new OpenReadCompletedEventHandler(GetImage);

38 proxy1.OpenReadAsync(new Uri(serviceURI));

39 }

40 }

41

42 void GetImage(object sender, OpenReadCompletedEventArgs e)

43 {

44

45 BitmapImage img = new BitmapImage();

46 img.SetSource(e.Result);

47 myImage.Source = img;

48

49 }

50

51 void myButton_Click(object sender, RoutedEventArgs e)

52 {

53 cmbName.Items.Clear();

54 cmbName.SelectedIndex = -1;

55 WebClient proxy = new WebClient();

56 proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(GetFileName);

57 proxy.OpenReadAsync(new Uri("http://localhost:19612/Service1.svc/GetFIles"));

58

59 }

60

61 void GetFileName(object sender, OpenReadCompletedEventArgs e)

62 {

63

64 DataContractSerializer serz = new DataContractSerializer(typeof(List<string>));

65 List<string > fileNames  = (List<string>) serz.ReadObject(e.Result);

66 cmbName.ItemsSource = fileNames;

67 }

68

69

70

71

72 }

73 }

74

75

76

77