Code to Search in Windows Phone 7

In this post I will show you how you could search a particular item on windows phone 7. You can achieve search using launchers. SearchTask class is used to search on Windows Phone 7.

Expected Output

User will type the word to search and click on Search on Phone button. Then application will search on device and web both and give the search result.

image

 

To search an item you will have to use launcher SearchTask. This class is defines as below,

image

You can see in the definition of class that you can set the SearchQuery. SearchQuery is defined as string property in the class.

To work with SearchTask launcher first make instance of this class as below,

clip_image001

Then set the search criteria

clip_image002

In above code we are reading the search criteria from a text box.

For your reference full code to search is as below,


using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
namespace abc
{
public partial class MainPage : PhoneApplicationPage
{

public MainPage()
{
InitializeComponent();

}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
SearchTask searchonPhoneTask = new SearchTask();
searchonPhoneTask.SearchQuery = txtSearchItem.Text;
searchonPhoneTask.Show();

}
}
}

Design

Design of the page is simple. Application is having one textbox and one button. On click event of the button, it would search the text entered in the textbox.


<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="search phone" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="search on phone" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Button Grid.Row="1" x:Name="btnSearch" Content="Search on Phone" Height="77" Click="btnSearch_Click" Width="auto" Margin="0,23,0,0" />
<TextBox x:Name="txtSearchItem" Width="auto" Height="77" Margin="0,0,0,83" Grid.RowSpan="2" />
</Grid>
</Grid>

This is all you require to search on web and device from your windows phone application. I hope this post is useful. Thanks for reading Smile

 

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Code to select photo on Windows Phone 7

In this post we will see how could we select a photo saved on device and bind it as source of image control on our application.

Expected Output

image

 

image

To work with photo on device you need to work with Choosers. To work with Choosers you need to add Microsoft.Phone.Tasks namespaces.

clip_image001

PhotoChooserTask class allows us to choose a photo on the device. To choose a photo you need to make an object of this class. PhotoChooserTask class is defined as below,

image

You can see in definition of class that either you can choose photo from camera by setting ShowCamera value to true . In this post we will choose save photo from the device. You have option to set pixel height and width value of selected photo as well.

So very first, you need to create instance of PhtoChooserTask ,

image

And then set the height and width of the selected photo. By setting these values user will able to select only 400×400 pixels of the photo.

image

Next show the chooser to user to select the photo

image

PhtoChooserTask returns selected photo as byte array. In completed event, you need to decode the byte array as writeable bitmap and then set as the source of Image control. For that you need to add below namespaces

image

And decode the byte array to writable bitmap as below,

clip_image002

And set the writeablebitmap to the source of image control ,

clip_image003

For your reference full source code is as below,


using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone;

namespace PhoneApp6
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}

private void btnSelectPhoto_Click(object sender, RoutedEventArgs e)
{
PhotoChoos erTask taskToChoosePhoto = new PhotoChooserTask();
taskToChoosePhoto.PixelHeight = 400;
taskToChoosePhoto.PixelWidth = 400;
taskToChoosePhoto.Show();
taskToChoosePhoto.Completed += new EventHandler<PhotoResult>(taskToChoosePhoto_Completed);
}

void taskToChoosePhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
string fileName = e.OriginalFileName;
WriteableBitmap selectedPhoto = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
imgSelected.Source = selectedPhoto;

}
}
}
}

&nbsp;

Design

I have just put one button and image control. On click event of the button user will select photo on device and after clicking on Ok button, selected photo will be set as source of the image control.


<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="select photo" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Select Photo" 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">
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Button x:Name="btnSelectPhoto" Content="Select Photo on Device" Height="100" Width="auto" Click="btnSelectPhoto_Click" />
<Image x:Name="imgSelected" Height="auto" Width="auto" Grid.Row="1" />
</Grid>
</Grid>

&nbsp;

In this way you can select a photo on Windows Phone 7. I hope this post is useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Reading coordinate values using Accelerometer API in Windows Phone 7

In this post we will see how to read different axis values using Accelerometer API.

To work with Accelerometer API first you need to add reference of Microsoft.Devices.Sensors

