A new home

I’ve made the move to WordPress!

You should be automatically redirected in 5 seconds. Please visit World Wide Code on Wordpress

Hope to see you there!

Monday, March 28, 2011

News reader: Windows Phone 7 Panorama App


Every one must have header about the panorama control available for the Windows Phone 7 applications. But have you created an app using it? Let's begin creating a simple news reader app using the panorama control.
At first, create a panorama application project in Visual Studio 2010. This adds a lot of files to your project, you may choose to just modify than or add your own files. The basic structure that VS 2010 creates for you is perfect for this app. Let us first concentrate on the UI design.
The app will have two panorama screens, the first one will display the top stories, while the other will show a list of news categories for the user to choose.
Every panorama screen has a title, that identifies what the screen is about or what you can expect it to have. I would be naming my screen "top stories". You might wonder why the lower case, well that's what most of the WP7 apps have titles, all in lower case.
The content of the screen is pretty straight forward, it contains a list box display all the news stories.
<!--Panorama item one-->
<PanoramaItem Header="top stories">

<ListBox ItemsSource="{Binding TopStories}" SelectionChanged="MainListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" Style="{StaticResource PhoneTextTitle2Style}"/>
<TextBlock Text="{Binding PublishedDate}" TextWrapping="Wrap" Margin="12,5" Style="{StaticResource PhoneTextSmallStyle}" FontStyle="Italic"/>
<TextBlock Text="{Binding Description}" TextWrapping="Wrap" Margin="12,2" Style="{StaticResource PhoneTextSubtleStyle}"/>
<!--StackPanel>-->
</DataTemplate>
<!--ListBox.ItemTemplate>-->
<!--ListBox>-->
</PanoramaItem>
When the user selects any item in the list box, the user would be redirected to the browser display the entire article.  Following code accomplishes this task for you.

Wednesday, March 2, 2011

Dynamic loading of Assemblies

When you build your silverlight application, there arises a point where your xap is a couple of MB(s) in size.  To improve your applications download experience you may decide to split your application into different modules.
In this regard, I would advise you to keep only one application with its output as a xap, all the rest should be class library projects.

In this post I will explain the method of loading such dynamic modules into your application. For this sample, I have used three projects namely,

  • SampleApp as the main navigation project,
  • SampleModule as the dynamic assembly,
  • SampleApp.Web as the host for SampleApp

At first, create a sample control in the SampleModule project, lets call it SilverlightControl1. Add a simple text block with some static text.
<Grid x:Name="LayoutRoot" Background="#EEEEEE">
<TextBlock Text="Sample Control in Sample Module" FontSize="13" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>

Now, build your SampleModule and add a zip of the SampleModule.dll in the ClientBin folder in the Host project.


In the SampleApp project, open the Home.xaml.cs file.(I am assuming that you have used the default template for a Silverlight Navigation Application provided by Visual Studio).
We would now add come code to the OnNavigatedTo method which will load our dynamic module.

protected override void OnNavigatedTo(NavigationEventArgs e)
{

if (App.Assemblies.Any(a => a.FullName.StartsWith("SampleModule")))
{
var module = App.Assemblies.FirstOrDefault(a => a.FullName.StartsWith("SampleModule"));
PageScrollViewer.Content = module.CreateInstance("SampleModule.SilverlightControl1");
}
else
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("SampleModule.zip", UriKind.Relative));
}
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var resourceInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/x-zip-compressed"), new Uri("SampleModule.dll", UriKind.Relative));
AssemblyPart asmPart = new AssemblyPart();
Assembly asm = asmPart.Load(resourceInfo.Stream);
PageScrollViewer.Content = asm.CreateInstance("SampleModule.SilverlightControl1");
App.Assemblies.Add(asm);
}

The above code performs two basic tasks, at first it loads your module using a Web Client and then creates the instance of your control using the module it has already downloaded.I also copy the downloaded assembly in a global assemblies list, so that it can be referenced later when required. Here I have hard coded the module and controls names, you can load by any configuration method available to you.

