Friday, September 14, 2012

Install Windows Phone 7 sdk on Windows 8

Its been a pain recently for many WP7 developers after they migrated and Windows 8 and found themselves in the trouble of being stuck with not being able to install the WP7 sdk and also if by any chance anyone succeeded they could not run the emulator.

I even know few of them who reverted back to windows 7 just for the sake of this problem. So put down the exact steps that you can follow in order to have the installation and the development for WP7 running smoothly on your new Windows 8 OS without any problems.

1. Install Visual Studio 2010 if you don't already have it installed.
2. Install Visual Studio 2010 SP1 , again if you haven't already installed it.
3. Download and install Windows Market Place Client from : http://www.xbox.com/en-US/LIVE/PC/DownloadClient
4. Download and install XNA Game Studio 4.0 from : http://www.microsoft.com/en-gb/download/details.aspx?id=23714
5. Download and install Windows Phone SDK 7.1 from : http://www.microsoft.com/en-us/download/details.aspx?id=27570
6. Finally, download and install Windows Phone SDK 7.1.1 update from : http://www.microsoft.com/en-us/download/details.aspx?id=29233


[P.S : Make sure you follow the above steps in the same order]

Thursday, June 7, 2012

WPF : Text Pixelation Issue

It's obvious from the title of the post, but here is a screen shot of the issue :


As you can notice the left side shows when the text's get pixelated. The right side is proper. This you can reproduce with most WPF applications if you turn off ClearType from ControlPanel as shown:




Solution : 

Very simple indeed, but took me some time to figure it out. Set TextOptions.TextRenderingMode="ClearType" . This you can either do for each of your TextElement ( TextBox or TextBlock ) or you can define a app level style for your default text and set the property as shown : 

<Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBox}">
<Setter Property="TextOptions.TextRenderingMode" Value="ClearType"/>
</Style>

Sunday, March 18, 2012

WPF : DataGrid single border selection for multiple row

I had to have a slightly tricky was of having row style for selected item. i.e if multiple row are selected are consecutive then those rows will have a single border around them instead of each row having its own border as shown :

SNAGHTML484140

To Solve this i have to create four seperate style resources for selected row. They are :

  • TopRowSelectionStyle : Has no border line for bottom
  • InnerRowSelectionStyle : Has no border line for top and bottom
  • BottomRowSelectionStyle : Has no border line for top.
  • SingleRowSelectionStyle : Has border lines around all four side ( i.e : Top, Left, Right, Bottom )

The follows shows the style resources :

<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}" x:Key="SingleRowSelectionStyle">
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="2"/>
</Style>
<Style TargetType="{x:Type DataGridRow}" x:Key="TopRowSelectionStyle">
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="2,2,2,0"/>
</Style>
<Style TargetType="{x:Type DataGridRow}" x:Key="InnerRowSelectionStyle">
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="2,0,2,0"/>
</Style>
<Style TargetType="{x:Type DataGridRow}" x:Key="BottomRowSelectionStyle">
<Setter Property="Background" Value="AliceBlue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="2,0,2,2"/>
</Style>
</DataGrid.Resources>




Once the style resources is added to the DataGrid , i created and added a custom attached behavior to the grid

public class MultiSelectStyleBehavior : Behavior<DataGrid>
{
private string TopStyleName = "TopRowSelectionStyle";
private string BottomStyleName = "BottomRowSelectionStyle";
private string InnerStyleName = "InnerRowSelectionStyle";
private string SingleStyleName = "SingleRowSelectionStyle";

protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
AssociatedObject.RowStyleSelector = new RowStyleSelector();
}

void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var removedItem in e.RemovedItems)
{
var row = (DataGridRow)AssociatedObject.ItemContainerGenerator.ContainerFromItem(removedItem);
if(row!=null) row.Style = null;
}
if (AssociatedObject.SelectedItems.Count > 1)
{
var items = new Dictionary<int, DataGridRow>();
foreach (var selectedItem in AssociatedObject.SelectedItems)
{
var row = (DataGridRow)AssociatedObject.ItemContainerGenerator.ContainerFromItem(selectedItem);
if (row != null)
{
var index = row.GetIndex();
items.Add(index, row);
}
}


var sorted = items.OrderBy(i => i.Key).ToArray();

int count = sorted.Count();
for (int i = 0; i < count; i++)
{
var currentIndex = sorted[i].Key;
var currentRow = sorted[i].Value;

if (NextIndex(i, sorted) - currentIndex > 1 && currentIndex - PrevIndex(i, sorted) != 1)
ApplyStyle(currentRow, SingleStyleName);

if (NextIndex(i, sorted) - currentIndex == 1 && currentIndex - PrevIndex(i, sorted)>1)
ApplyStyle(currentRow, TopStyleName);

if (NextIndex(i, sorted) - currentIndex == 1 && currentIndex - PrevIndex(i, sorted) == 1)
ApplyStyle(currentRow, InnerStyleName);

if (NextIndex(i, sorted) - currentIndex > 1 && currentIndex - PrevIndex(i, sorted) == 1)
ApplyStyle(currentRow, BottomStyleName);
}
}
}

private static int PrevIndex(int i, KeyValuePair<int, DataGridRow>[] sorted)
{
if (i > 0)
return sorted[i - 1].Key;
return -999999999;
}

private static int NextIndex(int i, KeyValuePair<int, DataGridRow>[] sorted)
{
if (sorted.Count() > i + 1)
return sorted[i + 1].Key;
return 999999999;
}

private void ApplyStyle(DataGridRow dataRow, string styleName)
{
var style = AssociatedObject.TryFindResource(styleName) as Style;
if (style != null && dataRow != null)
dataRow.Style = style;
}
}




That’s it , all you have to do now is attach this behavior to the DataGrid as follows :

