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);

}
}
}

 

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.

Check Windows Azure Roles instance running in Emulator?

SDK :  Windows Azure SDK 1.5

In Build Windows Azure SDK 1.5 got announced. Windows Azure SDK 1.5 allows us to check whether Roles are running in emulator or not?

Static method IsEmulated returns Boolean value after checking whether Role instance is running in emulator or not.

clip_image001

Signature of IsEmulated is as below and it is part of the class RoleEnvironment

image

You can check running instance is in emulator or not as below,


bool isRunningInEmulator = RoleEnvironment.IsEmulated;
if (isRunningInEmulator)
Label1.Text = "Running in Emulator";
else
Label1.Text = "Hey you are on Cloud";

 

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.

Adding message in a Windows Azure Queue

In this post I will show you code snippet to add message in azure queue. I have written a function returning Boolean value and taking string input parameter to add as message in queue.

Create instance of cloud storage account

image

Create a client of azure queue

image

Get the reference of particular queue. Create queue if does not exist

image

Add message to queue

image

For your reference full source code is given below,


public bool AddMessageinQueue(string MessageToAdd, string QueueName)
{
try
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudQueueClient queueClient = account.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference(QueueName);
queue.CreateIfNotExist();

CloudQueueMessage m = new CloudQueueMessage(MessageToAdd);
queue.AddMessage(m);


return true;


}
catch (Exception ex)
{
return false;
}
}

&nbsp;

 

In this way you can add message in azure queue. 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.

Creating Deep Zoom Images through c# code

In this quick post, I will show you the creation of deep zoom images from Image in Azure BLOB. You may come with a requirement where you need to create deep zoom images using code. If you need deep zoom images for Pivot Viewer you can very much create it using several tools available. However you may have to create deep zoom images using code in some scenario. I am going to share code snippet for the same.

Very first you need to include DeepZoomTools dll as a reference in your project.

Add namespace

clip_image001

Next you need to create Container and set the basic properties as below,

clip_image003

Next create list of images you want to convert as deep zoom image. For purpose of this post, I am taking only one image. That image is in Azure Blob. So for that I am giving URL of the Image saved in azure Blob. You can choose image from local storage as well.

clip_image005

In last step you need to create deep zoom images using the create method of CollectorCreator

clip_image006

For reference full source code is as below,


protected void Button1_Click(object sender, EventArgs e)
{

string directoryToSaveDeepZoomImages = "D:\\abc";

CollectionCreator collectionCreator = new CollectionCreator();
collectionCreator.TileSize = 256;
collectionCreator.TileFormat = Microsoft.DeepZoomTools.ImageFormat.Png;
collectionCreator.ImageQuality = 1.0;
collectionCreator.TileOverlap = 0;

List<Microsoft.DeepZoomTools.Image> images =
new List<Microsoft.DeepZoomTools.Image>();
images.Add(new Microsoft.DeepZoomTools.Image("azuerbloburlforimage"));

collectionCreator.Create(images, directoryToSaveDeepZoomImages);
}

&nbsp;

In this way you can create deep zoom images. 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.

ROSLYN: Complier as Service ?

As a developer I see [rather forced to see] Compiler as a black box. It takes certain input and gives respective output. If I remember my college days classical definition of compiler was,

Compiler is system software which converts high level language in machine instructions line by line

Compilation process follows certain steps,

clip_image001

And as developer [most of us] focus on writing codes in very rigid time to meet certain business requirement. We really don’t bother about black box [Compiler].

In the process of creating executable binary instruction from high level language instructions, compiler generates huge amount of code or information. As of now developers do not have access to those generated information. Due to this restriction compiler appear as a black box.

In Build Microsoft revealed that now no longer compiler would be a black box.

 

clip_image002

As part of project codename ROSLYN Microsoft is trying to make complier generated information available to developers.

As Anders Hejlsberg said,

This Project is about to revising what compiler do. This project is about opening the compiler and making all the information available so developer can harness all of this knowledge. He added idea of “Compiler as service “also does not so bad“.

Essentially what ROSLYN would be capable of?

  • Creating variables on the fly
  • Creating objects on the fly
  • Inject instance of dynamic object in static languages
  • Converting VB code to c# and vice versa [this was the demo in Build]
  • With compilation information available developers would able to do refactor and reorganization of the code better.
  • Function written in c# or VB can be used with other languages
  • C# and VB would be more dynamic and many more exciting things.

