Mini Browser for Windows 7 Mobile

Objective

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

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

Step 2

Right click on project and add reference of Microsoft.Phone.Controls.WebBrowser

Step 3

On the XAML page add namespace

xmlns:wb=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.WebBrowser”

Step 4

Design page.

  1. Divide content grid in two rows
  2. In first row put a textbox and button.
  3. In second row put Web Browser control.

    MainPage.Xaml

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

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

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
 xmlns:phoneNavigation=”clrnamespace:Microsoft.Phone.Controls;

 assembly=Microsoft.Phone.Controls.Navigation”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:wb=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.WebBrowser”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
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=”Browser” x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>
</Grid>
<Grid x:Name=”ContentGrid” Grid.Row=”1″>
<Grid.RowDefinitions>
<RowDefinition Height=”80″/>
<RowDefinition Height=”*”/>
</Grid.RowDefinitions>
<StackPanel Orientation=”Horizontal” Grid.Row=”0″>
<TextBox Height=”31″ Name=”textBox1″ Text=”” Width=”404″ />
<Button x:Name=”btnGo” Content=”GO” Height=”70″ Width=”85″ />
</StackPanel>
<wb:WebBrowser x:Name=”myBrowser” Grid.Row=”1″ Margin=”10″/>
</Grid>
</Grid>
</phoneNavigation:PhoneApplicationPage>

Step 5

Now in code behind just navigate in click event of button

    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 namespace browserforWin7Phone

   14 {

   15     public partial class MainPage : PhoneApplicationPage

   16     {       

   17         public MainPage()

   18         {

   19 

   20             InitializeComponent();

   21             SupportedOrientations = SupportedPageOrientation.Portrait;         

   22             btnGo.Click += new RoutedEventHandler(btnGo_Click);

   23         }

   24 

   25         void btnGo_Click(object sender, RoutedEventArgs e)

   26         {          

   27             Uri uri = new Uri(textBox1.Text, UriKind.Absolute);

   28             if (uri != null)

   29                 myBrowser.Navigate(uri);

   30         }

   31     }

   32 }

Press F5 to get the output. In textbox give the site URL and press GO button.

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

A Silverlight Twitter Client for Windows 7 Mobile Part #1

Objective

In this article I will show how to make a basic twitter client for Windows 7 mobile. This is part 1 of the series. In this part, I will show only how to read statues of given user. In further parts, I will show Tweet, Re tweet and Direct Message functionalities.

Follow the below steps

 Step 1 From Start menu select Microsoft Visual Studio 2010 express edition


 
 
 
 
 
 

Step 2

From File menu select New Project. From Silverlight for Windows phone tab select Windows Phone application project type.


Once selecting that a new project will get created with below solution structure

Make sure in Debug option Windows Phone7 Emulator is selected. If it is selected to Windows Phone 7 Device then Visual studio will deploy the application to mobile device directly.

 

Step 3

Design phone page

  1. Change text of title text box to “Twitter for Windows 7 Phone “
  2. Divide content grid in two rows.
  3. In first row put a stack panel with horizontal orientation.
  4. Inside stack panel put a textbox and button. User will input twitter username in textbox. Button click (Touch event in real device) will fetch status of entered user name.
  5. Style for both textbox and button is from the default static resources PhoneTextBoxStyle and PhoneButtonBase.
  6. In second row of content grid put another grid and divide this grid in two rows again.
  7. In first row put a list box with style PhoneListBox
  8. Inside Item template put a data template.
  9. Inside data template put a stack panel.
  10. Put three textboxes and one image control. These controls I will bind with the properties of the tweet entity class.
  11. In second row of grid put a text block and a display message.

MainPage.xaml

<phoneNavigation:PhoneApplicationPage x:Class=”TwiiterClient.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

xmlns:phoneNavigation=”clrnamespace: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=”Green”>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto”/>

<RowDefinition Height=”*”/>

</Grid.RowDefinitions>

<Grid x:Name=”TitleGrid” Grid.Row=”0″>
<TextBlock Text=”Twitter for Windows 7 Phone” x:Name=”Twitter” Style=”{StaticResourcePhoneTextPageTitle1Style}”/>

<TextBlock Text=”Twitter” x:Name=”Windows7Twitter” Style=”{StaticResource PhoneTextPageTitle2Style}”/>

</Grid>

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

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

<Grid.RowDefinitions>

<RowDefinition Height=”Auto” />

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<StackPanel Grid.Row=”0″ Orientation=”Horizontal” HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Margin=”0,0,0,0″>

<TextBox x:Name=”txttweet” Height=”10″ Width=”325″ HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” Opacity=”10″ Style=”{StaticResource PhoneTextBoxStyle}” />

<Buttonx:Name=”btnTwiiter” Content=”Tweets” Height=”60″ Width=”150″ Style=”{StaticResource PhoneButtonBase}”/>