<i:Interaction.Behaviors>
<DataGridTest:MultiSelectStyleBehavior/>
</i:Interaction.Behaviors>

Friday, February 17, 2012

WP7 : My Latest app Sketch Pad on the Marketplace

Yesterday i submitted my latest app Sketch Pad on the Windows Phone Marketplace. It should soon be published as long as the certification process does not fail. The link to the app is : http://www.windowsphone.com/en-GB/apps/fee4523c-35ef-4693-a0c5-60ef2f5270d9 (Wait for few days)
You must be wondering why am i blogging of it now, when i could have waiting for it to get published. Yes i know that. But it’s just that excitement when you make something nice and fun. So i couldn’t wait to share some of the screenshots specially the controls i have designed especially for this. I promise i will soon put these individual controls on codeplex once i get some time to separate them from the solution.  So here they are.
Please leave some comments below about your views on these controls :

The app screen shots :

a1b1cdg

The Controls :

This control is used to change opacity of fill colors
opacitySelector
This control is used to pick different color. It works like a spin wheel and you can flick to spin it to see other colors.
colorselector
This control is also a spin wheel to select different canvas sized.
paperSize
This control is used to select the options you want to work with.
Selector
This is again a spin wheel to select different dash style for brush or lines
dashstyleSelector
This is my custom font chooser i blogged about in one of my previous posts. : WP7 Font Picker
fontSelector
This control is used to choose different font sizes a selected front.
fontSizeSelector

Wednesday, February 15, 2012

WP7 : Hide application title from app tile like Facebook app

Sometimes you would want to have your app tile very neat with a smart looking graphics icon. But then suddenly it all dies when the name of your app floats on the app tile.  In fact if you look at apps like Facebook and office for WP7, they don’t have any app name in their tile.

This is a very simple step.

Under <Tokens><PrimaryToken> in WMAppManifest.xml, set the <Title> to a whitespace.

image

You shouldn't change the Title attribute in the tag at the top.

image

Friday, February 10, 2012

WP7 : Get Style from resources

There are two different scope for Xaml resources like Style and DataTemplates which depends on where the resource is defined. These are Page resources and Application wide resource.

Here is a code sample to access these resources.

Application Wide Resources :

mybtn.Style = Resources["MyButtonStyle"] as Style;


Page Resources


mybtn.Style = Application.Current.Resources["MyButtonStyle"] as Style;

Monday, January 16, 2012

WP7 : Custom Font Picker

WP7FontPicker1

It’s quite surprising that until now (at the time of posting this entry) there is a not a single fontpicker for WP7. Then i started spending few minutes online and to my surprise window phone does not yet have the method to fetch the list of FontFamily that are present in the system. The only place i could get information about the list of fonts in the system is  : http://msdn.microsoft.com/en-us/library/ff806365(v=VS.95).aspx

Also the method Fonts.SystemFontFamilies() is not supported in windows phone 7. So i decided to create my own FontPicker.

The usercontrol simply makes use of a ListPicker from windows phone toolkit.

<toolkit:ListPicker x:Name="lstPicker" ItemsSource="{Binding FontFamilyCollection}" Margin="0" Style="{StaticResource FontPickerStyle}" ItemTemplate="{StaticResource DataTemplate}" FullModeItemTemplate="{StaticResource FullModeItemDataTemplate}" ItemsPanel="{StaticResource ItemsPanelTemplate}" />


In the ItemsSource which is bound to the custom property FontFamilyCollection is initialized as follows :


public ObservableCollection<FontFamily>  FontFamilyCollection
{
get { return (ObservableCollection<FontFamily>)GetValue(FontFamilyCollectionProperty); }
set { SetValue(FontFamilyCollectionProperty, value); }
}

public static readonly DependencyProperty FontFamilyCollectionProperty =
DependencyProperty.Register("FontFamilyCollection", typeof(ObservableCollection<FontFamily>), typeof(FontPicker), new PropertyMetadata(GetFontFamilies()));

private static ObservableCollection<FontFamily> GetFontFamilies()
{
var fontFamilies = new ObservableCollection<FontFamily>();
fontFamilies.Add(new FontFamily("Arial"));
fontFamilies.Add(new FontFamily("Arial Black"));
fontFamilies.Add(new FontFamily("Arial Bold"));
fontFamilies.Add(new FontFamily("Arial Italic"));
fontFamilies.Add(new FontFamily("Calibri"));
fontFamilies.Add(new FontFamily("Calibri Bold"));
fontFamilies.Add(new FontFamily("Calibri Italic"));
fontFamilies.Add(new FontFamily("Comic Sans MS"));
fontFamilies.Add(new FontFamily("Comic Sans MS Bold"));
fontFamilies.Add(new FontFamily("Courier New"));
fontFamilies.Add(new FontFamily("Courier New Bold"));
fontFamilies.Add(new FontFamily("Courier New Italic"));
fontFamilies.Add(new FontFamily("Georgia"));
fontFamilies.Add(new FontFamily("Georgia Bold"));
fontFamilies.Add(new FontFamily("Georgia Italic"));
fontFamilies.Add(new FontFamily("Lucida Sans Unicode"));
fontFamilies.Add(new FontFamily("Malgun Gothic"));
fontFamilies.Add(new FontFamily("Meiryo UI"));
fontFamilies.Add(new FontFamily("Microsoft YaHei"));
fontFamilies.Add(new FontFamily("Segoe UI"));
fontFamilies.Add(new FontFamily("Segoe UI Bold"));
fontFamilies.Add(new FontFamily("Segoe WP"));
fontFamilies.Add(new FontFamily("Segoe WP Black"));
fontFamilies.Add(new FontFamily("Segoe WP Bold"));
fontFamilies.Add(new FontFamily("Segoe WP Light"));
fontFamilies.Add(new FontFamily("Segoe WP Semibold"));
fontFamilies.Add(new FontFamily("Segoe WP SemiLight"));
fontFamilies.Add(new FontFamily("Tahoma"));
fontFamilies.Add(new FontFamily("Tahoma Bold"));
fontFamilies.Add(new FontFamily("Times New Roman"));
fontFamilies.Add(new FontFamily("Times New Roman Bold"));
fontFamilies.Add(new FontFamily("Times New Roman Italic"));
fontFamilies.Add(new FontFamily("Trebuchet MS"));
fontFamilies.Add(new FontFamily("Trebuchet MS Bold"));
fontFamilies.Add(new FontFamily("Trebuchet MS Italic"));
fontFamilies.Add(new FontFamily("Verdana"));
fontFamilies.Add(new FontFamily("Verdana Bold"));
fontFamilies.Add(new FontFamily("Verdana Italic"));
fontFamilies.Add(new FontFamily("Webdings"));
fontFamilies.Add(new FontFamily("Wingdings"));
return fontFamilies;
}