This code is a basic skeleton and should be used as a reference purpose. You may need to add some error handling and show a delay to the user while the module is being downloaded.

Further Improvements

Further Improvements can be made to this code so that it is clean and modular. The first being, the code needs to be ported to a class which takes certain arguments like assembly name, source url, Control type name etc. Then the class can also save the assembly in isolated storage, instead of it being stored in memory.
I would provide more insights into this topic in future posts.
For more on this topic see Dynamic loading of Assembles II

Related Links


Complete Source Code : DynamicXap.zip

Sunday, February 27, 2011

Panorama versus Pivot: Windows Phone 7


The most popular controls in the Windows Phone 7 tools are the Panorama and pivot. Their usage is somewhat similar, but both provide a different kind of experience.
Here's a link to a post from Tim Heuer's blog, Pano versus Pivot: Windows Phone Design Days content available.
The post provides good insights on the two controls and has links to some good learning videos on windows phone 7.
If you are interested in a much more detail look into the implementation of these two controls consider visiting Windows Phone 7 - Part #5: Panorama and Pivot controls

Saturday, February 26, 2011

Accessing data grid row from an event


When using a Data grid in Silverlight, there comes a situation when you want to get the row(or cell) that contains your text box, hyperlink button or any other control. You try to see if the Data Grid has a property like Rows or something which can give you the handle of the current row. Many people do not know is that the DataGridRow class has a static method GetRowContainingElement which takes the control that you have placed in that row and returns you that row object.
So, consider you have a button in some column of a row, now add an event handler for the click event of the button. The following code describes the way to get the clicked row and its related objects.
private void Button_Click(object sender, RoutedEventArgs e)
{

//Get clicked row
var dataGridrow = DataGridRow.GetRowContainingElement(sender as FrameworkElement);
//Or get clicked index
var roIndex = DataGridRow.GetRowContainingElement(sender as FrameworkElement).GetIndex();
//Or if you need any column of clicked row
//Suppose column1 contains a TextBox
var textBox = myDataGrid.Columns[1].GetCellContent(dataGridrow) as TextBox;
}
It is not necessary to use the GetRowContainingElement method in a click event any event that you have subscribed will do the task.

Using Icons in Windows Phone 7 App



When using icons, you just think of a general colorful image that you have just found on Google. It might not be easy as you think, when you want to include icon in the application bar of your windows phone 7 app. Being from Microsoft, Windows phone 7 puts its own restrictions on using icons, and no they are not limited to just size.
Heres what msdn article Application Bar Best Practices for Windows Phone puts it
The following items apply to the Icon Buttons displayed by the Application Bar
  • Icon images should use a white foreground on a transparent background using an alpha channel. The Application Bar will colorize the icon according to the current style settings and colored icons can cause this effect to display unpredictably.
  • The circle displayed on each Icon Button is drawn by the Application Bar and should not be included in the source image.
  • Icon images should be 48 x 48 pixels in size. The white foreground graphic for the button should fit in a 26 x 26 area square in the center of the image so that it does not overlap the circle.
  • Do not use an Icon Button for a Back button that navigates backwards in the page stack. All Windows Phones are required to have a dedicated hardware Back button that should always be used for backward navigation.
  • Use Icon Buttons for the primary, most-used actions in your menu. Some actions are difficult to convey clearly with an icon. If this is the case, consider using a Menu Item instead.
  • Choose icons that have clear meanings when the Application Bar is rotated. The Application Bar automatically handles changes in screen orientation. When the device is in a landscape orientation, the menu is displayed vertically on the side of the screen. The icon buttons are rotated so that they appear upright to the user, but the order of the icons in the list is not changed. It is possible for icon meanings to be confused when this occurs, particularly if two of the icons are mirror images of each other along the Y axis.
In short, you need to use icons which have the icon shape in white with a transparent background and having size of 48 x 48 pixels.
By installing Windows Phone Developer Tools, various icons are installed with it. You can find them at one of the following locations:
  • C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons\dark
  • C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Icons\dark