clip_image001

Then below namespace,

clip_image001[6]

Now to capture X Axis, Y Axis and Z Axis value you need to follow below steps

Step 1

Create task object of Accelerometer chooser

clip_image001[8]

Step 2

Call the callback method when user will complete a task and Implement the completed event to capture user data and status when user complete as tasks.

clip_image001[10]

Step 3

Call the start method to start the accelerometer,

clip_image001[12]

Step 4

We can read value of XAxis, YAxis and ZAxis as below along with timestamp of capturing data as below in the completed event. We are changing double values to string.

clip_image001[14]

You can save these data for further use that when accelerometer value got changed.

Let us run the application in debug mode to see value got captured,

image

When you click on Capture Data button control will go to Accelerometer reading changed event. Then each time you will move the ball Accelerometer reading changed event will get called.

image

For your reference full code is as below,


using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;

namespace EncryptingandDecryptinginMango
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
void accelerometerTaskObject_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
string xCordinate = e.X.ToString("0.00");
string yCordinate = e.Y.ToString("0.00");
string zCordinate = e.Z.ToString("0.00");
DateTimeOffset timeCaptured = e.Timestamp;
}

private void btnCaptureData_Click(object sender, RoutedEventArgs e)
{

var accelerometerTaskObject = new Accelerometer();
accelerometerTaskObject.ReadingChanged +=
new EventHandler<AccelerometerReadingEventArgs>
(accelerometerTaskObject_ReadingChanged);

try
{
accelerometerTaskObject.Start();
}
catch
{
//Error in starting the Accelerometer
}

}
}
}

In this way you can work with Accelerometer API to capture different axis values. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Code to Send SMS in Windows Phone 7

Launchers are used to perform task provided by phone operating system. Sending SMS is feature of Windows phone operating system and can be used by Launcher API. SmsCompseTask launcher is used to send SMS. This task class is defined as below,

image

To work with SmsComposeTask, first you need to add namespace of Microsoft.Phone.Task

clip_image001

Then create instance of SmsComposeTask.

clip_image003

Next you need to set required or optional parameter for the launcher task. Required parameters for SmsComposeTask are

  1. To number
  2. Body of SMS

 

So first set the parameter as below,

clip_image001[6]

And SMS body as below,

clip_image002

Last step you need to launch SMS send application provided by operating system. You can show that as below,

clip_image003

If you put all code together and want to send SMS on click event of button then full code will be as below,


using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace test
{
public partial class MainPage : PhoneApplicationPage
{

public MainPage()
{
InitializeComponent();
}

private void btnSendSMS_Click(object sender, RoutedEventArgs e)
{

SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "9158153792";
smsComposeTask.Body = "hey I am sending u SMS";
smsComposeTask.Show();

}
}
}

&nbsp;

When you run above code you will get application running as below,

image

When you click on Send SMS button, you will get drafted SMS with TO and body set as below,

image

Now you can either edit the message or set other recipients or send SMS as it is. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Protecting password or any data in Windows Phone 7 using Data Protection API

There may be many scenarios, when you need to save data in protected form for your application in isolated storage. Of course you have an option

  • To encrypt the data with some encryption algorithm
  • Save in the isolated storage

Problem with above approach is either you will have to store the key in isolated storage or read it from some external sources. In major scenarios key is residing on the phone itself and it brings the flaw.

Windows Phone Data Protection API helps us to protect data at the application level. On Windows Phone 7 every application has their own key. This key gets created when you first run the application.

Using DP API, all it takes one line of code to encrypt and decrypt the data.

To Encrypt

image

First line of code is converting string to byte array. To encrypt data only you need to pass byte array.

To Decrypt

image

Password is name of the file in which encrypted data is stored. All it takes only one line of code to decrypt.

If you closely look into ProtectedData class,

image

This is static class with two static methods. If required you can pass entropy as parameter also.

Design page

Now let us design a page like below, Design is very simple with one text box taking input to protect the data. There are two buttons, one to protect data and another to decrypt and retrieve protected data.

clip_image001