As you can see, all i am doing is using the font family name from the msdn list given at : http://msdn.microsoft.com/en-us/library/ff806365(v=VS.95).aspx

You can download the Xaml and cs file from here : Sample Font Picker Codes


Make sure the project where you will be using this, has reference to windows phone toolkit. You can get this from http://silverlight.codeplex.com/

WP7 : NetworkInterface.GetIsNetworkAvailable() always returns true

Basically this method indicates whether network is available or not. In many places on the internet it says that this method always returns true when testing on the simulator. But this was not the case. I was testing on an actual hardware ( a HTC HD7 to be precise) . And still i was getting true when i have turned on airplane mode.

Now what actually was happening behind the scene was that my device even though has all its network switched off ( i.e airplane mode on) it was still connected to the pc via the USB because i was debugging that time. So it was getting the network availability from the PC.

This is a bit odd but disconnecting from the USB cable solved the problem.

WP7 : Detect If Internet Is Available

*Please note that when you are using an emulator to test, it will always report as internet connection available. So use method 2 below.

Method 1 : Use this if u plan not to use the emulator for testing

private bool IsInternetAvailable()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
return false;
}
return true;
}

 

Method 2 : Using Conditional DEBUG compilation to test different scenario's


private bool IsInternetAvailable()
{
var result = !NetworkInterface.GetIsNetworkAvailable();
#if DEBUG
result = false;
#endif
if (!result)
{
return false;
}
return true;
}


 

Friday, January 13, 2012

WP7 : Microsoft adControl not showing add

This is a rather context specific problem. Many users might face this problem due to different scenario's. In my case it was a very simple correction. I was fool enough to exclude the Networking capability from the WMAppManifest.xml file. Re-adding it solved the problem.

Below snapshot shows it  :


Also note that the following capabilities are required for the AdControl to function
<Capability Name="ID_CAP_PHONEDIALER" />
<Capability Name="ID_CAP_IDENTITY_USER" />
<Capability Name="ID_CAP_MEDIALIB" />
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />

Another important thing to note is that make sure you make the adControl the same size as the addunit you will be displaying. For e.g, for a ad unit of 480 x 80 make the size of adcontrol to 480 x 80.

Thursday, January 12, 2012

WP7 : Application does not launch after project or rename

This sounds like a funny scenario, but it so happened to me that i spent 15 mins wasting my time to figure out what was going wrong. My WP7 solution was running fine and all morning i had been making changes and adding features. I was able to debug just fine. Then at one moment i decided to rename my project to a more sensible name. There you go. BOOM!! It stopped working. All i did was rename the project name, change the default namespace name and build the solution again. My application would simply launch and shut down.

Then after 15mins of time waste i noticed that the startup project is now pointing to nothing. So the rename and namespace changes changed the startup name which is why this happend. All i had to do is point this to the right app.


Wednesday, January 4, 2012

Change Print settings using printer preference dialog

It was a tough time for me to figure out how to change my current print job settings by displaying the printer preference dialog and reading the values back. The main problem is the PagemediaSize  object that is used for print ticket whereas print settings gives a list of PageSize objects. There is no one-to-one mapping between the both. Thus I have used the following technique to solve the problem and thought its worth sharing. Here are the steps involved.

1. Declare the P/Invoke signature for the DocumentProperties method of the winspool driver.

2. Open the printer preference dialog for the selected printer or the printer you are interested in and pass the printers current UserTicket.

3. After the changes are done on the preference dialog and pressing ok, return a result of 1 from the DocumentProperties Method. Now replace the UserPrintTicket with the modified PrintTicket.

4. There is a helpful utility class involved here “PrintTicketConverter” because I can assure you that you don’t want to mess with doing the to and fro PrintTicket conversion conversion  on your own.

Here is a sample code :

[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);

Public void ChangePrintPreference()
{
var ptc = new PrintTicketConverter(CurrentPrinter.FullName, CurrentPrinter.ClientPrintSchemaVersion);
var mainWindowPtr = new WindowInteropHelper(FullScreenPrintWindow).Handle;
var myDevMode = ptc.ConvertPrintTicketToDevMode(CurrentPrinter.UserPrintTicket, BaseDevModeType.UserDefault);
var pinnedDevMode = GCHandle.Alloc(myDevMode, GCHandleType.Pinned);
var pDevMode = pinnedDevMode.AddrOfPinnedObject();
var result = DocumentProperties(mainWindowPtr, IntPtr.Zero, CurrentPrinter.FullName, pDevMode, pDevMode, 14);
if (result == 1)
{
CurrentPrinter.UserPrintTicket = ptc.ConvertDevModeToPrintTicket(myDevMode);
pinnedDevMode.Free();
}
}