</StackPanel>

<Grid Grid.Row=”1″>

<Grid.RowDefinitions>

<RowDefinition Height=”*”/>

<RowDefinition Height=”Auto” />

</Grid.RowDefinitions>

<ListBox Grid.Row=”0″ Height=”Auto” Margin=”10,0,0,0″ Name=”listBox1″ Width=”476″ Style=”{StaticResource PhoneListBox}”>

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=”Horizontal” Height=”132″>

<Image Source=”{Binding ImageSource}” Height=”73″ Width=”73″ VerticalAlignment=”Top” Margin=”0,10,8,0″/>

<StackPanel Width=”370″>

<TextBlock Text=”{Binding UserName}” Foreground=”#FFC8AB14″ FontSize=”28″ />

<TextBlock Text=”{Binding Message}” TextWrapping=”Wrap” FontSize=”24″ />

<TextBlock Text=”{Binding CreatedAt}” FontSize=”20″ Foreground=”#FFC8AB14″ />
</StackPanel>
</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

<TextBlock Text=”Developed by Dhananjay Kumar at MIT UST Global” Style=”{StaticResource PhoneTextAccentStyle}” Grid.Row=”1″/>

</Grid>

</Grid>

</Grid>
 </phoneNavigation:PhoneApplicationPage>
 

 Step 4
Creating an twitter entity class

Right click and add a class in project. I have given name here twitter to the class. I am going to work on only 4 data exposed by twitter API. So entity class is as below

Twitter.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 TwiiterClient

   13         {

   14             public class Twitter

   15             {

   16                 public string UserName { get; set; }

   17                 public string Message { get; set; }

   18                 public string ImageSource { get; set; }

   19                 public string CreatedAt { get; set; }

   20 

   21             }

   22         }