See more about ROSLYN here in below video,

http://research.microsoft.com/apps/video/?id=152281

Personally I have only this information available about ROSLYN and I am looking very forward and exciting to see more on this. I hope we will have COMPILER as Service in VS 2012. I end with saying still I am not very much clear how ROSLYN will be given to developer as service and if given then the pay model.

If with ROSLYN compilation as service is near then I wonder debugging as service is also not that far  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.

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.

Upload Image from Silverlight to Azure BLOB using WCF

Working with Azure Blob is very common task you must be doing. Sometime you may come with requirement to upload an image from Silverlight client to Azure BLOB. In this post I am trying to help you in achieving this.

In this post I will show you below three stuffs.

  1. Uploading Image to Azure BOLB
  2. Abstracting BLOB upload code in WCF service
  3. Using WCF Service in Silverlight client to upload the image.

Expected Output

image

Flow of application

Step 1: On click event of Button File Dialog will open

Step 2: User will select Image and on selection Image will get uploaded in Azure Blob.

Step 3: On successful uploading URI of image will be returned from the service. Source property of Image control would be set to the returned URL.

Creating Service

Service Contract will have an function expose as operation contract as below,


[ServiceContract]
public interface IBLOBImageUpload

{

[OperationContract]
string UploadImage(byte[] Image);

}

Service is implemented as below,

  • We are creating a new GUID to set as file name of the image
  • Converting input byte array to stream
  • Calling a function to upload stream to blob
  • And returning URL of uploaded image
public string  UploadImage(byte[] Image)
{
string rowKeynFileName = Guid.NewGuid().ToString();
System.IO.Stream stream = new System.IO.MemoryStream(Image);
string imageUri= UploadImageinBlob(stream, rowKeynFileName );
return imageUri;

}

Function to upload Image in BLOB is as below

  • It is taking stream as input to upload
  • It is taking filename to be given to upload image
  •  DataConnectionString is connection string to Azure storage.
  •  urlContainer is name of the public container
  • Creating blob name by appending .jpg extension
  • Returning URL of uploaded image.

public string UploadImageinBlob(Stream Streams,string FileName)
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("urContainer");
string uniqueBlobName = string.Format("{0}.jpg", FileName);
CloudBlob blob = container.GetBlobReference(uniqueBlobName);
blob.Properties.ContentType = "image\\jpeg";
Streams.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(Streams);
string url = blob.Uri.OriginalString;
Streams.Close();
return url;

}

Configuring Service EndPoint

There are many points you need to put in mind while configuring the service end point.

  • Change maxReceivedMessageSize to 2147483647
  • Change maxBufferSize to 2147483647
  • Change maxArrayLength to 2147483647
  • Change maxBytePerRead to 2147483647
  • Change maxDepth to 2147483647
  • Change maxTableCharCount to 2147483647
  • Change maxStringContentLength to 2147483647
  • In Service behavior change data contract serliazer max object graph value to 2147483647

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="ServicesBinding"

maxReceivedMessageSize="2147483647"

maxBufferSize="2147483647">

<readerQuotas

maxArrayLength="2147483647"

maxBytesPerRead="2147483647"

maxDepth="2147483647"

maxNameTableCharCount="2147483647"

maxStringContentLength="2147483647" />

</binding>

</basicHttpBinding>

</bindings>

<services>
<service name="Service.BLOBImageUpload" behaviorConfiguration="ServiceData.Service1Behavior">

<endpoint address="" binding="basicHttpBinding" contract=" Service.IBLOBImageUpload " bindingConfiguration ="ServicesBinding" />

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="ServiceData.Service1Behavior">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

<dataContractSerializer maxItemsInObjectGraph ="2147483647"/>

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

</system.serviceModel>

&nbsp;

Now your service is written. You can choose service to host anywhere you want.

Creating UI

I have kept UI as sweet and simple as possible. There is just a button and image control. On click of button FileDialogBOX will open and user can select an image to upload. After successful uploading, URL of uploaded image in Azure blob will be returned and that will be set as source of Image control


<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>

<RowDefinition Height="100" />
<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Button x:Name="btn" Height="100" Width="100" Click="btn_Click" Content="Upload Image" />
<Image Grid.Row="1" x:Name="img" Height="auto" Width="auto" />
</Grid>

&nbsp;

Calling Service