Tuesday, November 15, 2011

Top five reasons that an application fails for certification in Windows phone 7 apphub

Introduction


I have recently submitted my first home made application to the windows phone marketplace (AppHub) to be more precise. The link to the application is : Binary Clock ( still not active at the time of publishing this article.

It is a very simple app and the mere purpose of writing and submitting this application is to try out the app hub and see user responses on the windows phone market place. This will then lead to my background work, which i hope to be the next killer game after angry birds :) ( keeping my finders crossed there ). Now that's another  Story.

However, to my surprise, the certification process failed and the only reason i did not address one of the top five reasons described later below. Then i found out about these top 5 reasons and wanted to share with other newbies out there planning to publish their next million dollar application.

The Top 5 Failures


The details of all the below can be found from the following Technical Certification Requirements

1: Application closure


2: Content and themes


3: Back button


4: Language validation


5: Application running on multiple devices


 

1: Application Closure


This is the most common reason. The application crashing. The developer must make sure the application does not close unexpectedly, i.e crash, and if it must, then it should display a friendly error message to the user.

As a developer you can get the crash dump sent back to you via various options, for e.g letting the user email it.

Also when you go to your apphub, you will be able to the crash analysis for your app. Its an awesome service for developers and you can get real time analysis on how well you application is performing.


2: Content and Themes


This is the reason why my application failed the first time. Make sure you test your application in both the light and dark theme. The users can completely customize their device and see it in black or white.

The developers don't take into account that the back ground might be white and they might choose colors that look good in black theme but completely out of place when the theme is light and hence a bad experience for the users.

3: Back button


Applications should subscribe to the back button behavior that's required.

From mango (7.5) onward developers have more fine grain control over the back stack. They can if they wish to, delete items from the back stack.

4: Language validation


Now at the time of writing this article, 20 languages are supported. More and more developers are taking advantage of this beyond EFIGS (English, French, Italian, German and Spanish).

Due to this, what is observed is that the application description entered in during the submission process is not localized to each targeted language.

Make sure that for each target language of the application the localized description is of appropriate type ( i.e in the same language).

Also note that if you have previously published application[s], and selected worldwide distribution, go back to the application dashboard and re-select worldwide again to have the new countries to be selected as this does not happen by default at this moment.

5: Application running on multiple devices


Always remember that there is a huge value in testing the application in an actual device.

For your existing/new 7.0 applications, make sure you test those applications on Mango devices as well as they become available. This is important because since 7.0 applications are available in the marketplace, end users with Mango devices will be able to use them too.

It is however encouraged to update these 7.0 applications to 7.5. This might raise a question. If you have and existing 7.0 application and then you submit an update targeting Mango devices, what happens to 7.0 users ?

Simple! 7.0 applications will remain published in the marketplace and will be visible to the 7.0 users. However, the 7.5 (Mango) users will see the the updated 7.5 application.

Conclusion


I hope this experience of mine will be able to help others from suffering from the same certification fail as myself.

To conclude i would like to say a word on the certification time length. In general, the certification process should take 5 business days or less. If someone fails they get explicit information on why their application failed the certification process. A detailed test summary report will be provided which outlines which test cases specifically failed. Where its appropriate they will get rest run notes that will provide additional notes as to how that error was found ( more like a repo step) and how to address the error in some cases.

Friday, October 14, 2011

[AuthenticationException: A call to SSPI failed, see inner exception.]

I was working on Secure WCF services and did all the steps to necessary for testing them on my local IIS 7 on a windows 7 machine. Then when i tried to start the newly created website that hosts these secure service it won't start give the error "A call to SSPI failed, see inner exception". In my case i was using ntlm for authentication.

So all you need is to enabled windows authentication for the website which is disabled by default when u create a new website in your IIS.



Tuesday, June 14, 2011

Smooth Transition With SilverLight 5 VisualStateManager.LoadTransition

I was quite happy to see the all those sleek new additions to silverlight 5. I will be addressing all of them one by one. For the timebeing i will show how to give that nice and smooth initial animation when a control is loading. Before silverlight 5, this was pretty time consuming as you required to write all those custom animation codes and have their triggers in place. Now all you need to do is the following :
<Grid>
<VisualStateManager.LoadTransition>
<LoadTransition StartXOffset="300" GeneratedDuration="0:0:1.0" StartOpacity="0.2">
<LoadTransition.GeneratedEasingFunction>
<CircleEase/>
</LoadTransition.GeneratedEasingFunction>
</LoadTransition>
</VisualStateManager.LoadTransition>
</Grid>