In this step, I will be using Twitter API. And will apply LINQ to XML to fetch the desired data. Twitter API will be returning an XML.

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 TwiiterClient

   16 {

   17     public partial class MainPage : PhoneApplicationPage

   18     {

   19         public MainPage()

   20         {

   21             InitializeComponent();

   22 

   23             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   24             btnTwiiter.Click += new RoutedEventHandler(btnTwiiter_Click);

   25 

   26         }

   27 

   28         void btnTwiiter_Click(object sender, RoutedEventArgs e)

   29         {

   30             WebClient client = new WebClient();

   31             client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

   32             client.DownloadStringAsync(new Uri(http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=&#8221; + txttweet.Text));

   33         }

   34 

   35         void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

   36         {

   37 

   38             if (e.Error != null)

   39                 return;

   40             XElement xmlTweets = XElement.Parse(e.Result);

   41             listBox1.ItemsSource = from tweet in xmlTweets.Descendants(“status”)

   42                                    select new Twitter

   43                                    {

   44                                        ImageSource = tweet.Element(“user”).Element(“profile_image_url”).Value,

   45                                        Message = tweet.Element(“text”).Value,

   46                                        UserName = tweet.Element(“user”).Element(“screen_name”).Value,

   47                                        CreatedAt = tweet.Element(“created_at”).Value

   48                                    };

   49             Windows7Twitter.Text = txttweet.Text;

   50 

   51 

   52         }

   53     }

   54 }

 

Explanation

  1. Add reference of System.XML.Linq.
  2. Using Web Client class call the Twitter REST service.
  3. Parsing the result using XElement.
  4. Using LINQ creating the twitter entity class and setting it as item source of list box.
  5. If service call is returning error then just returning . 

Just press F5 and in Windows 7 mobile emulator you can see the output. Enter user name in the text to fetch tweets.


 

Conclusion

This article explained how to create a basic twitter client for Window7 mobile. In further articles, I will show how to achieve other functionalities of twitter. Thanks for reading. Hope it was useful.

Touch events in Silverlight for Windows 7 mobile application Part #2

Objective

This article will explain how to work with Touch events in Silverlight for Windows 7 mobile application. This is part 2 of the touch events.

Read my first article on touch events before going through this article.

Background

We saw in last article on touch events that, even if after touching (clicking) somewhere else than text block, the text in text block was not resuming to original fonts and colors. The reason behind that was, I attached the event to the text block. I can conclude reason as follows

  1. I attached ManipulationStarted event to text block.
  2. I did not handle ManipulationCompleted event for the text block.
  3. In ManipulationStarted event for text block I changed the text color and font size.
  4. But I did not write code for resuming the original font size and color on ManipulationCompleted event for text block.

    Normal behavior should be, when user is touching or clicking somewhere else on the screen text block should resume to its originality.

So how to achieve it

Fine; when we see the class hierarchy. I will explain this hierarchy in later articles. But what point to be noted here is that , we can override OnManipulationStarted
method and then can sense the touch on whole screen. We can override this method and check if the source of the touch is text block , we can manipulate color and font . If source is somewhere on the screen we can restore the default font and color.


In this article, I am going to work with only ManipulationStarted event. Follow the below steps
Step 1

From Start menu select Microsoft Visual Studio 2010 express edition

Step 2

From File select New Project. From Silverlight for Windows phone tab select Windows Phone application project type.


Once selecting that a new project will get created with below solution structure

Make sure in Debug option Windows Phone7 Emulator is selected. If it is selected to Windows Phone 7 Device then Visual studio will deploy the application to mobile device directly.

Step 3

Open MainPage.Xaml and just add a text block. Set the text of the text block as Hello World. Here if you want you can change Title text also.

If you closely look into XAML, you will find there are two Grids inside main Grid. One is title Grid and other is body Grid. So put your text block in the Body grid.

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

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

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

xmlns:phoneNavigation=”clrnamespace: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=”MY First Mobile Application x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

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

</Grid>

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

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

<TextBlock x:Name=”txtHelloWord” Text=”Hello World” HorizontalAlignment=”Center” VerticalAlignment=”Center” Foreground=”Azure” />

</Grid>

</Grid>
</phoneNavigation:PhoneApplicationPage>

The code I changed is in bigger font and yellow background. This time there is no event attached to text block.
Step 4

In code behind, I am going to write code for changing the color of the text and setting the font size. I will be writing code on overridden method.

MainPage.Xaml.Cs

1 namespace FirstWindowPhoneApplication

2 {

3 public partial class MainPage : PhoneApplicationPage

4 {

5

6 Random radNumber = new Random();

7 public MainPage()

8 {

9 InitializeComponent();

10

11 SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

12 }

13

14

15

16 protected override void OnManipulationStarted(ManipulationStartedEventArgs e)

17 {

18

19 Color clr = Colors.White;

20 double font = 30;

21 if (e.OriginalSource == txtHelloWord)

22 {

23 clr = Color.FromArgb(255, (byte)radNumber.Next(255), (byte)radNumber.Next(255), (byte)radNumber.Next(255));

24 font = 75;

25 }

26

27 txtHelloWord.Foreground = new SolidColorBrush(clr);

28 txtHelloWord.FontSize = font;

29 base.OnManipulationStarted(e);

30 }

31 }

32 }

Explanation

  1. I am overriding OnManipulationStarted method here.
  2. I am checking what the source of calling the method is.
  3. If it is text box, I am setting the font size and color to random color.
  4. If it is not text box , I am setting size and color to default.

Step 5
Just press F5 and in Windows 7 mobile emulator you can see the output. In center you can see Hello world. When you click on the text block, font of the text will be changed to 75 and foreground color will change randomly. But when you click outside the text block or any other place on page text font size will be changed to 30 and text color to white.

Now when I click text color of the text will get changed. This will act exactly on the touch in real device.


Again when user will touch any other place on the page , text color and text size will restore to white and 30 respectively.


Conclusion

This article explained how to handle touch event on page in Silverlight application for Windows 7 mobile. Thanks for reading.

Touch events in Silverlight for Windows 7 mobile application

Objective

This article will explain how to work with Touch events in Silverlight for Windows 7 mobile application.

Background

On real device touch screen get sensed by users figure. But on the Emulator Mouse movement works as input for touch events. Touch events detect movement of finger on the screen.

There are four touch events

  1. ManipulationStarted
  2. ManipulationInertiaStarting
  3. ManipulationDetla
  4. ManipulationCompleted


In this article, I am going to work with only ManipulationStarted event. Follow the below steps

Step 1

From Start menu select Microsoft Visual Studio 2010 express edition


Step 2

From File select New Project. From Silverlight for Windows phone tab select Windows Phone application project type.


Once selecting that a new project will get created with below solution structure

Make sure in Debug option Windows Phone7 Emulator is selected. If it is selected to Windows Phone 7 Device then Visual studio will deploy the application to mobile device directly.

Step 3

Open MainPage.Xaml and just add a text block. Set the text of the text block as Hello World. Here if you want you can change Title text also.

If you closely look into XAML, you will find there are two Grids inside main Grid. One is title Grid and other is body Grid. So put your text block in the Body grid.

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

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

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

xmlns:phoneNavigation=”clrespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation”

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

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

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 First Mobile Application x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>

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

</Grid>

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


<TextBlock Text=”Hello World” HorizontalAlignment=”Center” VerticalAlignment=”Center” Foreground=”Azure”
ManipulationStarted
=”TextBlock_ManipulationStarted” />

</Grid>

</Grid>

</phoneNavigation:PhoneApplicationPage>

The code I changed is in bigger font and yellow background.

Step 4

In code behind, I am going to write code for changing the color of the text and setting the font size. I will be writing code on event ManipulationStarted. Below is very simple code. In this code I am setting the color to a random and setting the font to double 50.


Step 5

    1 namespace FirstWindowPhoneApplication

    2 {

    3     public partial class MainPage : PhoneApplicationPage

    4     {

    5 

    6         Random radNumber = new Random();

    7         public MainPage()

    8         {

    9             InitializeComponent();

   10 

   11             SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

   12         }

   13 

   14         private void TextBlock_ManipulationStarted(object sender, ManipulationStartedEventArgs e)

   15         {

   16             TextBlock txtBlck = sender as TextBlock;

   17             Color clr = Color.FromArgb(255, (byte)radNumber.Next(255), (byte)radNumber.Next(255), (byte)radNumber.Next(255));

   18             txtBlck.Foreground = new SolidColorBrush(clr);

   19             txtBlck.FontSize = 50;

   20 

   21 

   22         }

   23     }

   24 }

   25 

   26 

   27 

Just press F5 and in Windows 7 mobile emulator you can see the output. In center you can see Hello world. When you click on the text block, font of the text will be changed to 20 and foreground color will change randomly.


Now when I click text color of the text will get changed. This will act exactly on the touch in real device.


But when I click out area of the text box text size and color won’t get to its original because I have not handled ManipulationCompleted event.

Conclusion

This article explained how to handle touch in Silverlight application for Windows 7 mobile. Thanks for reading.

Get an Image using WCF REST service

Objective

This article will give a very simple and basic explanation of , how to fetch an image using WCF REST service.

Step 1

Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application.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 2

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 3

Create contract. Operation contract will return Stream. Stream is in the namespace System.IO. By putting WebGet attribute make operation 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”, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]

17 Stream GetImage();

18

19 }

