F5 Debug…

Building & Debugging the Technology!!!

Archive for February, 2012

Learn Windows Phone 7 Development in 31 Days – Day 29 – Working with Encrypting Data for Security in WP7

Posted by Karthikeyan Anbarasan on February 29, 2012

01 Download ToolsDownload Source CodeDownload as PDF FileSubscribe to F5debugComplete Article Listing

Introduction:

In this article we are going to see how to encrypt data and use it in Windows phone 7 application development. Security is mainly a concern for developing applications with mobile since misusing of data like Passwords, connection strings etc. are highly possible which we need to take care by encrypting and decrypting where ever possible. In Windows Phone 7 we have Data Protection API which can be used to encrypt the data, storing the confidential data with in the Application Isolated Storage or with encrypting using the local keys is not highly secure since the keys that are required to decrypt the data will reside on the device itself. Data protection API solves this problem of explicitly generating and storing the key. ProtectData class is used to access the Data Protection APIs that can be used with the inbuilt methods which we are going to see in this article.

Data Protection API’s uses the Protect Method and UnProtect Method which are used to encrypting and decrypting the data as and when required which using the dynamic key generations as and when called. Let us see the step by step process on how to use these methods to encrypt the data and decrypt it in this article.

Steps:

Open visual studio 2010 IDE in administrator mode and create a new Silverlight for Windows phone 7 application with a valid project name as shown in the screen below.

2012-02-28 23h06_21

Now let us design the application to get the inputs from the user to encrypt the data and store the pin in the isolated storage using the Protectdata method. Once we added the controls to the page we can see the screen as shown in the screen below.

2012-02-28 23h18_17

Let us start with our code behind to add the core logic to encrypt the data, to do that we need to import some namespaces which are not available initially. Copy and paste the below 4 namespaces to the code behind as shown below.

Code Behind:

<pre>using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Security.Cryptography;

Once we added the using statement, we need to add the below code to encrypt the data which the user inputs the data as shown in the screen below. In this code we are going to encrypt the pin to the byte array using the protect method.

2012-02-28 23h30_39

Code Behind:


private void button1_Click(object sender, RoutedEventArgs e)
 {
 byte[] PinByte = Encoding.UTF8.GetBytes(textBlock1.Text);
 byte[] ProtectedPinByte = ProtectedData.Protect(PinByte, null);
 this.Writedata(ProtectedPinByte);
 textBlock1.Text = "";
 MessageBox.Show("Encrypted the Pin!!!");
 }

private void Writedata(byte[] pinData)
 {
 IsolatedStorageFile ISfile = IsolatedStorageFile.GetUserStoreForApplication();
 IsolatedStorageFileStream swIS = new IsolatedStorageFileStream(strFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, ISfile);

Stream writer = new StreamWriter(swIS).BaseStream;
 writer.Write(pinData, 0, pinData.Length);
 writer.Close();
 swIS.Close();
 }

Now we are done with the code to encrypt the data, we use the Writedata private method to store the data to the Isolated Storage by using the Isolated Stream Class. Once the pin is encrypted we have provided a message box to indicate the user that the data is encrypted correctly. Now let us decrypt the data on the second button click event. Decrypting the data will be done using the UnProtect method which reads the data from the isolated storage medium on the path which we specified and decrypts the pin and get the data as shown in the screen below.

2012-02-28 23h37_19

Code Behind:


private void button2_Click(object sender, RoutedEventArgs e)
 {
 byte[] ProtectedPinByte = this.ReadPinFromFile();
 byte[] PinByte = ProtectedData.Unprotect(ProtectedPinByte, null);
 textBlock1.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length);

}

private byte[] ReadPinFromFile()
 {
 IsolatedStorageFile ISfile = IsolatedStorageFile.GetUserStoreForApplication();
 IsolatedStorageFileStream rsIS = new IsolatedStorageFileStream(strFilePath, System.IO.FileMode.Open, FileAccess.Read, ISfile);

Stream reader = new StreamReader(rsIS).BaseStream;
 byte[] pinArray = new byte[reader.Length];

reader.Read(pinArray, 0, pinArray.Length);
 reader.Close();
 rsIS.Close();

return pinArray;
 }