As we can see above, its a very simple usage. All we need to do is add the VisualStateManager.LoadTransition to our Grid. The parameters are quite self explanatory :

  • StartXOffset : The intial x co-ordinate from which to start the transition

  • GeneratedDuration : The amount of time it would animate

  • StartOpacity : The initial Opacity. Here it start with an initial opacity of 20%

  • Also notice that we have added an easing function of type CircleEase. (More details on it at : http://msdn.microsoft.com/en-us/library/ee308751.aspx)

No DirectX in windows 8

Recently there has been an outcry on the Window 8 M2 / Pre-M3 Build 7955 Findings. Out of the discussion on the thread : http://forums.mydigitallife.info/threads/26404-Windows-8-%287955%29-Findings-in-M3-Leak/page20 there are probably three major findings leaked :

  • DirectUI : It's the Underlying UI Framework.

  • Jupiter : A new user interface (UI) library on top of windows alongside Window 8. Seems it allows apps to be written in any language of choice and packaged.

  • Immersive Applications : These are not meant to be Windows desktop apps. Nor are they necessarily pure web apps. They are applications that will be build using C#, VB ( and maybe C++).


Now all these makes sense. But what surprised me the omission of DirectX. The follow shows the dependency tree of DirectUI.

http://xs.to/photo/5662

DirectUI ( which has been there since Windows Vista) will have additional functionality to load XAML applications.



[caption id="" align="alignnone" width="775" caption="Xaml Loader"][/caption]

Wednesday, June 8, 2011

Is HTML 5 going to replace WPF/Silverlight

DEFINITELY NOT!!!.

It seems most of us are hyped up for HTML 5, or at least thinking over the idea of taking a full-fledged desktop application and converting it to a single threaded, web application. Funny isn’t it?

Here’s are few hint’s why i  believe the concept of HTML 5 replacing Silverlight/WPF is a joke.

  1. No Multi Threading : Now that’s a surprise. How can people , when processors are everyday getting new cores, think of even going back to the past building highly inefficient application, with only one thread of execution, when you can do all the processing and hundreds of threads in Silverlight/WPF

  2. Full Trust Applications : Now how do you intend to make use of all the resources when your applications isn’t running under full trust with HTML5. ?

  3. 3. Maintenance : Who do you suppose is going to do all the JavaScript maintenance ? and what about smart tools like re-sharper that makes RAD double efficient.




These are just few areas i felt worth mentioning. Experts can come out with more practical scenario’s to prove the pitfalls of moving into HTML5 for a high end business application, especially when it’s a new technology that’s still in the womb.

Sunday, June 5, 2011

What new in SilverLight 5.0 beta

Recently SilverLight 5.0 has been made available to the developer community. Out of many features i have been wishing for a long time, two are my favourite in this version. The Xaml debugging and P/Invoke calls to Win32 api’s and unmanaged libraries under trusted out of browser application.

Let me take you through few of the new features including the above two.

XAML Debugging



  • Breakpoint in xaml : No more writing those silly custom value converters just to check the value coming in/out into your binding. You can put break breakpoint in you xaml code and debug right inside your binding.

  • RelativeSource Binding : Now you can set binding to a property on parent control using Mode=FindAncestor




       <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=Window, AncestorLevel=1}}"/>





  • Binding Style Setters : This is a long wished feature by many.



      <Style TargetType="TextBlock">
      <Setter Property="Foreground" Value="{StaticResource BlueBrush}" />
      </Style>




  • Implicit DataTemplates : You can define datatemplates and associate them with a particular data type. Without assigning any key for the data template, silverlight with know how to display the data of that type. http://bit.ly/hGLthY


Full Trust Applications



  • Elevated Trust Application : Application can now request for elevated trust if they are running under group policy restrictions.

  • Keyboard Support : In full-screen applications, like KIOSK type applications

  • Unrestricted File System Access : Only in windows

  • Native Window Support : If you are building out of browser applications, you can have multi monitor support apps, or applications with multiple windows.

  • P/Invoke : Having said above, you can now access Win32 api’s and other unmanaged libraries using P/Invoke.


Media



  • Support for low latency sound : Now you can get support for low latency sound effect which is given using the XNA SoundEffect API. Using SoundEffect and SoundEffectInstance, you can also reuse sound effects in your applications.

  • Trick Play : This is support for variable speed playback , so now you can play video at different speeds ( thrice the speed) and still have the audio play at original speed. ( This feature is not in the beta)

  • H.264 Hardware Decoded : This gives an awesome performance.


Text



  • Tracking and Leading Control : This will allow you to control the spaces between characters and lines.

  • Linked RichTextBoxes : This is a cool feature that will allow you to have text overflow between the controls, something like a multi column text.



      <RichTextBox x:Name="FirstBox" OverflowContentTarget="{Binding ElementName=SecondBox}" Width="100" />
      <RichTextBoxOverflow x:Name="SecondBox" Width="100" />





Input



  • ClickCount : MouseEventArgs has now a clickcount property.

  • TypeAhead Searching : Listbox and comboBox now support the type ahead searching, so that when you start typing it will scroll to the nearest matching items.


Graphics



  • Independant Animations :

  • XNA 3D Api : gives low level access to GPU, vertex shaders and 3D primitives. This also works as a immediate mode 2d api.


Performance Improvements



  • Xaml Parsing : Parsing xaml is now much faster.

  • ClientHttpWebRequest : 90% performance boost. So scenarios where you are using the client network stack, network latency is highly improved.

  • Harware Acceleration : For windowless silverlight applications, there have a good performance improvement with the SurfacePresenter API in IE9.

Tuesday, May 31, 2011

Windows Azure : Save your money during development

Why are we developing for cloud? Isn’t it obvious that we want to save money because we don’t want to spend a lot buying our own servers, maintaining them, scaling them before even knowing if we really need them. Right. So why do you want to spend off your money during your development time.

In order to do so, and lower your bill rate of your subcription, use a “VMSize” of “ExtraSmall”. So do this, within, the ServiceDefinition.csdef set the vmsize attribute to the <WebRole> element and set its value to ExtraSmall.

   1: <WebRole vmsize="ExtraSmall">



   2: .. .. 



   3: </WebRole>




 



Other supported values are Small, Medium, Large, or ExtraLarge. Details of each can be found at : http://msdn.microsoft.com/en-us/library/ee814754.aspx



Note that ExtraSmall is supported in Windows Azure SDK version 1.3 or later. Also try to avoid the ExtraSmall vmsize if you are planning to support a large user base because of its shared resources which makes is less efficient than the rest. The following table depicts it.



azure1

Friday, May 27, 2011

The three pillars of Windows Azure

I started recently exploring Windows Azure, and i should definitely say, it is one hell of a thing i have been striving to lean towards for a very long time. Yes that’s right.. i was interested in cloud computing for a long time now, but never felt comfortable to deal with all the implementation details. In short, i wanted a typical Microsoft version of solution that will save me from all the 99% of the things i shouldn’t be caring about when i want to build a great Application/Service.