20 }

21

22

23

Implement service. In service class write the below code. Using FileStream open and read the image. Then set outgoing response as image/jpeg using WebOperationContext class.

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 FetchingImageinBrowser

11 {

12 public class Service1 : IService1

13 {

14 public Stream GetImage()

15 {

16 FileStream fs = File.OpenRead(@”D:\a.jpg”);

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

18 return fs;

19 }

20

21 }

22 }

23

Step 4

Press F5 to run the application. Append GetImage/ in URL to get the output.

Creating first Windows 7 mobile application in Silverlight

 

Objective

This is a pictorial tutorial on how to create first Silverlight mobile application for Windows 7. This is very simple article giving you introduction how to setup the environment and run and debug the application.

Since everyone is talking about Windows 7 Mobile development. Let us learn together J

Step 1

Download windows phone developer tools from Here.

Pre requisite are

  1. Visual Studio 2010
  2. Windows 7 or Vista
  3. 2GB Ram
  4. 3GB space available

To develop window 7 mobile phone application, you need

  1. Visual Studio 2010 Express for Windows Phone CTP
  2. Windows Phone Emulator CTP
  3. Silverlight for Windows Phone CTP
  4. XNA 4.0 Game Studio CTP

Once you download and install Windows Phone developer tool, all the requirements to develop application will get installed.

Step 2

From Start menu select Microsoft Visual Studio 2010 express edition


 

Step 3

From File select New Project. From Silverlight for Windows phone tab select Windows Phone application project type.


Once selecting that a new project will get created with below solution structure

 

Step 4

Open MainPage.Xaml and just add a text block. Set the text of the text block as Hello World. Here if you want you can change Title text also.

If you closely look into XAML, you will find there are two Grids inside main Grid. One is title Grid and other is body Grid. So put your text block in the Body grid.

<phoneNavigation:PhoneApplicationPage


x:Class=”FirstWindowPhoneApplication.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&#8243;


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


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=”MY First Mobile Application x:Name=”textBlockPageTitle” Style=”{StaticResource PhoneTextPageTitle1Style}”/>


<TextBlock Text=” Windows 7 Mobile application x:Name=”textBlockListTitle” Style=”{StaticResource PhoneTextPageTitle2Style}”/>


</Grid>


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


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


<TextBlock Text=”Hello World” HorizontalAlignment=”Center” VerticalAlignment=”Center” Foreground=”Azure” />


</Grid>


</Grid>

</phoneNavigation:PhoneApplicationPage>

 

The code I changed is in bigger font.

Step 5

Just press F5 and in Windows 7 mobile emulator you can see the output. In center you can see Hello world. Make sure in Debug option Windows Phone7 Emulator is selected. If it is selected to Windows Phone 7 Device then Visual studio will deploy the application to mobile device directly.



 

Conclusion

This article explained how to create your first Windows 7 mobile application.

Creating IPL Photo gallery using AccordionControl in Silverlight 3.0: Part #1

Objective

This article will explain

  1. Basic use of Accordion control in Silverlight 3.0
  2. Binding Accordion items with properties of entity class.
  3. Creating an Imagesource from Image URL provided.