Now we are done with our code part, to check the encryption and decryption, run the application by pressing F5 directly from the keyboard and we can see the application loads on to the Windows Phone 7 Emulator. Input the sample data and we can see the encryption and decryption happening as shown in the screens below.

Output Screens:

image

Conclusion:

So in this article we have seen the most interesting topic on how to encrypt and decrypt the data using the available API’s which can be used to encrypt the sensitive data as and when required with the application development.

Thanks for reading my article. If you like my blog and if you are interested in getting the latest updates on new articles, kindly follow me through one of these options.

F5Debug FacebookF5debug LinkedInF5debug TwitterF5debug GooglePlusF5debug RSSFeed

Posted in Windows Phone 7 | Tagged: , , , , , , , , , , , , , | 3 Comments »

Learn Windows Phone 7 Development in 31 Days – Day 28 – Working with Consuming a WCF Service in WP7

Posted by Karthikeyan Anbarasan on February 28, 2012

01 Download ToolsDownload Source CodeDownload as PDF FileSubscribe to F5debugComplete Article Listing

Introduction:

In this article we are going to see how to consume a WCF Service in a Windows Phone 7 Application Development. For the beginners WCF is a Windows Communication Foundation is a Microsoft framework to build application in Service Oriented Architecture. We can use WCF as a service to send data across the application as a service with the endpoints predefined to communicate. The service endpoints can be of type which is hosted on to an IIS Server and available anytime, or it can also be an application oriented service to provide on demand usage. The data transfer through the messages can be of any particular format that the sender and receiver can able to understand the communication over the protocol.

In Windows Phone 7 development we have scenarios where we need to pass and get the data over the service through some authorized protocols and secured ports where WCF plays a major role. Let us see the step by step process on how to consume a WCF Service in a Windows Phone 7 Application taking into consideration the reader should be familiar with creating a WCF Service and hosting on to IIS. Refer MSDN article to get some idea on how to create and host the WCF Service using the link http://msdn.microsoft.com/en-us/library/ms733766.aspx

Steps:

Open Visual Studio 2010 IDE in administrator mode and create a new Silverlight for Windows Phone 7 Application with a valid project name as shown in the screen below.

2012-02-22 13h23_13

We can see the project is created and the main page is opened with the default controls. Let us consider that we have a WCF application already created and hosted on IIS which can be consumed and pass the value (2 numbers) and we will get the sum of the values passed as the output. So from our Windows phone 7 application we can pass the 2 values and we can make the WCF do the sum and sends the result back which can be viewed in the application.

First let us add some controls which gets the user inputs that should be passed to the WCF Service and to show the results to the end users. Just copy the XAML provided below to get the same user experience with the design as shown in the screen below.

2012-02-28 07h16_23

XAML Code:


<Grid x:Name="LayoutRoot" Background="Transparent">
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto"/>
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>

<!--<span class="hiddenSpellError" pre="">TitlePanel</span> contains the name of the application and page title-->
 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>
 <TextBlock x:Name="PageTitle" Text="WCF Service" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
 </StackPanel>

<!--<span class="hiddenSpellError" pre="">ContentPanel</span> - place additional content here-->
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 <TextBlock Height="30" HorizontalAlignment="Left" Margin="30,43,0,0" Name="textBlock1" Text="Value 1" VerticalAlignment="Top" />
 <TextBlock Height="30" HorizontalAlignment="Left" Margin="30,117,0,0" Name="textBlock2" Text="Value 2" VerticalAlignment="Top" />
 <TextBox Height="72" HorizontalAlignment="Left" Margin="119,19,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="313" />
 <TextBox Height="72" HorizontalAlignment="Left" Margin="119,97,0,0" Name="textBox2" Text="" VerticalAlignment="Top" Width="313" />
 <TextBlock Height="116" HorizontalAlignment="Left" Margin="53,312,0,0" Name="txtResult" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="379" />
 <Button Content="Consume WCF and Get Result" Height="72" Margin="6,196,0,0" Name="button1" VerticalAlignment="Top" />
 </Grid>
 </Grid>