So here i am with my first blog on Windows Azure. I promise i will come back with loads of stuff in the coming days, but for a start, I would like share my understanding of something i like to term as CSS ( the three pillars of Azure – aka Compute, Storage and Sdk).

Background

First lets try to answer the first thing that comes to our mind. What is Windows Azure? Well, i can go on for days, giving reference to all those extensively elaborated long articles taking you through all the intrinsic details.Hmmm, now that’s one way to start. Instead, take a read of the following and see if you can understand :

Imagine you created an application that you want to host on the internet. Your application is ready your solution is not. To reach to the end users you need to think of too many things at once. We need to think of the OS we need to use and how to maintain it. We need to think of the network ( the routers, load balancers, connectivity etc.). We need to think about the storage of our applications data, the disaster recovery strategies. Then finally we also need to think about the scalability of our whole solution.

Now imagine we never had to deal with all these complexities i just mentioned. Something that does solves all these for us. All we need now is to worry about our application. In fact this is the whole idea behind Windows Azure. Windows Azure deals with all the rest and leaves us with only one task to worry about. Our application. Windows Azure, in other words is the Microsoft’s answer to cloud computing used to build, host and scale web applications through Microsoft datacenters

Now if that answered the basic question about Windows Azure, let move back to the three pillars. I will start with the Fabric.

Compute

It the set of compute resources provided the datacenters running many computers with multiple virtual machines, running windows. Or re-phrase , it provides a runtime execution environment for managed code in the hosted services. The service may run in one or multiple roles supported by Windows Azure :

  • Web Role : Runs in full IIS 7.0, customized for web application programming
  • Worker Role : used in more generalized form, so perform blocks of execution, for e.g: background processing for a web role.
  • Virtual Machine Role (VM Role) : helps to move existing Windows Server applications to Windows Azure hosting environment.

Storage

It is the services that’s here to help you manage and scale your data. It provides persistent , durable storage in the cloud which you can access using a storage account, provide via Windows Azure Platform Management Portal. It is known as SQL Azure, that allows you to make relational queries against your stored data, along with search, data synchronization and analysis.

SDK

The fabric( compute resources), the storage service, and the Api’s in the cloud, all of this is packaged along with tools for Visual Studio in the form of an SDK in order to help you develop and test your applications locally before you deploy it to the cloud. You can download the SDK from : http://www.microsoft.com/windowsazure/sdk/

That’s all for today, with the brief overview of my own understanding of Windows Azure. More to come soon.

Wednesday, May 25, 2011

CEO Friday: Why we don’t hire .NET programmers

I read the post CEO Friday: Why we don’t hire .NET programmers by David Barrett and was really pissed off.. i was annoyed more when comments were closed. How can someone point finger's at a huge community (us .net programmers) and not face our comments/views. So i thought i would add this post here just as a platform for all the smart .net programmer out there, wanting to still comment and let the rest know what's our side of the story.

Sunday, May 22, 2011

WPF Print Engine

Source code at : http://wpfprintengine.codeplex.com/
Source code with caching disabled : http://dl.dropbox.com/u/57582420/CodesForBlog/SUT.PrintEngine.rar

It was summer time. I was enjoying my time. Little did i know that my tough days were coming. Yes that’s right. I had been assigned the work on printing. I wouldn’t say it was very difficult. Its just that i had no idea how printing works in WPF world and to my surprise it wasn’t as easy as few Google searches. So after struggling a lot and spending some extra time apart from normal hours, i ended up with some pretty good experience that i want to share with you all.

Overview

In an attempt to explain things i split it into 5 sections as follows :

  • Demonstration : Overview of how it works
  • Usage : Code samples
  • DocumentPaginator : How the pagination is achieved
  • PrinterUtility : Retrieval of available printers and their properties / preferences

 

Demonstration

WPF print engine comes with the following features at the moment :
  • Smart print preview to see what it would look like on after printing on the printer and paper you selected
  • Support for changing printer preferences directly
  • Scale page content in the print preview to fit in less pages
  • Turn on/off page numbers
  • Asynchronous printing directly to printer
  • Any WPF Visual Support
  • Any WPF FrameworkElement Support
  • DataTable Support

The above snapshot shows the demo application.  As you can see it has as this stage, support for generating print preview for WPF Visual or a DataTable as input. Below is a snapshot of what we get then select “Print This Visual”. You can see that the visual is split in 2 separate pages because the current selected paper (A4) is smaller than the visual’s size.


You can change the printer, the printer preferences, the number of copies to print from the printing options tool. It also allows you to print the page numbers on each page or hide them.

There is one neat feature – “Print Size” that allows you to shrink the generated print preview content’s size to your will, so that you can fit it in less number of pages. This is done with the help of a slider giving you complete control over the resize ratio so that you can decide when you data is not being too small. This is unique in the sense that many applications allow you to shrink but not all allow you to control how much.

Notice below the updated snapshot after it has been shrunken just enough to fit into 1 pages instead of 2.

Similarly the demo application show an example for using DataTable as input for the print preview. Notice that the pagination is done such that no columns or row get cut and yet the maximum possible row or column is fit in the selected paper size.

Usage

Printing a WPF Visual:

First you need to create an instance of the printcontrol which you can using the PrintControlFactory.Create method. It has few overloads, that i will be adding more to in future. One of those is the one that takes a size and a visual as input. Visual is the WPF visual (could be any control, panel, grid, window) anything that you want to print. When you specify a visual, all its children, as rendered on the screen are taken into consideration.
var visualSize = new Size(visual.ActualWidth, visual.ActualHeight);
var printControl = PrintControlFactory.Create(visualSize, visual);
printControl.ShowPrintPreview();