Background

This article is first part of 3 or 4 parts IPL Photo Gallery series. In this article, I am reading image, team name and caption name from hard coded list. I have added images in the project as existing items. In further article I will modify this to read from database using WCF.

Expected output

 Follow the stepsStep 1

Create a Silverlight application.

Step 2

Create an entity class. This class will contain as property, TeamName and TeamImage of the IPL team. Team entity class is as below. Just right click on Silverlight project and add a new class named Team.

Type of TeamImage is ImageSource because I am going to bind this property directly to a imagesource.

 Step 3
In this step, I will get an image from the path of the image provided. I have created function that is returning an ImageSource.
Step 4
Right click and add images in Silverlight project. To do so; right click and select add existing items. I have added 8 images corresponding to 8 teams of IPL.
Step 5
In this step, I am creating a function to return list of Teams.
Step 6
On the page load bind the list of teams as item source to Accordion control.
Here teamAccordianControl is name of the Accordion control added on XAML page.
So, complete code for MainPage.Xaml.cs 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 System.Windows.Media.Imaging;

   13 

   14 namespace AccordianControl

   15 {

   16     public partial class MainPage : UserControl

   17     {

   18         public MainPage()

   19         {

   20             InitializeComponent();

   21             teamAccordianControl.ItemsSource = GetTeams();

   22         }

   23 

   24         public ImageSource GetImage(string path)

   25         {

   26             return new BitmapImage(new Uri(path, UriKind.Relative));

   27         }

   28 

   29         public List<Team> GetTeams()

   30         {

   31             List<Team> lstTeam = new List<Team>()

   32                                  {

   33                                      new Team{TeamName=“Rajasthan Royals “ , TeamImage = GetImage(“RR.jpg”),Capatin=“Shane Warne”},

   34                                      new Team{TeamName=“Delhi DareDevils “ , TeamImage = GetImage(“DD.jpg”),Capatin=“Gautam Gambhir”},

   35                                      new Team{TeamName=“Chenni SuperKing “ , TeamImage = GetImage(“CS.jpg”),Capatin=“Mahendra Singh Dhoni”},

   36                                      new Team{TeamName=“Mumbai Indians “ , TeamImage = GetImage(“MI.jpg”),Capatin=“Sachin Tendulkar”},

   37                                      new Team{TeamName=“Kolkatta KnightRiders “ , TeamImage = GetImage(“KK.jpg”),Capatin=“Saurabh Ganguli”},

   38                                      new Team{TeamName=“Royal Challenger Bangalore “ , TeamImage = GetImage(“RC.jpg”),Capatin=“Anil Kumble”},

   39                                      new Team{TeamName=“Deccan Charger Hyderabad “ , TeamImage = GetImage(“DC.jpg”),Capatin=“Adam Ghilchrist”},

   40                                      new Team{TeamName=“Kings 11 Punjab” , TeamImage = GetImage(“KP.jpg”),Capatin=“Kumar Sangakara”}

   41 

   42                                  };

   43             return lstTeam;

   44 

   45         }

   46     }

   47 }

   48 

   49 

 Step 7

In this step, I will design the page.

  • Drag and drop a Accordion control from toolbox on page
  • Set vertical and horizontal alignment of control to stretch.
  • Set SelectionSequence to CollapsebeforeExpand
  • Set SelectMode to ZeroOrOne
  • Set the header using Accordion.ItemContainerStyle
  • Inside Data template put a text block and bind to the TeamName property of Team entity class.
  • Accordion.ContentTemplate create item of the Accordion control
  • Inside Data Template put a Stack panel with orientation vertical.
  • Put a Text block and bind to Caption property of Team entity class.
  • Put an Image control and bind to TeamImage property of Team entity class.

     MainPage.Xaml

<UserControl xmlns:layoutToolkit=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit”
x:Class=”AccordianControl.MainPage”

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

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

xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;


mc:Ignorable=”d” d:DesignWidth=”*” d:DesignHeight=”*” Background=”Azure” >


<Grid x:Name=”LayoutRoot” Height=”620″ Width=”420″ >


<layoutToolkit:Accordion x:Name=”teamAccordianControl”


HorizontalAlignment=”Stretch”


VerticalAlignment=”Stretch”


SelectionSequence=”CollapseBeforeExpand”


Height=”auto”


SelectionMode=”ZeroOrOne”>


<layoutToolkit:Accordion.ItemContainerStyle>


<Style x:Name=”accordionitemstyle1″ TargetType=”layoutToolkit:AccordionItem”>


<Setter Property=”HeaderTemplate”>


<Setter.Value>


<DataTemplate>


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


</DataTemplate>


</Setter.Value>


</Setter>


</Style>


</layoutToolkit:Accordion.ItemContainerStyle>


<layoutToolkit:Accordion.ContentTemplate >


<DataTemplate>