Now we can consume the WCF Service by right clicking on the Project and select Add Service reference, we can see a pop up window where we need to input the WCF Service and the details as shown in the screen below.

2012-02-28 07h21_30

Clicking on OK will add the service reference to the project file and we can see the service reference files added with the name provided in the namespace along with some reference files as well. Now we need to put our code logic to consume the service and pass the values as shown in the code below.

image

Code Behind:


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;

namespace F5debugWp7ConsumeWCF
 {
 public partial class MainPage : PhoneApplicationPage
 {
 // Constructor
 public MainPage()
 {
 InitializeComponent();
 }

private void button1_Click(object sender, RoutedEventArgs e)
 {
 WCFServiceToSumData.Service1Client client = new WCFServiceToSumData.Service1Client();
 int intvalue1 = Convert.ToInt32(textBox1.Text.ToString());
 int intvalue2 = Convert.ToInt32(textBox2.Text.ToString());

client.Add2NumbersAsync(intvalue1, intvalue2);
 client.Add2NumbersCompleted += new EventHandler<WCFServiceToSumData.Add2NumbersCompletedEventArgs>(client_getStringCompleted);

}

private void client_getStringCompleted(object sender, WCFServiceToSumData.Add2NumbersCompletedEventArgs e)
 {
 txtResult.Text = "The Sum of the above 2 number is " + e.Result;

}
 }
 }

Now we are done with our code, just to check if the things are working good we can directly run the application by pressing F5 from the key board or from the tool bar and we can see the expected results once we pass the data as shown in the screens below.

Output Screens:

image

Conclusion:

So in this article we have seen how to make use of the WCF service which we created locally or to consume the 3rd party WCF Service and get the desired output as per the requirement in Windows Phone 7 Development environment.

Thanks for reading my article. If you like my blog and if you are interested in getting the latest updates on new articles, kindly follow me through one of these options.

F5Debug FacebookF5debug LinkedInF5debug TwitterF5debug GooglePlusF5debug RSSFeed

Posted in Windows Phone 7 | Tagged: , , , , , , , , , , , , , , | 2 Comments »

Learn Windows Phone 7 Development in 31 Days – Day 27 – Working with Consuming an ODATA Service in WP7

Posted by Karthikeyan Anbarasan on February 27, 2012

01 Download ToolsDownload Source CodeDownload as PDF FileSubscribe to F5debugComplete Article Listing

Introduction:

In this article we are going to see how to consume a ODATA service in Windows Phone 7 application. ODATA is Open Data Protocol is an entity model used to access data as a REST service, which can be used to execute queries and to create, update and delete data on to the remote data service. ODATA service allows the consumers to query the data over the http protocol and retrieve the result in a plain XML format. Normally a mobile application development requires data that are available as a service which can be consumed and use on demand, where the ODATA Service plays a major role. We have variety of ODATA services that are available in market, rather we can create our ODATA service which can also be consumes as a WCF Data Services.

As per ODATA website, The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years.  OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.

We have a comprehensive list of public ODATA Services that can be consumed from the client devices using the link http://www.odata.org/producers. Let us see the step by step process on how to consume the ODATA Service in our Windows Phone 7 application and see how to make use of it efficiently.

Steps:

Open Visual Studio 2010 IDE in administrator mode and create a new Silverlight for Windows Phone 7 project with a valid project name as shown in the screen below.

2012-02-21 11h53_19

Now we need to design our XAML page where we want to show our consumed ODATA service, we can use the Listbox and dynamically bind the data which we consume. Copy the below XAML code to get the unique design in our sample project as shown in the screen below.

2012-02-21 15h40_06

XAML Code:


<Grid x:Name="LayoutRoot" Background="Transparent">
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto"/>
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>

<!--<span class="hiddenSpellError" pre="">TitlePanel</span> contains the name of the application and page title-->
 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>
 <TextBlock x:Name="PageTitle" Text="OData Service" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
 <!--<span class="hiddenSpellError" pre=""-->StackPanel>

<!--<span class="hiddenSpellError" pre="">ContentPanel</span> - place additional content here-->
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 <button>OData" Margin="0,507,0,0" Click="Button_Click"></button>
 <ListBox x:Name="MainListBox"&nbsp; ItemsSource="{Binding}" Margin="0,6,0,106">
 <ListBox.ItemTemplate>
 <DataTemplate>
 <StackPanel Margin="0,0,0,17" Width="432">
 <TextBlock Text="{Binding Path=Name}" TextWrapping="NoWrap"
 Style="{StaticResource PhoneTextExtraLargeStyle}"/>
 <TextBlock Text="{Binding Path=Description}" TextWrapping="NoWrap"
 Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
 <TextBlock Text="{Binding Path=Url}" TextWrapping="NoWrap" Margin="12,-6,12,0"
 Style="{StaticResource PhoneTextSubtleStyle}"/>
 </StackPanel>
 </DataTemplate>
 </ListBox.ItemTemplate>
 </ListBox>
 </Grid>
 </Grid>

Once we designed the XAML page, now we need to consume the ODATA service, in this sample application we will make use of the Telerik Video’s ODATA service which is available to public. The ODATA service is available using the URI http://tv.telerik.com/services/odata.svc/. To add the ODATA service right click on the project name and select Add Service Reference as shown in the screen below.
2012-02-21 12h04_08

Clicking on Add Service Reference will get a pop window where we need to provide the OATA Service uri and click on Go button to discover the service online. Once the service is discovered we need to change the namespace to a user defined name as ODataTelerik as shown in the screen below.

2012-02-21 15h24_54

On successfully adding the ODATA service reference to the project we can see a list of files added to the service reference folder. Now we are ready with the service, our next step is write some code that will do the necessary process to get the data from the service and show it to the user interface which we designed. Add the below 2 namespaces which are required to consume and get the data from the ODATA service as shown in the screen below.

Code Behind:


using System.Data.Services.Client;
 using F5debugWp7ODataConsule.ODataTelerik;

Once we added the above 2 namespaces we need to start with our code to consume the service, copy the below code and add it to the Mainpage class. This code creates an instance of the reference which we added to the project and get the ODATA service URI which is used to create a reference while consuming the service as shown in the code below.

2012-02-21 15h27_17

Code Behind:


private ODataDataSource TelerikEntity;
 private static string strODataURI = "<a href="http://tv.telerik.com/services/odata.svc/%22;">http://tv.telerik.com/services/odata.svc/";</a>
 private readonly Uri tURI = new Uri(strODataURI);
 private DataServiceCollection<Video> videos;

Now in the button click event we need to call the ODATA Service and get the data which is required to bind to the controls which we designed in our initial process. Once we created the instance we can query the data from the DataServiceCollection by just using the LINQ query as shown in the screen below. Just copy and paste the below code the button click event to step further.

2012-02-21 15h30_04

Code Behind:


private void Button_Click(object sender, RoutedEventArgs e)
 {
 TelerikEntity = new ODataDataSource(tURI);
 videos = new DataServiceCollection<video tabindex="0">(TelerikEntity);</video>

var queryvideo = from vid in TelerikEntity.Videos
 select vid;

videos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(videos_LoadCompleted);
 videos.LoadAsync(queryvideo);
 }

Now we need to add the below code which is basically required to handle the event on the completion of loading the data to the user interface to scroll and have a better look for the end users as shown in the code below.

Code Behind:


void videos_LoadCompleted(object sender, LoadCompletedEventArgs e)
 {
 if (e.Error == null)
 {
 if (videos.Continuation != null)
 {
 videos.LoadNextPartialSetAsync();
 }
 else
 {
 this.MainListBox.DataContext = videos;
 }
 }
 else
 {
 MessageBox.Show("Error while fetching the data!!!");
 }
 }