XAML of design is as below,


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="PageTitle" Text="protected data" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="180" />
</Grid.RowDefinitions>
<TextBox x:Name="txtDataToProtect" HorizontalAlignment="Left" Width="450" Height="80" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,0" Grid.Row="1">
<Button x:Name="btnReteriveData" Content="Reterive" Height="100"  Click="btnReteriveData_Click" Width="200" />
<Button x:Name="btnProtectData" Content="Protect" Height="100"  Click="btnProtectData_Click" Width="260" />
</StackPanel>
</Grid>
</Grid>

Protecting Data


private void btnProtectData_Click(object sender, RoutedEventArgs e)
{
byte[] passwordData = Encoding.UTF8.GetBytes(txtDataToProtect.Text);
byte[] EncryptedPasswordData = ProtectedData.Protect(passwordData, null);
SaveToFile(EncryptedPasswordData, "password");
}

In above code,

  1. We are converting text to byte array
  2. Passing byte array to protect
  3. We are applying no entropy.
  4. Saving protected data to a file called password. We will have to fetch encrypted data from file password while retrieving.
  5. To save protected data calling a function called SaveToFile

SaveToFile function


private void SaveToFile(byte[] EncryptedPasswordData,string FileName)
{
IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Create, FileAccess.Write, getApplicationFile);
Stream writer = new StreamWriter(fileAsStream).BaseStream;
writer.Write(EncryptedPasswordData, 0, EncryptedPasswordData.Length);
writer.Close();
fileAsStream.Close();
}

In above code,

  1. We are passing byte array to save
  2. We are passing filename to say where to save the data in application
  3. Reading application file and opening it as file stream
  4. Writing byte array to file stream.

Decrypting data


private void btnReteriveData_Click(object sender, RoutedEventArgs e)
{
byte[] data = ReadFromFIle("password");
byte[] passwordByte = ProtectedData.Unprotect(data, null);
string password = Encoding.UTF8.GetString(passwordByte, 0, passwordByte.Length);
txtDataToProtect.Text = password;

}

In above code,

  1. We are first reading encrypted data from the isolated storage file. If you notice file name is same.
  2. Calling unprotect method and passing encrypted byte array to decrypt.
  3. Converting decrypted byte array to string and displaying in text box

ReadFromFile function


private byte[] ReadFromFIle(string FileName)
{

IsolatedStorageFile getApplicationFile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileAsStream = new IsolatedStorageFileStream(FileName, System.IO.FileMode.Open, FileAccess.Read, getApplicationFile);
Stream reader = new StreamReader(fileAsStream).BaseStream;
byte[] password = new byte[reader.Length];
reader.Read(password, 0, password.Length);
reader.Close();
fileAsStream.Close();
return password;
}

In above code,

  1. Reading application file and opening it as file stream
  2. Reading byte array to file stream.

If you would have noticed we have not provided KEY either to ENCRYPT or DECRYPT the data.

In this way you can protect data in Windows Phone 7. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Global Application Bar in Windows Phone 7

In a Windows Phone 7 application, Application Bar is very useful. With as assumption that, you know what is Application Bar? I will discuss with you

  • How Application Bar can be used as static resource?
  • How to make Application Bar as global resource?
  • How to use same Application Bar in multiple pages?

Designing Global Application Bar

To use Application Bar globally in the application, you need to make it as Static Resource. For that open App.xaml and add below code in the resource section,


<Application.Resources>
<shell:ApplicationBar x:Key="MyGlobalAppBar" IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/button1.png" Text="FIRST BUTTON" Click="ApplicationBarIconButton_Click" />
<shell:ApplicationBarIconButton IconUri="/button2.png" Text="SECOND BUTTON" Click="ApplicationBarIconButton_Click_1" />
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="First Menu Item" Click="MenuItem1_Click" />
<shell:ApplicationBarMenuItem Text="Second Meny Item" Click="MenuItem2_Click" />
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</Application.Resources>

There are few points worth discussing

  • I have added as resource two images and setting them as image of the button
  • There are two buttons and two menu items. You are free to change this as of your requirement.
  • Button and menu item click event is being handled on the app.xaml.cs file
  • Key of the global application bar is MyGlobalAppBar . You need to use this key at time of using this application bar. However you are free to give different key and use them accordingly