<StackPanel Height=”auto” Width=”auto” Orientation=”Vertical”>


<TextBlock HorizontalAlignment=”Center” FontFamily=”Arial” FontSize=”20″ Text=”{Binding Path=Capatin}” />


<Image Source=”{Binding Path=TeamImage}”/>


</StackPanel>


</DataTemplate>


</layoutToolkit:Accordion.ContentTemplate>


</layoutToolkit:Accordion>


</Grid>

</UserControl>

Now press F5 and output would be

Conclusion

 In this article, I have shown basic use of accordion control. I have shown how to bind Accordion items with different properties of an entity class. I will further modify this sample and add more functionality. Thanks for reading.

Reading RSS feed in Silverlight 3.0

Objective

This article is going to explain; how we can read RSS feeds in Silverlight 3.0.

Expected output

  1. User will enter RSS URL in text box.
  2. On click of Fetch Feed button ; RSS items will get populated
  3. On Clear Search button click text box and list box will be cleared.


So, let us start follow the below steps

Step 1

Create a Silverlight application.

Step 2

Add an entity class. In this class RSS Feeds would be read. Right click Silverlight project and add a class. Give any name; I am giving name here MYFeed.

MyFeed.cs

    1  namespace ReadingFeeds

    2     {

    3         public class MyFeed

    4         {

    5 

    6             public string Title { get; set; }

    7             public string Summary { get; set; }

    8             public string PublishedDate { get; set; }

    9             public Uri Url { get; set; }

   10 

   11         }

   12     }

   13 

 

Design the page

  1. Divide grid in three rows.
  2. In first and second row add stack panels.
  3. Give orientation of stack panel as horizontal.
  4. In first row; add one text block and one text box. User will enter RSS URL in text box provided here.
  5. In second row; add two buttons. One button to fetch URL and other to clear the values.
  6. In third row put a list box. Return items of RSS will be bind to this list box. List box is bind as follows.

     

<ListBox x:Name=”myListBox” Grid.Row=”2″ ScrollViewer.HorizontalScrollBarVisibility=”Disabled” >

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=”Vertical” >

<TextBlock x:Name=”txtTitle” FontSize=”14″
Text=”{Binding Title}”/>

<TextBlock x:Name=”txtSummary” Text=”{Binding Summary}”
TextWrapping=”Wrap”/>

<TextBlock x:Name=”txtPublishedDate”
Text=”{Binding PublishedDate}” />


<TextBlock x:Name=”txtUri” Text=”{Binding Url}” />


<Rectangle Height=”3″ Fill=”Blue” />


</StackPanel>


</DataTemplate>


</ListBox.ItemTemplate>


</ListBox>

 There is stack panel inside data template. There are different text blocks bind with different data.
MainPage.Xaml

<Grid x:Name=”LayoutRoot”>

<Grid.RowDefinitions>

<RowDefinition Height=”1*” />

<RowDefinition Height=”1*” />

<RowDefinition Height=”12*” />

</Grid.RowDefinitions>

<StackPanel Grid.Row=”0″ Orientation=”Horizontal” HorizontalAlignment=”Center”>


<TextBlock x:Name=”lblFeed” Height=”40″
Text=”RSS FEED” FontSize=”18″
/>


<TextBox x:Name=”txtRssFeed” Height=”40″ Width=”1000″ Background=”AliceBlue” />


</StackPanel>


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


<Button x:Name=”btnFetchFeed” Height=”30″ Width=”100″ Content=”Fetch Feed” VerticalAlignment=”Center” />


<Button x:Name=”btnClear” Height=”30″ Width=”100″ Content=”Clear Search” VerticalAlignment=”Center” />


</StackPanel>


<Rectangle Height=”5″ Fill=”Blue” Grid.Row=”0″ VerticalAlignment=”Bottom” />


<Rectangle Height=”5″ Fill=”Blue” Grid.Row=”1″ VerticalAlignment=”Bottom” />


<ListBox x:Name=”myListBox” Grid.Row=”2″ ScrollViewer.HorizontalScrollBarVisibility=”Disabled” >


<ListBox.ItemTemplate>


<DataTemplate>


<StackPanel Orientation=”Vertical” >


<TextBlock x:Name=”txtTitle” FontSize=”14″
Text=”{Binding Title}”/>


<TextBlock x:Name=”txtSummary” Text=”{Binding Summary}”
TextWrapping=”Wrap”/>


<TextBlock x:Name=”txtPublishedDate”
Text=”{Binding PublishedDate}” />


<TextBlock x:Name=”txtUri” Text=”{Binding Url}” />


<Rectangle Height=”3″ Fill=”Blue” />


</StackPanel>


</DataTemplate>


</ListBox.ItemTemplate>


</ListBox>


</Grid>