Now we are done with our complete code, our final code behind class will look like the below code.

Code Behind:


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 F5debugWp7ODataConsule.ODataTelerik;

namespace F5debugWp7ODataConsule
 {
 public partial class MainPage : PhoneApplicationPage
 {
 private ODataDataSource TelerikEntity;
 private static string strODataURI = "<a href="http://tv.telerik.com/services/odata.svc/%22;">http://tv.telerik.com/services/odata.svc/";</a>
 private readonly Uri tURI = new Uri(strODataURI);
 private DataServiceCollection<Video> videos;

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

private void Button_Click(object sender, RoutedEventArgs e)
 {
 TelerikEntity = new ODataDataSource(tURI);
 videos = new DataServiceCollection<Video>(TelerikEntity);

var queryvideo = from vid in TelerikEntity.Videos
 select vid;

videos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(videos_LoadCompleted);
 videos.LoadAsync(queryvideo);
 }

void videos_LoadCompleted(object sender, LoadCompletedEventArgs e)
 {
 if (e.Error == null)
 {
 if (videos.Continuation != null)
 {
 videos.LoadNextPartialSetAsync();
 }
 else
 {
 this.MainListBox.DataContext = videos;
 }
 }
 else
 {
 MessageBox.Show("Error while fetching the data!!!");
 }
 }
 }
 }

Now build and execute the application by simply pressing F5 from the keyboard and we can see the expected results are shown in the screens below.

Output Screens:

image

Conclusion:

So in this article we have seen what is ODATA service and how to consume the service from the Windows Phone 7 application to get the data and process it as per the requirement. Hope this article is useful for the readers.

Thanks for reading my article. If you like my blog and if you are interested in getting the latest updates on new articles, kindly follow me through one of these options.

F5Debug FacebookF5debug LinkedInF5debug TwitterF5debug GooglePlusF5debug RSSFeed

Posted in Windows Phone 7 | Tagged: , , , , , , , , , , , | 1 Comment »

Learn Windows Phone 7 Development in 31 Days – Day 26 – Working with Creating a Local Database in WP7

Posted by Karthikeyan Anbarasan on February 26, 2012

01 Download ToolsDownload Source CodeDownload as PDF FileSubscribe to F5debugComplete Article Listing

Introduction:

In this article we are going to see the usage of Isolated Storage by creating a local relational database and save the data locally that are accessible to the specific Windows Phone 7 application. The local relational database will be created on to the Isolated Storage Container where in Windows Phone 7 we need to make use of the LINQ to SQL for all the database operations. LINQ to SQL plays a major role in creating the data schema, selecting the data and making operation to the data as and when required. LINQ to SQL object model uses the System.Data.Linq.DataContext namespace to basically make a proxy call to the local database in the Isolated Storage container. LINQ to SQL Runtime plays as a bridge between the data context object and the real data to do the manipulations based on the user selection.

When considering making use of a local database for Windows Phone 7 Application development we need to consider some of the points mentioned below to get a much more performance and usage over the application.

  • Database file will be stored in the Isolated Storage Container.
  • Database is available specific to the application targeted as it is Isolated from other application.
  • LINQ is used to query the data from the database since TSQL Querying is not supported.
  • Local database feature can be accessed directly by adding System.Data.Linq assembly only since primary support is available with the framework.
  • Connection string much be use in the format of “Data Source =’isostore:/DirectoryName/Databasename.sdf”;

We are going to see how to perform the CRUD operation for the Windows Phone 7 Application Isolated Storage Local database using the Data Context class with a sample application. We will get clear idea on the below tasks on how to perform with the Windows Phone 7, which will be covered in details in this article

  • Creating a local database
  • Adding data to the local database
  • Fetching data from local database
  • Deleting data from the local database
  • Deleting a local database