Code behind for Global Application Bar

In App.Xaml.cs file you need to handle the click event of buttons and menu item as below,


private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
MessageBox.Show("I am Button 1");
}
private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
{
MessageBox.Show("I am Button 2");
}
private void MenuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show("I am Menu Item 1");
}
private void MenuItem2_Click(object sender, EventArgs e)
{
MessageBox.Show("I am Menu Item 2");
}

&nbsp;

Creating page to use Global Application Bar

You need to set the application bar in each page as below. If you remember MyGlobalAppBar is key of the application bar we created as static resource.

clip_image001

Now when you run the application, you should get below Application Bar on each page you have set it .

image

I hope this post was useful. Thanks for reading and tune in for the next post  Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

System Tray ProgressIndicator in Windows Phone 7.5 or Mango phone

Windows Phone 7.5 (Mango) provides a Progress Indicator on System Tray to show progress of async operation.

clip_image001

ProgressIndicator is a dependency object and can be data bind to the System Tray. ProgressIndicator class is defined as below,

clip_image002

Using ProgressIndicator

To use ProgressIndicator, first you need to add the namespace,

clip_image003

And then create it as below,

clip_image004

On the async operation status you can set visibility to false.

clip_image005

Finally you need to set it to the System Tray or Status Bar as below,

clip_image006

Putting all together below listed source code will give you output shown earlier in the post.


using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
SystemTray.SetIsVisible(this, true);
SystemTray.SetOpacity(this, 0.5);
SystemTray.SetBackgroundColor(this, Colors.Black);
SystemTray.SetForegroundColor(this, Colors.Blue);
ProgressIndicator progressIndicator = new ProgressIndicator();
progressIndicator.IsVisible = true;
progressIndicator.IsIndeterminate = true;
progressIndicator.Text = "Hey I am Progress Indicator";
SystemTray.SetProgressIndicator(this, progressIndicator);

}
}
}

&nbsp;

In this way you can use system tray progress indicator. I hope this post was useful. Thanks for reading  Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Local Database application for windows Phone

Version: Windows Phone 7.1, Mango, 7.5 [at time of writing this post this post was applicable to said versions]

Local data base support in windows phone 7.1 is enabled via LINQ to SQL. LINQ to SQL enables application to use isolated storage as database.

clip_image001

Each application is having own isolated storage and LINQ to SQL in Windows 7.1 enables us to use that as local database. LINQ to SQL gives us object model to work with local database.

clip_image002

Image taken from MSDN.

There is few points’ worth to be discussed about local database

  • · It runs as application process
  • · Unlikely to SQL Server , it does not run in the background
  • · Local database belongs to a particular application and cannot be  accessed   by other application
  • · Local database resides in isolated storage
  • · Local database does not support TSQL.

Application

I am going to create a table Bloggers in the local database of Windows Phone 7.1. UI will be as below to work with the data from the local storage. User cane

  • Add detail of blogger to local database.
  • Delete blogger from the local database.
  • Page will get refreshed dynamically.

image

Create a windows phone application by choosing target framework 7.1.After creation of project add reference of System.Data.Linq to the project.

clip_image002

Creating Entity class

Note: Make sure you are calling OnNotifyPropertyChanged() after seeting the value of the property [Edited]

Let us go ahead and decide on database schema and entity of database.. I am going to have table called Bloggers in database. To represent table you need to create an entity class. I am implementing INotifyPropertyChanged interface to support two way binding. However you can choose not to implement and this interface has nothing to do with local database support.

You need to add the namespace to class,

clip_image003

And implement interface as below,

clip_image004

Since this class is representing table so attribute it with the [Table]

Implement the property of INotifyPropertyChanged as below,

clip_image006

Now each column of the table will be mapped to a property in the entity class as below. Name property is representing Name column of table.

clip_image007

You will have to create properties like below for all the columns you want as part of table. You must have a primary key column in the table and that could be created by giving extra parameter to column attribute.

clip_image008

After adding all the columns Bloggers class would be as below,


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