Printing a DataTable as source :


In order to give a datatable as a source, you will need to also supply the width of each column as a List<double>. Then instantiate a printcontrol using the PrintControlFactory.Create method that takes a datable and columnsWidths as arguments.


var columnWidths = new List<double>() {30, 40, 300, 300, 150};
var printControl = PrintControlFactory.Create(dataTable, columnWidths, headerTemplate);
printControl.ShowPrintPreview();


Printing a DataTable as source with Header Template :


There is also an overload to give a header template. The header template to supply is a string of the Xaml File you will create. This can be in the form of a user control. To denote the page number and it place holder, simple place the verbatim string “@PageNumber” in its placeholder.

<UserControl x:Class="DEMOApplication.HeaderTemplate"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignWidth="919">
    <DockPanel LastChildFill="False" Margin="10">
        <Image Source="Images/headerDemo.gif" DockPanel.Dock="Left" Stretch="None" />
        <TextBlock DockPanel.Dock="Right" VerticalAlignment="Bottom" FontWeight="Bold" TextWrapping="Wrap" Text="Page Number : @PageNumber"/>
    </DockPanel>
</UserControl>




var columnWidths = new List<double>() {30, 40, 300, 300, 150};

var ht = new HeaderTemplate();

var headerTemplate = XamlWriter.Save(ht);
var printControl = PrintControlFactory.Create(dataTable, columnWidths, headerTemplate);
printControl.ShowPrintPreview();


How the control is initiated


At the heart of the print engine are two parts. One is the PrintControlFactory that creates a DrawingVisual object to be used later by the control. I will explain this shortly. The second important part (I should probably mention it first, because this is in fact the most important bit) is, wait for it..., the Paginator.

The following diagram displays a flowchart of how the whole process works. I will explain one step at a time and give the implementation details.







Step 1: Initialize the Print Engine


The PrintControlFactory.Create() method is responsible for creating an instance of the PrintControl. This method has several overloads for working with a WPF Visual item. Also, there is an overload that takes aDataTable, widths of the columns as List, and a header template as string. We will look into the working of the engine with DataTable much later. Let's first understand the complete flow when using a WPFVisual.


var unityContainer = new UnityContainer();
PrintEngineModule.Initialize(unityContainer);
var printControlPresenter = (PrintControlViewModel)unityContainer.ResolvePrintControlViewModel>();


You will notice the above part of code in the create method. This is where the print engine is assigned a new instance of UnityContainer since I am using Prism and Unity for MVVM architecture. Here I register all the Views and ViewModels to the container.


Step 2: Build Graph Visual


public static DrawingVisual BuildGraphVisual(PageMediaSize pageSize, Visual visual)
{     
    var drawingVisual = new DrawingVisual();
    using (var drawingContext = drawingVisual.RenderOpen())
    {
        var visualContent = visual;
        var rect = new Rect
                      {
                      X = 0,
                      Y = 0,
                      Width = pageSize.Width.Value,
                      Height = pageSize.Height.Value
                      };          
        var stretch = Stretch.None;          
        var visualBrush = new VisualBrush(visualContent) { Stretch = stretch };
        drawingContext.DrawRectangle(visualBrush, null, rect);          
        drawingContext.PushOpacityMask(Brushes.White);     
    }     
    return drawingVisual;
}


This method takes a WPF Visual and creates a DrawingVisual object. Why we need this is very crucial. If you have already run the sample application in the source code and played with it, you will notice that based on the selected printer and paper type, the visual is paginated into multiple pages. This is possible due to the fact that we can clip a certain area of the original DrawingVisual starting from any X,Y co-ordinate. I will show this further below.

In order to create this DrawingVisual, I have created a VisualBrush with the given input and painted with it.

Step 3: Initialize Printer Properties


This is another interesting area of the engine and in fact was a little challenge for me at the beginning. This is the part where I connect to the installed printers to fetch their properties such as the PaperSizes, DefaultPaper,printer hardware margin, etc. Also I have made sure that I do these once during the life time because this operation is expensive and sometimes takes long depending on the type of printers you have. The class PrintUtlity deals with all these operations. One such method that gets the list of installed printers is shown below. I have used Enterprise Library for caching these values so that these expensive operations are done only once.

public PrintQueueCollection GetPrinters()
{    
    if (!_cacheHelper.Contains("Printers"))        
    {        
        var printServer = new PrintServer();            
        _cacheHelper.Add("Printers", printServer.GetPrintQueues(          
                                    new[] 
                                    { 
                                        EnumeratedPrintQueueTypes.Connections,           
                                        EnumeratedPrintQueueTypes.Local 
                                    }));        
    }    
    var printers = (PrintQueueCollection)_cacheHelper.GetData("Printers");    
    return printers;
}


Step 4: Create Scaled Visual


The method ReloadPreview() executes when the control is first loaded. In fact from this step to the last step, everything takes place in the ReloadPreview method.


private DrawingVisual GetScaledVisual(double scale)
{    
    if (scale == 1)    
        return DrawingVisual;    
    var visual = new DrawingVisual();    
    using (var dc = visual.RenderOpen())    
    {        
        dc.PushTransform(new ScaleTransform(scale, scale));            
        dc.DrawDrawing(DrawingVisual.Drawing);    
    }    return visual;    
}


This step would make no sense at first, but when you use the option to scale the visual so that it takes up less space, the scale value changes ranging from 0 to 1 where 1 is 100% size and 0% the original size. This is done by performing a ScaleTransform on the DrawingVisual.


Step 5: Setup Paginator


Ahh... the most interesting and intelligent class of the whole system. The Paginator! Rhymes pretty well will Arnold Schwarzenegger. This class does all the heavy lifting of cutting the entire visual into separate individual pages.