You need to make a normal service call

  • On click event of the button opening the file dialog
  • Converting stream to byte array
  • Passing byte array as input to the function.
  • GetImageSource function is converting given string URL as image source to be set as source of image control

public partial class MainPage : UserControl
{

public OpenFileDialog fileDialog = null;
public MainPage()
{
InitializeComponent();
}

private void btn_Click(object sender, RoutedEventArgs e)
{
Stream strm;
byte[] buffer = null; ;
fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "All Files|*.*";
bool? retval = fileDialog.ShowDialog();
if (retval != null && retval == true)
{
strm = fileDialog.File.OpenRead();
buffer = new byte[strm.Length];
strm.Read(buffer, 0, (int)strm.Length);
}

BLOBImageUploadClient proxy = new BLOBImageUploadClient ();

proxy.UploadImageAsync(buffer);
proxy.UploadImageAsync += new EventHandler<UploadImageCompletedEventArgs>(proxy_UploadImageCompleted);
}

void proxy_UploadImageCompleted (object sender, UploadImageCompletedEventArgs e)
{

img.Source = GetImageSource(e.Result.ToString());
}

private ImageSource GetImageSource(string fileName)
{
return new BitmapImage(new Uri(fileName, UriKind.Absolute));
}

}
}

&nbsp;

This is what all you need to do as far as coding is concern. Yes you may need to put clientacccesspolicy.xml at the root location of server where you are hosting WCF service to avoid cross domain problem.

I hope this post was useful. Thanks for reading Smile

If you find my blogs useful you may like to,

Follow me on twitter http://twitter.com/debug_mode

Like Facebook page of this 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.

Step by step installation guide to install Windows 8 Developer Preview on Virtual Box

image

In Microsoft Build conference all we got an opporunity to have a first look on most awaited Windows 8 . Microsoft revealed Developer Preview of Windows 8 on 13th september 2011. Windows 8 is adhering Metro Design Gudielines. Without going much into deep technical discussions on features of Windows 8 , in this post I have targeteed to show you installation steps of Windows 8 on virtual box.

So to strat with go and dowanlaod Windows 8 developer preview from below link. Choose appropirate link as of your syste, {Like : 32 bit or 64 bit } to downlaod and install.

http://msdn.microsoft.com/en-us/windows/apps/br229516

once downloaded , mount ISO image to virtual drive or if you want , go ahead and burn it tgo DVD 9.

Next step is to downalod Virtual box and installed it. When virtual box is installed we will install Windows 8 developer perview on virtaul box.

Go ahead and downlaod virtual box from below link,

http://www.virtualbox.org/wiki/Downloads

Insatllation steps are farly straight forward . So I am not going to bore you to death by writing one or two sentences with each screen shorts. I am just posting all the screen you may get while installing , just follow the screens to get Windows 8 installed on Virtual box.

While installing virtual box whereever you get oracle security warning . clcik run and move ahead

clip_image001

clip_image002

clip_image003

clip_image004

clip_image005

clip_image006

Check the check box and click Install

clip_image007

clip_image008

clip_image009

Give name of the virtual box and choose version of your host opearting system from the drop down.

clip_image010

Recommened memory is 1024MB. If you want you can amend it.

clip_image011

Select Create new hard disk option

clip_image012

Now you need to provide file location and size.

clip_image013

clip_image014

clip_image016

clip_image017

On create button click you will get below screen. Click on Seeetings menu .

clip_image019

Here you need to click on the Sysytem tab and make sure that Enable IO APIC is checked

clip_image020

In Processor tab make sure Enable PAE/NX is checked.

clip_image021

In Accelration tab make sure both the check box are checked.

clip_image022

Next go to storage tab and selcet Empty option. And from Attribute section select IDE Secondary Master from drop down

clip_image024

Choose Virtaul CD/DVD option here .

clip_image025

Select ISO file of Windows 8 developer preview you downloaded and then click on Ok button

clip_image027

clip_image028

Now click on the start button to start installation of Windows 8 .

clip_image030

clip_image031

clip_image033

clip_image035

clip_image037

clip_image039

clip_image041

clip_image043

clip_image045

clip_image047

clip_image049

clip_image051

clip_image053

clip_image055

clip_image056

clip_image058

Here you got Windows 8 developer preview installed on virtual box. Enjoy and explore  Smile

 

I hope this post was useful. Thanks for reading. 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 this 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.