namespace LocalDatabaseApplication.Model
{

[Table]
public class Bloggers : INotifyPropertyChanged
{
private string name;
[Column]
public string Name
{
get
{
return name;
}
set
{
NotifyPropertyChanged("Name");
name = value;
}
}

private string interest;
[Column]
public string Interest
{
get
{
return interest;
}
set
{
NotifyPropertyChanged("Interest");
interest = value;
}
}

private int  id;
[Column(IsPrimaryKey=true,
CanBeNull= false,
IsDbGenerated= true ,
DbType="INT NOT NULL Identity",
AutoSync=AutoSync.OnInsert)]
public int  Id
{
get
{
return id;
}
set
{
NotifyPropertyChanged("Id");
id = value;
}
}

private int  totalposts;
[Column]
public int Totalposts
{
get
{
return totalposts;
}
set
{
NotifyPropertyChanged("Totalposts");
totalposts = value;
}
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

#region INotifyPropertyChanging Members

#endregion

}
}

In this way you have created entity class representing Bloggers table.

Creating Datacontext class

Create a class and inherit DataContext class

clip_image001[7]

Next you need to set the connection string as below,

clip_image003

Pass connection string to base class as below,

clip_image004[6]

Context class would be implemented as below,


using System.Data.Linq;

namespace LocalDatabaseApplication.Model
{
public class BloggersDataContext : DataContext
{
public static string DBConnectionString = "Data Source=isostore:/Bloggers.sdf";

public BloggersDataContext(string connectionString)
: base(connectionString)
{
}
public Table<Bloggers> bloggers;

}
}

Creating Database

There are two steps involved in creating database

  1. Check whether databases exist or not?
  2. If not exist then create database.

You will have to perform above two steps at application constructor. So code will be added to App.xaml.cs.

Add below line of codes to constructor of application,


public App()
{

using (BloggersDataContext db = new BloggersDataContext(BloggersDataContext.DBConnectionString))
{
if (db.DatabaseExists() == false)
{
//Create the database
db.CreateDatabase();
}
}

Using Database

As of now database schema has been created. To use it on the page very first you need to implement INotifyPropertyChanged on the page as below,

clip_image002[6]

Next step you need to do is

  1. Create reference of BloggerDataContext
  2. Define a property as observablecollection of Bloggers entity

clip_image003[6]

Now in constructor create instance of BloggersDataContext ,

clip_image005

Adding new Record

Adding new record is very much straightforward.

  1. Create instance of Bloggers
  2. Add it to the property define on the page
  3. Call InsertOnSubmit
  4. Finally call SubmitChanges.

clip_image006

Fetching all Records

You can use simple LINQ query to fetch all the records.

clip_image007[6]

lstData is name of list box here.

Deleting a Record

To delete a particular item

  1. Fetch the selected item from list box
  2. Get reference of selected item in data context
  3. Remove selected item

clip_image009

Full code for reference is as below,


using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using LocalDatabaseApplication.Model;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace LocalDatabaseApplication
{
public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
{

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion

private  BloggersDataContext  bloggerDB;
private ObservableCollection<Bloggers > bloggerItems;
public ObservableCollection<Bloggers> BloggerItems
{
get
{
return bloggerItems;
}
set
{
if (bloggerItems != value)
{
bloggerItems = value;
NotifyPropertyChanged("BloggerItems");
}
}
}
public MainPage()
{
InitializeComponent();
bloggerDB = new BloggersDataContext(BloggersDataContext.DBConnectionString);
this.DataContext = this;
}

private void btnUpdate_Click(object sender, EventArgs e)
{
MessageBox.Show("Update");
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
var bloggers = from r in bloggerDB.bloggers select r;
BloggerItems = new ObservableCollection<Bloggers>(bloggers);
lstData.ItemsSource = BloggerItems;
base.OnNavigatedTo(e);
}
private void Button_Click(object sender, RoutedEventArgs e)
{

Bloggers data = (sender as Button).DataContext as Bloggers;
ListBoxItem bloggerToDeleteFromListBox = this.lstData.ItemContainerGenerator.ContainerFromItem(data)
as ListBoxItem;

var bloggerToDelete = (from r in bloggerDB.bloggers
where r.Id == data.Id
select r).FirstOrDefault();
BloggerItems.Remove(bloggerToDelete);
bloggerDB.bloggers.DeleteOnSubmit(bloggerToDelete);
bloggerDB.SubmitChanges();
MessageBox.Show("Delete");
}

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Bloggers bloggerToAdd = new Bloggers
{
Interest = txtInterest.Text,
Name = txtName.Text ,
Totalposts = Convert.ToInt32(txtPosts.Text)
};

BloggerItems.Add(bloggerToAdd);
bloggerDB.bloggers.InsertOnSubmit(bloggerToAdd);
bloggerDB.SubmitChanges();
MessageBox.Show("Add");
}
}
}

&nbsp;

Design UI

For purpose of this post, I have put UI very simple. UI consists of