Here are some icons from that pack:
appbar.feature.camera.rest appbar.feature.email.rest appbar.feature.search.rest appbar.feature.settings.rest appbar.feature.video.rest appbar.folder.rest appbar.minus.rest appbar.new.rest appbar.next.rest appbar.questionmark.rest appbar.refresh.rest appbar.save.rest appbar.share.rest appbar.stop.rest appbar.sync.rest appbar.transport.ff.rest appbar.transport.pause.rest appbar.transport.play.rest appbar.transport.rew.rest appbar.upload.rest appbar.add.rest appbar.back.rest appbar.basecircle.rest appbar.cancel.rest appbar.check.rest appbar.close.rest appbar.delete.rest appbar.download.rest appbar.edit.rest appbar.favs.addto.rest appbar.favs.rest
Related Links

Tuesday, February 8, 2011

Creating a collapsible panel using storyboard

Every time when you want to create a pane that can collapse or expand, you have to write either a Storyboard in xaml or some other animation logic. This can be a tedious task and has many pitfalls. Some of them being
  1. Change in width of the pane requires rewiring of the storyboard.
  2. Consistency in the collapse/expand duration of the pane.
  3. Flexibility in changing the pane from vertical to horizontal.
To solve all of these and many more problems that may arise we need to build a custom PaneManager that will do this for us when required.
At first we must create a class in your Silverlight application, lets call it PaneManager, with the following members
public class PaneManager
{
#region Public Members
public TimeSpan Interval { get; set; }
public double Increment { get; set; }
public double MinValue { get; set; }
public double MaxValue { get; set; }
public Grid Grid { get; set; }
public int Index { get; set; }
public GridUnitType GridUnitType { get; set; }
public Orientation Alignment { get; set; }
#endregion
}
Let us go over each member in detail.
  • Interval - This defines the duration to wait between successive calls to make the pane transition.
  • Increment - This is the value by which the pane's width or height must change.
  • MinValue - This defines the minimum threshold of the pane's width or height.
  • MaxValue- This defines the maximum threshold of the pane's width or height.
  • Grid - This is the parent Grid that contains the desired pane.
  • Index - This is the index of the row or column containing the pane.
  • GridUnitType - this is the unit of measurement of the Grid's row/column.
  • Alignment - This specifies whether the pane transition is to be done on a row or column.
We will also need to add the following members and events to the PaneManager class
#region Private Members
private Storyboard _storyboard = new Storyboard();
#endregion
#region Public Event
public event EventHandler Completed
{
add { _storyboard.Completed += value; }
remove { _storyboard.Completed -= value; }
}
#endregion
We have until now created the basic structure of the PaneManager without adding any functionality as such. To make this class usable,

Tuesday, February 1, 2011

DispatcherTimer vs Storyboard


Many of you must have heard and used the Dispatcher Timer class in Silverlight for all sorts of things. One common usage is for animation purpose, which is an incorrect practice.
Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. The Dispatcher Timer is also influenced by the UI Thread, so if any heavy rendering is to be done can cause you animation to be rigid and many a times slow.
Silverlight also has a class called Storyboard which can solve these issues and is a better solution than the Dispatcher Timer. The Storyboard has simple properties like TargetProperty, TartgetName which specify which property of which element you would like to animate. The Storyboard supports several animations namely, Color Animation, Double Animation, Point Animation andObject Animation Using Key Frames
Using a Storyboard in XAML


<StackPanel>
  <StackPanel.Resources>
    <!-- Animates the rectangle's opacity. -->
    <Storyboard x:Name="myStoryboard">
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:1"
        AutoReverse="True" RepeatBehavior="Forever" />
    </Storyboard>
  </StackPanel.Resources>

  <Rectangle
    x:Name="MyAnimatedRectangle"
    Width="100" Height="100" Fill="Blue" />
</StackPanel>
Heres a link to create an Animation in Procedural Code if you need.


In Conclusion
I would suggest avoid using the Dispatcher Timer whenever possible. If you have any queries, you can get back to me.


Related Links