Let us jump start to see the step by step process on how to achieve the above tasks with the Isolated Storage Local Database in Windows Phone 7 Application development by creating a sample application.

Steps:

Open Visual Studio 2010 IDE in administrator mode and create a new Silverlight for Windows Phone 7 Application project with a valid project name as shown in the screen below.

2012-02-20 07h49_23

Now let us design the User Interface to achieve the tasks listed above, Copy the below XAML code to get the unique user interface with the controls provided to achieve each and every task as shown in the screen below.

2012-02-21 08h11_10

XAML Code:


<Grid x:Name="LayoutRoot" Background="Transparent">
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto"/>
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>
 <TextBlock x:Name="PageTitle" Text="Employee DB" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
 </StackPanel>

<!--ContentPanel - place additional content here-->
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 <TextBox Height="72" HorizontalAlignment="Left" Margin="113,28,0,0" Name="txtName" Text="" VerticalAlignment="Top" Width="324" />
 <TextBlock Height="30" HorizontalAlignment="Left" Margin="33,57,0,0" Name="textBlock1" Text="Name" VerticalAlignment="Top" />
 <TextBox Height="72" HorizontalAlignment="Left" Margin="113,93,0,0" Name="txtAge" Text="" VerticalAlignment="Top" Width="324" />
 <TextBlock Height="30" HorizontalAlignment="Left" Margin="33,122,0,0" Name="textBlock2" Text="Age" VerticalAlignment="Top" />
 <TextBox Height="72" HorizontalAlignment="Left" Margin="113,159,0,0" Name="txtEmpid" Text="" VerticalAlignment="Top" Width="324" />
 <TextBlock Height="30" HorizontalAlignment="Left" Margin="33,188,0,0" Name="textBlock3" Text="Emp ID" VerticalAlignment="Top" />
 <Button Content="Create Database" Height="72" HorizontalAlignment="Left" Margin="33,255,0,0" Name="button1" VerticalAlignment="Top" Width="404" Click="button1_Click" />
 <Button Content="Add an Employee" Height="72" HorizontalAlignment="Left" Margin="33,319,0,0" Name="button2" VerticalAlignment="Top" Width="404" Click="button2_Click" />
 <Button Content="Delete an Employee" Height="72" HorizontalAlignment="Left" Margin="33,384,0,0" Name="button3" VerticalAlignment="Top" Width="404" Click="button3_Click" />
 <Button Content="Fetch all Employees" Height="72" HorizontalAlignment="Left" Margin="33,449,0,0" Name="button4" VerticalAlignment="Top" Width="404" Click="button4_Click" />
 <Button Content="Delete Database" Height="72" HorizontalAlignment="Left" Margin="33,514,0,0" Name="button5" VerticalAlignment="Top" Width="404" Click="button5_Click" />
 </Grid>
 </Grid>

Now we are done with the User interface design, now we need to create a data context and start using the data object model and start using the data schema to perform the operations. Let us start with adding the LINQ to SQL data context reference by right clicking the project from the solution explorer and adding the reference from the Add Reference menu as shown in the screen below.

2012-02-20 08h06_18

Once we added the reference for the System.Data.Linq to the application, we need to add the below namespaces to the code behind page of the MainPage.Xaml as shown in the screen below.

2012-02-20 08h09_53

Code Behind:


using System.Data.Linq;
 using System.Data.Linq.Mapping;
 using System.ComponentModel;
 using System.Collections.ObjectModel;

Now our first task is to create a database which is used locally isolated to the application. Since we are going to use the LINQ to SQL data context as a bridge between the local database and the data context we need to create 2 classes as shown below.

The first class is the Employee class which holds the properties for the fields that are tables and columns which are used to build the database, copy the below code to a new class Employee as shown in the screen below. The class has 3 properties that are going to be the data columns which we are going to get as inputs from the end users. If we notice in the below code we are providing the properties for each of the column with one being a primary key, and other are not null etc which we need to specify based on the database design that is normally changes based on the requirement.