  1. List box to display data
  2. Textbox to get user input to add
  3. Button to add and delete

For reference XAML of UI is as below,

<phone:PhoneApplicationPage
x:Class="LocalDatabaseApplication.MainPage"
xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>"
xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="<a href="http://schemas.microsoft.com/expression/blend/2008">http://schemas.microsoft.com/expression/blend/2008</a>"
xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-compatibility/2006">http://schemas.openxmlformats.org/markup-compatibility/2006</a>"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
<!--LayoutRoot is the root grid where all page content is placed-->
<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="local database application" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="320" />
</Grid.RowDefinitions>
<ListBox x:Name="lstData" Margin="5,7,6,15">
<ListBox.ItemTemplate>
<DataTemplate >
<Grid x:Name="TopGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Margin="5,5,5,5" Click="Button_Click">
<Button.Template >
<ControlTemplate >
<Image Source="delete.png" VerticalAlignment="Center"   Height="30" Width="30"/>
</ControlTemplate>
</Button.Template>
</Button>
<Grid x:Name="nestedGrid" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock Text="{Binding Interest}"  Style="{StaticResource PhoneTextSubtleStyle}" />
<TextBlock Text="{Binding Totalposts}" Style="{StaticResource PhoneTextAccentStyle}"/>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid HorizontalAlignment="Left" Height="320" VerticalAlignment="Bottom" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="80"/>
<RowDefinition Height="80"/>
<RowDefinition Height="80"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="77" />
<ColumnDefinition Width="29*" />
</Grid.ColumnDefinitions>
<TextBlock  Text="Name" Style="{StaticResource PhoneTextNormalStyle}" />
<TextBlock  Grid.Row="1"  Text="Interest" Style="{StaticResource PhoneTextNormalStyle}" Grid.ColumnSpan="2" Margin="12,0,6,0" />
<TextBlock  Grid.Row="2"  Text="Posts" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBox x:Name="txtName" Grid.Column="1" Margin="35,0,-327,0" VerticalAlignment="top" Height="80" />
<TextBox x:Name="txtInterest" Grid.Row="1" Grid.Column="1" Margin="35,0,-327,0" VerticalAlignment="top" Height="80" />
<TextBox x:Name="txtPosts" Grid.Row="2" Grid.Column="1" Margin="35,0,-327,0" />

<Button x:Name="btnAdd" Grid.Row="3" Content="Add" Click="btnAdd_Click" VerticalAlignment="Top" Grid.ColumnSpan="2" Margin="0,0,-296,0" />
</Grid>
</Grid>
</Grid>

</phone:PhoneApplicationPage>

Press F5 to run the application and you should get application running with local database. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Fetching selected value from List Box in Silverlight

Let us say you have a list box as below. You have a requirement that on click of button fetch value of the same row button belongs to.

For example if you are clicking second cross, you should able to fetch value Pinal, SqlServer , 500 from the list box.

clip_image001

In above list box