Step 4

  1. To read RSS feed; first we need to create instance of WebClient class. This class helps us to make HTTP call from Silverlight 
  1. Create a list to read RSS feeds. 
  2. Add reference of     using System.ServiceModel.Syndication;
  3. Read result return from service in a Stream.
  4. Create XMLReader from the stream.
  5. Load SyndicationFeed from the XMLReader. Fetch all the SyndicationItem ina foreach loop and create MyFeed instance and add to list. Bind list as datasourec of List box.
     MainPage.Xaml.cs
      

        1 

        2 using System;

        3 using System.Collections.Generic;

        4 using System.Linq;

        5 using System.Net;

        6 using System.Windows;

        7 using System.Windows.Controls;

        8 using System.Windows.Documents;

        9 using System.Windows.Input;

       10 using System.Windows.Media;

       11 using System.Windows.Media.Animation;

       12 using System.Windows.Shapes;

       13 using System.IO;

       14 using System.Xml;

       15 using System.ServiceModel.Syndication;

       16 using System.Collections;

       17 

       18 namespace ReadingFeeds

       19 {

       20     public partial class MainPage : UserControl

       21     {

       22 

       23         List<MyFeed> lstFeed = null;

       24         MyFeed feed = null;

       25 

       26         public MainPage()

       27         {

       28             InitializeComponent();

       29             btnFetchFeed.Click += new RoutedEventHandler(btnFetchFeed_Click);

       30             btnClear.Click += new RoutedEventHandler(btnClear_Click);

       31 

       32         }

       33 

       34         void btnClear_Click(object sender, RoutedEventArgs e)

       35         {

       36             myListBox.SelectedIndex = –1;

       37             myListBox.ItemsSource = null;

       38             txtRssFeed.Text = “”;

       39 

       40         }

       41 

       42         void btnFetchFeed_Click(object sender, RoutedEventArgs e)

       43         {

       44 

       45             Uri serviceURI = null;

       46             if (string.IsNullOrEmpty(txtRssFeed.Text))

       47             {

       48                 MessageBox.Show(“RSS Field is empty “);

       49             }

       50             else

       51             {

       52                 serviceURI = new Uri(txtRssFeed.Text.Trim());

       53                 WebClient proxy = new WebClient();

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

       55                 proxy.OpenReadAsync(serviceURI);

       56             }

       57 

       58         }

       59 

       60         void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

       61         {

       62 

       63             lstFeed = new List<MyFeed>();

       64             Stream stream = e.Result;

       65             XmlReader response = XmlReader.Create(stream);

       66             SyndicationFeed feeds = SyndicationFeed.Load(response);

       67             foreach (SyndicationItem f in feeds.Items)

       68             {

       69                 Uri imgUri = f.BaseUri;

       70                 feed = new MyFeed() { Title = f.Title.Text, Summary = f.Summary.Text, PublishedDate = f.PublishDate.ToString(), Url = imgUri };

       71                 lstFeed.Add(feed);

       72             }

       73             myListBox.ItemsSource = lstFeed;

       74         }

       75     }

       76 }

       77 

       78  

    Press F5 and run the application.

    Conclusion

    In this article I discussed how to read RSS in Silverlight 3.0. Thanks for reading.

LINQ to Object Part #4: Querying Non- IEnumerable collections

Objective

In this article, I am going to show, how we could apply LINQ to query non-IEnumerable<T> Collections.

I have created a class for my explanation purpose. Student class is having details of students.

 Student.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace LINQtoOBJECT1

    7 {

    8      public  class Student

    9     {

   10 

   11          public int RollNumber { get; set; }

   12          public string Name { get; set; }

   13          public int Section { get; set; }

   14          public int HostelNumber { get; set; }

   15     }

   16 }

   17 

 

To create ArrayList of Student, I am creating a static function. This static function will return ArraList of student.

Function to return ArrayList of students.

    1  public static ArrayList   GetStudentAsArrayList()

    2         {

    3 

    4             ArrayList  students = new ArrayList

    5             {

    6                 new Student() { RollNumber = 1,Name =“Alex “ , Section =  1 ,HostelNumber=1 },

    7                 new Student() { RollNumber = 2,Name =“Jonty “ , Section = 2 ,HostelNumber=2 },

    8                 new Student() { RollNumber = 3,Name =“Samba “ , Section = 3 ,HostelNumber=1 },

    9                 new Student() { RollNumber = 4,Name =“Donald “ , Section = 3 ,HostelNumber=2 },

   10                 new Student() { RollNumber = 5,Name =“Kristen “ , Section = 2 ,HostelNumber=1 },

   11                 new Student() { RollNumber = 6,Name =“Mark “ , Section = 1 ,HostelNumber=2},

   12                 new Student() { RollNumber = 7,Name =“Gibbs “ , Section = 1 ,HostelNumber=1 },

   13                 new Student() { RollNumber = 8,Name =“Peterson “ , Section = 2 ,HostelNumber=2 },

   14                 new Student() { RollNumber = 9,Name =“collingwood “ , Section = 3 ,HostelNumber=1 },

   15                 new Student() { RollNumber = 10,Name =“Brian “ , Section = 3 ,HostelNumber=2 }

   16 

   17             };

   18 

   19             return students;

   20 

   21         }

 Now when I tried to query the returned ArrayList using LINQ, I got compile time error. Because ArrayList does not implement interface IQueryable and it is not IEnumerable<T> collection.

 Below code gave a compile time error

    1 ArrayList lstStudents = GetStudentAsArrayList();

    2             var res = from  r in lstStudents select r;