2012-02-21 08h16_15

Code Behind:


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;
 using System.Data.Linq.Mapping;
 using System.Data.Linq;

namespace F5debugWp7LocalDatabase
 {
 [Table]
 public class Employee
 {
 [Column(IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false, AutoSync = AutoSync.OnInsert)]
 public int EmployeeID
 {
 get;
 set;
 }

[Column(CanBeNull = false)]
 public string EmployeeName
 {
 get;
 set;
 }

[Column(CanBeNull = false)]
 public string EmployeeAge
 {
 get;
 set;
 }
 }
 }

Now we need to add another class as EmployeeDataContext which is basically used as the database schema to create an instance, copy the code from the below code block as shown in the screen below.

2012-02-21 08h20_12

Code Behind:


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;
 using System.Data.Linq;

namespace F5debugWp7LocalDatabase
 {
 public class EmployeeDataContext:DataContext
 {
 public EmployeeDataContext(string connectionString)
 : base(connectionString)
 {
 }

public Table<Employee> Employees
 {
 get
 {
 return this.GetTable<Employee>();
 }
 }
 }
 }

Now let us start with our code on the MainPage.Xaml.cs to perform each of the tasks that are mentioned above.


Task 1 – Creating a local database

First let us start with creating a database which is the very first step we need to perform when we are going to use the local database storage to store the data with in the application Isolated Storage Container. We need to have a connection string which is pointing to the local database storage, let us create the connection string as a private constant as shown in the code below.

Code Behind:


private const string strConnectionString = @"isostore:/EmployeeDB.sdf";

Now we need to add the below code to create a database instance, here we are going to create an instance of the Data context by passing the connection string which is pointing to the local database storage as shown in the screen below.

2012-02-21 08h26_33

Code Behind:


private void button1_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 if (Empdb.DatabaseExists() == false)
 {
 Empdb.CreateDatabase();
 MessageBox.Show("Employee Database Created Successfully!!!");
 }
 else
 {
 MessageBox.Show("Employee Database already exists!!!");
 }
 }
 }

Task 2 – Adding data to the local database

Our second task is to add some records to the database which we have created, so to add the employee we need to create an instance of the data context and pass the properties that are matching the column properties which we are created in our data context initially. Here we are going to add an employee which has the Employee ID, Employee Name and Employee Age, we have created the instance and passed the values appropriately. Once we fetched the user inputs we need to insert the details on the submit so we use the InsertonSubmit method to add the employees as shown in the screen below.

2012-02-21 08h30_53

Code Behind:


private void button2_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 Employee newEmployee = new Employee {
 EmployeeID = Convert.ToInt32(txtEmpid.Text.ToString()),
 EmployeeAge= txtAge.Text.ToString(),
 EmployeeName=txtName.Text.ToString()
 };

Empdb.Employees.InsertOnSubmit(newEmployee);
 Empdb.SubmitChanges();
 MessageBox.Show("Employee Added Successfully!!!");
 }
 }

Task 3 – Fetching data from local database

Our next task is to fetch the consolidated list of data from the local database which normally as an end user we require to report the data in some particular format. So in order to fetch the data we use the LINQ query format to query the data based on the data table and the data context. We have used the simple List to consolidate the data using the LINQ query and we are using the string builder to consolidate the data as user readable as shown in the screen below.

2012-02-21 08h35_35

Code Behind:


public IList<Employee> GetEmployeeList()
 {
 IList<Employee> EmployeeList = null;
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
 EmployeeList = EmpQuery.ToList();
 }
 return EmployeeList;
 }

private void button4_Click(object sender, RoutedEventArgs e)
 {
 IList<Employee> EmployeesList = this.GetEmployeeList();

StringBuilder strBuilder = new StringBuilder();
 strBuilder.AppendLine("Employee Details");
 foreach (Employee emp in EmployeesList)
 {
 strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
 }
 MessageBox.Show(strBuilder.ToString());
 }

Task 4 – Deleting data from the local database