  • There is a button (cross image) in each item.
  • Text blocks bind with data.
  • List box is bind to the collection.

XAML of list box is as below,

<ListBox x:Name="lstData" Margin="5,7,6,15">
<ListBox.ItemTemplate>
<DataTemplate >
<Grid x:Name="TopGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Margin="5,5,5,5" Click="Button_Click">
<Button.Template >
<ControlTemplate >
<Image Source="delete.png" VerticalAlignment="Center"   Height="30" Width="30"/>
</ControlTemplate>
</Button.Template>
</Button>
<Grid x:Name="nestedGrid" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock Text="{Binding Interest}"  Style="{StaticResource PhoneTextSubtleStyle}" />
<TextBlock Text="{Binding Totalposts}" Style="{StaticResource PhoneTextAccentStyle}"/>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>

&nbsp;

Item source of list box is set to List of Bloggers.

image

Bloggers class is as below,

Note: Make sure you are calling OnNotifyPropertyChanged() after seeting the value of the property [Edited]


public class Bloggers : INotifyPropertyChanged
{
private string name;
public string Name
{
get
{
return name;
}
set
{
NotifyPropertyChanged("Name");
name = value;
}
}

private string interest;
public string Interest
{
get
{
return interest;
}
set
{
NotifyPropertyChanged("Interest");
interest = value;
}
}

private int  id;
public int  Id
{
get
{
return id;
}
set
{
NotifyPropertyChanged("Id");
id = value;
}
}

private int  totalposts;
public int Totalposts
{
get
{
return totalposts;
}
set
{
NotifyPropertyChanged("Totalposts");
totalposts = value;
}
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

&nbsp;

}

&nbsp;

Now on click event of button if you want to fetch particular list item then first take data context as blogger

clip_image002

Then fetch list box item as below,

clip_image004

Now you would able to use data as below

clip_image005

On click event of button you need to write code as below to fetch particular item list value.


private void Button_Click(object sender, RoutedEventArgs e)
{

Bloggers data = (sender as Button).DataContext as Bloggers;
ListBoxItem bloggerToDeleteFromListBox = this.lstData.ItemContainerGenerator.ContainerFromItem(data)
as ListBoxItem;
var Name = data.Name
}

In this way you can fetch the value of particular list item. I hope this post was useful. Thanks for reading J

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Windows Phone 7.5 or Mango Phone Application Performance analysis

When you create an application along with killer user interface, you ought to consider various performance parameters of your application as well. There are certain eligibility performances criteria, your application must pass to be accepted in the Marketplace. These criteria may check your application

1. For maximum memory usage

2. Launching time of your application

3. How responsive is your application

There is Market Place Test Kit you can use to test likely of your application accepted by the marketplace.

Measuring performance of your application should be always the essential task of your application creation life cycle.

 

clip_image001

In Windows Phone 7.1 you get a Performance Analysis Tool. This tool helps you to do analysis on

  • CPU usage
  • Memory Usage
  • How you are handling garbage collection
  • What is your application frame rate

You get performance analysis tool by either pressing ALT+F1 or selecting it from Debug menu option.

clip_image002

There are few thumb rules you need to follow to get best result out of performance analysis tool

  1. You should target device rather emulator
  2. Run the project in release mode rather than debug mode

Just after clicking on Start Widows Phone Performance Analysis, you will get an empty performance log created for you in the solution explorer.

clip_image003

When you choose for performance analysis, you will be prompted to choose from two options

  1. Execution
  2. Memory

clip_image004

Choose your option and click on Launch Application. Application will be launched with performance analysis.

Come back to visual studio and click on Stop Profiling. You will get progress messages that analyzed data is being created.

clip_image006

clip_image008

When you click on .sap file you will get performance graph as below,

clip_image010

Frame Rates provides information about number of frame redrawn each second. This information is only available when display UI is getting updated. Windows Phone 7 application should have 30 to 60 second frame rate per second.

In CPU usage there are four colors and each color have their own significant meaning.

clip_image011

Memory usage says about amount of phone memory used in application. It is measured in mega bytes

Storyboard gives information about animation in the application. There are two types of animation and represented by two different colors.

clip_image012

Image loads says about image load as assets into the phone memory.

GC events say about when garbage collector collects free memory.

By having all above information discussed above you can very much do performance analysis of your application. Have a good time writing good performance centric application Smile

If you find my blogs useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.