Error is as below,


Above error cause because LINQ by default only query against IEnumerable<T> collections.

So , how to query an ArrayList? Here Range variable comes into action. If I modify the above query as below , I would be able to query LINQ against a non IEnumerable<T> collection.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using System.Collections;

    6 

    7 

    8 namespace LINQtoOBJECT1

    9 {

   10     class Program

   11     {

   12         static void Main(string[] args)

   13         {

   14 

   15 

   16             ArrayList lstStudents = GetStudentAsArrayList();

   17             var res = from  Student   r in lstStudents select r;

   18             foreach (Student s in res)

   19             {

   20                 Console.WriteLine(s.Name);

   21             }

   22 

   23            Console.ReadKey();

   24 

   25 

   26 

   27         }

I am using Student as range variable. And we will get output as below .In above code I am using Student the class in ArrayList as range variable.


Conclusion

In this article, I discussed how to query against non IEnumerable<T> collection. Thanks for reading.

Demystifying CLR Part #1

Objective

This is a fully theoretical article. In this article, I am going to explain fundamentals of CLR. How CLR executes codes written in different languages. I am going to explain various components of MANAGED MODULES also.

Note: I have written this article on basis of my learning from the very nice book written by Jeffery Richter named CLR via C#. I suggest everyone to have a better understating on CLR read this book. Thanks to original author Jeffery. I just tried to make his words simpler for native reader like me.

Flow Chart of CLR execution model

 


CLR comes as part of .Net framework. This is a run time that is useable by different and varied programming language.

Features of CLR is as follows

  1. Memory Management
  2. Assembly Loading
  3. Security
  4. Exception Handling
  5. Thread Synchronization

Any language which targets its compiled output to CLR can avail above features.

CLR can work on any language; condition is compiler of that language targets the compiled output to the CLR. Microsoft has created much language which compilers targets to CRL.


Managed Module

This is either 32 bit or 64 bit Microsoft Standard Portable Executable File Format. These are the files required by CLR to execute.

Compiler of all high level language does the task of syntax checking and language analysis and targets the compiled output to CLR. All languages outputs PE 32 or PE32+ format files and that will get executed by CLR to produce CPU instructions.


The above diagram describes why .Net frameworks are so called Language independent. It is due to CLR. CLR is common for all languages.

Components of Managed Module


PE32 or PE32 + Header

  1. The standard of windows portable executable file format header is similar to common object filr format (COFF) headers.


  1. Header contains information about type of the file. That whether it is DLL, GIF etc.
  2. Header contains information about time stamp that when file built.
  3. If the managed module is having only IL then PE 32 (+) header is ignored by CLR.
  4. If the managed module contains CPU Instructions then PE 32 (+) header contains information about CPU instructions.

CLR Header

  1. This contains the information interpreted by CLR.
  2. This contains information about version of CLR needed to interpret the managed module.
  3. This contains Flags information.
  4. CLR header contains MethodOF token which says what is entry point (main method) of managed module.

IL Code

Code generated by language compiler as compiled outputs. This IL code gets interpreted by CLR to produce CPU instructions.

MetaData

Each managed modules contain Meta Data table. There are normally two types of Meta Data table.


Every compiler targeting the CLR must emit a full set of Meta data. Meta Data is set of tables that contain all the information about what defines in the module. This contains information about all the types and members used in the code. This also contains all the type and members referenced in the code. Meta Data is always associated with the files contain the IL. Meta Data packaged in the same dll or exe file.

Uses of Meta Data table

  1. Meta Data removes the natives’ code like header files.
  2. Visual Studio uses Meta Data to perform work of IntelliSense. IntelliSense feature of visual studio uses Meta data tables to give suggestion while writing codes.
  3. CLR code verification uses Meta Data tables to make sure code only performs type safe operations.
  4. Meta Data performs work of serialization and deserialization.
  5. Garbage collector reads life time of object from Meta data table.

 

Conclusion

In this article, I discussed how high level language compiles source code to a managed module. And CLR reads this managed module to give CPU instructions as output. This was 1st part of series of article on CLR. Thanks for reading. I hope it was useful for you.