Our next task is to delete the user specific data from the local isolated storage database, this is straight forward as we query the data from the data context and delete it as shown in the screen below.

2012-02-21 08h41_58

Code Behind:


private void button3_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees where Emp.EmployeeName == txtName.Text select Emp;
 Employee EmpRemove = EmpQuery.FirstOrDefault();
 Empdb.Employees.DeleteOnSubmit(EmpRemove);
 Empdb.SubmitChanges();
 MessageBox.Show("Employee Deleted Successfully!!!");
 }
 }

Task 5 – Deleting a local database

Our final task is to delete the database completely once the user removes the application from the device. So to delete the data we can use the below code as shown in the screen below.

2012-02-21 08h45_38

Code Behind:


private void button5_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 if (Empdb.DatabaseExists())
 {
 Empdb.DeleteDatabase();
 MessageBox.Show("Employee Database Deleted Successfully!!!");
 }
 }
 }

Once we are done with the above code, our consolidated code will be like below. Just copy and paste it directly on to the cs page for easy access to the code which we have in the above 5 tasks.

Consolidated Code Behind:


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.Text;
 using System.Data.Linq;
 using System.Data.Linq.Mapping;
 using System.ComponentModel;
 using System.Collections.ObjectModel;

namespace F5debugWp7LocalDatabase
 {
 public partial class MainPage : PhoneApplicationPage
 {
 private const string strConnectionString = @"isostore:/EmployeeDB.sdf";

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

private void button1_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 if (Empdb.DatabaseExists() == false)
 {
 Empdb.CreateDatabase();
 MessageBox.Show("Employee Database Created Successfully!!!");
 }
 else
 {
 MessageBox.Show("Employee Database already exists!!!");
 }
 }
 }

private void button2_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 Employee newEmployee = new Employee {
 EmployeeID = Convert.ToInt32(txtEmpid.Text.ToString()),
 EmployeeAge= txtAge.Text.ToString(),
 EmployeeName=txtName.Text.ToString()
 };

Empdb.Employees.InsertOnSubmit(newEmployee);
 Empdb.SubmitChanges();
 MessageBox.Show("Employee Added Successfully!!!");
 }
 }

public IList<Employee> GetEmployeeList()
 {
 IList<Employee> EmployeeList = null;
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
 EmployeeList = EmpQuery.ToList();
 }
 return EmployeeList;
 }

private void button4_Click(object sender, RoutedEventArgs e)
 {
 IList<Employee> EmployeesList = this.GetEmployeeList();

StringBuilder strBuilder = new StringBuilder();
 strBuilder.AppendLine("Employee Details");
 foreach (Employee emp in EmployeesList)
 {
 strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
 }
 MessageBox.Show(strBuilder.ToString());
 }

private void button3_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees where Emp.EmployeeName == txtName.Text select Emp;
 Employee EmpRemove = EmpQuery.FirstOrDefault();
 Empdb.Employees.DeleteOnSubmit(EmpRemove);
 Empdb.SubmitChanges();
 MessageBox.Show("Employee Deleted Successfully!!!");
 }
 }

private void button5_Click(object sender, RoutedEventArgs e)
 {
 using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString))
 {
 if (Empdb.DatabaseExists())
 {
 Empdb.DeleteDatabase();
 MessageBox.Show("Employee Database Deleted Successfully!!!");
 }
 }
 }
 }

}

Now we are done with our code, to build and test the application press F5 and we can see the expected outputs as shown in the screen below.

Output Screens:

image

image

Conclusion:

So in this article we have seen how to use the local isolated storage to create and use the database by using the Linq to SQL data context and also we have seen the different steps to achieve the tasks mentioned on start of this article.

Thanks for reading my article. If you like my blog and if you are interested in getting the latest updates on new articles, kindly follow me through one of these options.

F5Debug FacebookF5debug LinkedInF5debug TwitterF5debug GooglePlusF5debug RSSFeed

Posted in Windows Phone 7 | Tagged: , , , , | 2 Comments »