There are several Paginators in the project. Each able to work with one kind of pagination.


  • VisualPaginator: This has two roles. First, it contains all the common logic for all the paginators and also is a base class to the other paginators. Second, it is responsible for performing page calculation and clipping of a given visual into separate individual pages.
  • DataTablePaginator: This does the pagination when a DataTable is used as the source for the printpreview.
  • DataGridPaginator: This does the pagination when a WPF DataGrid control is given as the input. This feature is still not complete because I am trying to add this feature to work even when the DataGrid is in Virtualization mode.

public VisualPaginator(DrawingVisual source, Size printSize, Thickness pageMargins, Thickness originalMargin)
{        
    DrawingVisual = source;    
    _printSize = printSize;    
    PageMargins = pageMargins;    
    _originalMargin = originalMargin;
}


I will describe the details of all the paginators in part II of the series as well as complete the DataGridPaginatorand its usage sample. In this part, we will only look into the details with respect to the VisualPaginator. The constructor as you can see is pretty straightforward. Next comes the Initialize() method. It performs two important pieces of work:

1: Calculates the Printable Page Width and Height


This calculation is necessary because different printers have different hardware margins. So if we draw anything outside the bounds of this margin, that part will get cut. So when calculating the number of pages required, this hardware margin has to be kept under consideration.


var totalHorizontalMargin = PageMargins.Left + PageMargins.Right;
var toltalVerticalMargin = PageMargins.Top + PageMargins.Bottom;
PrintablePageWidth = PageSize.Width - totalHorizontalMargin;
PrintablePageHeight = PageSize.Height - toltalVerticalMargin



2: Calculates the Horizontal and Vertical Page Count


This is fairly straightforward in the case of VisualPaginator. Other paginators, specially the ItemsPaginatordoes the most complex calculation. In fact, calculating the page count is what separates the different paginators. If you want to add support for your own control type, let's say a third part datagrid like xCeed grid control, then all you do is create a new paginator inheriting from VisualPaginator and write your own logic for the horizontal and vertical page count. OK, let's gets back to our VisualPaginator. Here the horizontal page count is the total visual width divided by the printable width of each page. Similarly, the vertical page count is the total height of the visual divided by the height of each individual page.

 


Step 6: Create Pages


Here I do an iteration to walk through the whole DrawingVisual and save each block as a separate page. This is done by first looping from 0 to the number of horizontal pages (calculated in the previous step) and then moving to the next row and repeating until I cover the total horizontal page count. All these sepsrate pages are saved in a collection, DrawingVisuals, to be later used during printing or showing the preview.

private void CreateAllPageVisuals()
{    
    DrawingVisuals = new List();    
    for (var verticalPageNumber = 0; verticalPageNumber < _verticalPageCount; verticalPageNumber++)    
    {        
        for (var horizontalPageNumber = 0; horizontalPageNumber < HorizontalPageCount; horizontalPageNumber++)        
        {            
            const float horizontalOffset = 0;            
            var verticalOffset = (float)(verticalPageNumber * PrintablePageHeight);            
            var pageBounds = GetPageBounds(horizontalPageNumber,                 
            verticalPageNumber, horizontalOffset, verticalOffset);            
            var visual = new DrawingVisual();            
            using (var dc = visual.RenderOpen())            
            {                
                CreatePageVisual(pageBounds, DrawingVisual, IsFooterPage(horizontalPageNumber), dc);            
            }            
            DrawingVisuals.Add(visual);        
        }    
    }
}


Step 7: Show Preview


After the pages are calculated, we are ready to show them to the user as preview. Since I am using a standard mechanism for the pagination and using a custom implementation of the .NET Framework's DocumentPaginatorclass, it should be fairly straightforward to simply give the paginator to the DocumentViewer. But there is a catch. When the number of pages increase, specially in the area of several hundreds, the standard DocumentViewer starts behaving awkward and even fails to display all the pages sometimes. So instead I went for a rather custom, but simple solution.

Using the collection of drawing visuals created by the paginator, I create a simple WPF Visual object from each of these DrawingVisuals and display them in a StackPanel. The code is rather self explanatory.


private Border GetPageUiElement(int i, DocumentPaginator paginator, double scale)
{    
    var source = paginator.GetPage(i);    
    var border = new Border() 
    { 
        Background = Brushes.White 
    };    
    border.Margin = new Thickness(10 * scale);    
    border.BorderBrush = Brushes.DarkGray;    
    border.BorderThickness = new Thickness(1);    
    var margin = new Thickness();    
    var rectangle = new Rectangle();    
    rectangle.Width = ((source.Size.Width * 0.96 - (margin.Left + margin.Right)) * scale);    
    rectangle.Height = ((source.Size.Height * 0.96 - (margin.Top + margin.Bottom)) * scale);    
    rectangle.Margin = new Thickness(margin.Left * scale, margin.Top * scale, margin.Right * scale, margin.Bottom * scale);    
    rectangle.Fill = Brushes.White;    
    var vb = new VisualBrush(source.Visual);    
    vb.Opacity = 1;    
    vb.Stretch = Stretch.Uniform;    
    rectangle.Fill = vb;    
    border.Child = rectangle;    
    return border;
}



Step 8: Change Paper / Printer Options


This is the step where the user selects a different paper size, page orientation, etc. Steps 4 to 7 are performed again to calculate new pages and display them.


More Info


This is the just the introduction, to both the project and its documentation. At this moment i believe there are many areas that can be improved, including facility for the WPF DataGrid as input, support for footer template, refactoring the codebase more, better samples to name a few. I would love to welcome anyone interested in contributing to the source code and bring in better improvements and features.

Also i have plan to give Visual Studio design time support for creating printing templates.