Danish Developer Conference 2012

There’s a lot of talks about HTML5 these days and I myself will be doing a talk regarding the subject in the Danish Developer Conference. I was planning on saving my content for my presentation but once my talk is done I’ll be posting a couple of articles on HTML5 and Windows Phone 7.

Here’s an introduction / teaser to what I’ll be presenting…

A long break…

As I come back from another long blogging break, a lot of great things have happened in my life…

The greatest experience I’ve had so far in my life was on September 15, 2011 I became a father to this wonderfully charming little guy you see below:

I took a full month off work to play daddy and to assist my wife with everything I possibly can. It was a great time and I’ll never regret or forget that.

My hands were completely tied from work the day I got back from my leave. Luckily the projects were all very exciting and challenging, but did require me to spend a ton of hours on work. I had the chance to work on an online music service called TDC Play for a rather large danish based telecom company called TDC. I unfortunately only took part in the design and development of the Windows Phone 7 version, but the app is also available on the iOS and Android.

You can check out the app here:
http://www.windowsphone.com/da-DK/apps/01f8e8d3-d7aa-4bf6-9dcd-38e556c81ee3
…unfortunately, due to infrastructure and licensing issues it’s only available to Danish customers

The app was extremely fun to make and I got the to work with my old colleages from the Microsoft Development Center in Copenhagen. I expect to post some articles on performance, background agents, Implementing a MediaStreamSource for streaming or progressive downloads, and loads of other fun stuff.

I also got started again in doing some speaking events. In February 29 in Horsons, Denmark I’ll be doing a talk on Windows Phone 7 and HTML5 for the Danish Developer Conference and on February 13 I’ll be doing an online talk on Background Agents on Windows Phone 7

So what’s next for me in the blogsphere? Well to begin with I’d like to continue on my series Multi-platform Mobile Development and some articles on Windows Phone 7 development. I’m looking forward to getting back into writing some useful articles.

I’ll probably also be back on the MSDN forums, especially the Smart Device section to help out other developers running into issues with mobile development

SQL Compact Query Analyzer

I’ve been working extensively on enterprise mobility projects lately. These applications integrate into large SAP based systems and when testing the system it can get very tedious to set up some temporary data from the backend. I’m also working with some not-so-technical testers that get intimidated by the Visual Studio or the SQL Server Management Studio. This led me to writing an open source project called SQL Compact Query Analyzer

Here’s some details I pulled directly off the CodePlex site

Project Description
SQL Server Compact Edition Database Query Analyzer

Features:

– Create new database
– Automatically refresh database upon executing create/alter/drop table queries
– Displays database information (database version, filename, size, creation date)
– Displays schema summary (number of tables, columns, primary keys, identity fields, nullable fields)
– Displays the information schema views
– Displays column information (database type, clr type, max length, allows null, etc)
– Displays index information (column name, is unique, is clustered)
– Execute SQL Queries against a SQL Server Compact Edition database
– Execute multiple SQL queries (delimited by a semi colon 😉
– Easily edit the contents of the database
– Display query result as XML
– Shrink and Compact Databases
– SDF file association with SQL Compact Query Analyzer for launching directly by opening the SDF in Windows Explorer
– Displays thumbnails for IMAGE fields
– Generates Schema and Data Scripts
– Supports password protected databases
– Supports SQLCE 3.0, 3.1, 3.5 and 4.0

Coming Soon:
– Purge database content
– Create, edit, and drop tables UI
– Create, edit, and delete table references and indexes UI
– Support for SQL Server Compact Edition 2.0

Screenshots


– Displays database and schema information and executes multiple SQL queries directly


– Edit the table data directly


– Display the contents of IMAGE fields


– Performance numbers for queries


– Query errors


– Output result set as XML


– Create new database


– Shrink, compact, script database

Prerequisites:
– .NET Framework 4.0

Check it out! You might find it useful!

SQL Compact Code Generator

More than a year ago, I published a project on CodePlex called SQL Compact Code Generator. Unfortunately, I never managed to find the time to do some work on it and the project was set on a very long hold. A year after I suddenly really needed such a tool and decided that I should put in some hours on the project.

I’m currently working on a large enterprise project where changes to the database schema is done rather frequently, to avoid the pain of updating my data layer after every change I decided to use my code generator.

Here’s some details I pulled directly off the CodePlex site.

Project Description
Contains a stand alone GUI application and a Visual Studio Custom Tool for automatically generating a .NET data access layer code for objects in a SQL Server Compact Edition database.

Features:

  • Visual Studio 2008 and 2010 Custom Tool Support
  • Creates entity classes for each table in the database
  • Generates data access code that implements the Repository Pattern
  • Generates methods for Create, Read, Update and Delete operations
  • Generates SelectBy and DeleteBy methods for every column in every table
  • Generates a Purge method for every table to delete all records
  • Generates Count() method for retrieving the number of records in each table
  • Generates CreateDatabase() method for re-creating the database
  • Generates xml-doc code comments for entities and data access methods
  • Generates Entity Unit Tests
  • Generates Data Access Unit Tests
  • Generates .NET Compact and Full Framework compatible code
  • Support for SQL Compact Edition version 4.0
  • Multiple test framework code generation (MSTest, NUnit, xUnit)
  • Transaction support per DataRepository instance (Begin, Commit, Rollback)
  • Code generation options to enable/disable unit test code generation
  • Windows Phone 7 “Mango” support for generating a LINQ to SQL DataContext
Coming Soon:
  • Generate database maintenance code (clear database, shrink/compress database)
  • Support for multiple versions of SQL Server Compact Edition
  • VB.NET Code Support
  • Visual Studio Add-in

Screenshots:


NEW: Custom Tool for Windows Phone 7 “Mango”

Custom Tool


Generating Entity Classes


Generating Data Access methods that implement the Repository Pattern


Generating Entity Unit Tests


Generating Data Access Unit Tests to validate the integrity between the data layer and the actual database

Check it out! You might find it useful too…

How to display a Notification Bubble in Windows Mobile using .NETCF

Yesterday, I found myself using an old piece of code that I wrote ages ago. It’s something I’ve used every now and then for past few years. Since I myself find it useful, I might as well share it. All the code does is display a Notification Bubble in Windows Mobile. To do this you use the Notification class in the Microsoft.WindowsCE.Forms namespace. Even though the Notification class is very straight forward and easy to use, I created a helper class so that I only need to write one line of code for displaying a notification bubble: NotificationBubble.Show(2, “Caption”, “Text”);

/// <summary>
/// Used for displaying a notification bubble
/// </summary>
public static class NotificationBubble
{
    /// <summary>
    /// Displays a notification bubble
    /// </summary>
    /// <param name="duration">Duration in which the notification bubble is shown (in seconds)</param>
    /// <param name="caption">Caption</param>
    /// <param name="text">Body</param>
    public static void Show(int duration, string caption, string text)
    {
        var bubble = new Notification
        {
            InitialDuration = duration,
            Caption = caption,
            Text = text
        };
 
        bubble.BalloonChanged += OnBalloonChanged;
        bubble.Visible = true;
    }
 
    private static void OnBalloonChanged(object sender, BalloonChangedEventArgs e)
    {
        if (!e.Visible)
            ((Notification)sender).Dispose();
    }
}

Hope you found this helpful.

Working around Pivot SelectedIndex limitations in Windows Phone 7

I’ve been working on an application with 2 pages, a main page and a content page. The content page contains a Pivot control with a few pivot items. The main page does nothing but navigate to the content page and suggest which pivot item to display. The only reason the main page exists is to display the information in the pivot item headers in a more graphical and elegant way.

For some reason I can’t set the displayed pivot index to be the third item. I wanted to do this on the OnNavigatedTo event of the content page but whenever I attempt doing so an exception is thrown. Every other pivot item works fine, which I think is really weird.

To load the content page, I navigate to the page by passing some information of the pivot index I wish to be displayed. Something like this:

NavigationService.Navigate(new Uri("/ContentPage.xaml?index=" + index, UriKind.Relative));

If the value of index in the code above is set to 2 then I get an exception, any other valid value works fine. A value out of range (less than 0 or greater than 5) throws an out of range exception which is the behavior anyone would expect.

Here’s the XAML definition of the content page

<phone:PhoneApplicationPage
    x:Class="WindowsPhonePivotApplication.ContentPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    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">
 
  <Grid x:Name="LayoutRoot" Background="Transparent">
    <controls:Pivot Name="pivot" Title="CONTENT PAGE">
      <controls:PivotItem Header="first" />
      <controls:PivotItem Header="second" />
      <controls:PivotItem Header="third" />
      <controls:PivotItem Header="fourth" />
      <controls:PivotItem Header="fifth" />
      <controls:PivotItem Header="sixth" />
    </controls:Pivot>
  </Grid>
 
</phone:PhoneApplicationPage>

To work around this limitation, you can handle the Loaded event of the page and update the pivot selected index from there. Here’s an example how to do it:

public partial class ContentPage : PhoneApplicationPage
{
    private int pivotIndex;
 
    public ContentPage()
    {
        InitializeComponent();
 
        Loaded += delegate { pivot.SelectedIndex = pivotIndex; };
    }
 
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        string value;
        if (NavigationContext.QueryString.TryGetValue("index", out value))
        {
            pivotIndex = 0;
            int.TryParse(value, out pivotIndex);
        }
    }
}

I’m not sure if this limitation is by design or it’s a bug in the control. Either way I managed to get it to work the way I wanted it to. Hopefully I’m not the only one who ran across this and that you found this information useful.

How to Darken an Image in WPF

I’m really getting carried away with playing with image manipulation in WPF. Here’s a short post on how to darken an image using the WriteableBitmap class.

The process is fairly simple, I manipulate each pixel by decrementing each RGB value with the provided level

unsafe static BitmapSource Darken(BitmapSource image, double level)
{
    const int PIXEL_SIZE = 4;
    int height = image.PixelHeight;
    int width = image.PixelWidth;
 
    var bitmap = new WriteableBitmap(image);
    bitmap.Lock();
 
    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
    for (int y = 0; y < height; y++)
    {
        var row = backBuffer + (y * bitmap.BackBufferStride);
        for (int x = 0; x < width; x++)
            for (int i = 0; i < PIXEL_SIZE; i++)
                row[x * PIXEL_SIZE + i] = (byte)Math.Max(row[x * PIXEL_SIZE + i] - level, 0);
    }
 
    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
    bitmap.Unlock();
 
    return bitmap;
}

Hope you found this useful.

How to Brighten an Image in WPF

Now I’m just getting carried away with playing with image manipulation in WPF. Here’s a short post on how to brighten an image using the WriteableBitmap class.

The process is fairly simple, I manipulate each pixel by incrementing each RGB value with the provided level

unsafe static BitmapSource Brighten(BitmapSource image, double level)
{
    const int PIXEL_SIZE = 4;
    int height = image.PixelHeight;
    int width = image.PixelWidth;
 
    var bitmap = new WriteableBitmap(image);            
    bitmap.Lock();
 
    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
    for (int y = 0; y < height; y++)
    {
        var row = backBuffer + (y * bitmap.BackBufferStride);
        for (int x = 0; x < width; x++)
            for (int i = 0; i < PIXEL_SIZE; i++)
                row[x * PIXEL_SIZE + i] = (byte)Math.Min(row[x * PIXEL_SIZE + i] + level, 255);
    }
 
    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
    bitmap.Unlock();
 
    return bitmap;
}

Hope you found this useful

How to Alpha Blend 2 Images in WPF

After having such fun trying to find optimal ways of manipulating images in WPF I decided to write another short post on image manipulation. This time I’d like to demonstrate how to alpha blend 2 images using the WriteableBitmap class.

I’m probably not the best one to explain how alpha blending is done but here’s the idea in a nutshell. I get the RGB values of every pixel for the each image and write them to a new bitmap where I manipulate each color information by applying the following formula:

r = ((image1 pixel (red) * alpha level) + (image2 pixel (red) * inverse alpha level)) / 256
b = ((image1 pixel (blue) * alpha level) + (image2 pixel (blue) * inverse alpha level)) / 256
g = ((image1 pixel (green) * alpha level) + (image2 pixel (green) * inverse alpha level)) / 256

unsafe static WriteableBitmap AlphaBlend(BitmapSource image1, BitmapSource image2, int alphaLevel)
{
    const int PIXEL_SIZE = 4;
    int ialphaLevel = 256 - alphaLevel;
    int height = Math.Min(image1.PixelHeight, image2.PixelHeight);
    int width = Math.Min(image1.PixelWidth, image2.PixelWidth);
 
    var bitmap = new WriteableBitmap(width, height, image1.DpiX, image1.DpiY, PixelFormats.Bgr32, null);
    var bitmap1 = new WriteableBitmap(image1);
    var bitmap2 = new WriteableBitmap(image2);
 
    bitmap.Lock();
    bitmap1.Lock();
    bitmap2.Lock();
 
    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
    var bitmap1Buffer = (byte*)bitmap1.BackBuffer.ToPointer();
    var bitmap2Buffer = (byte*)bitmap2.BackBuffer.ToPointer();
 
    for (int y = 0; y < height; y++)
    {
        var row = backBuffer + (y * bitmap.BackBufferStride);
        var img1Row = bitmap1Buffer + (y * bitmap1.BackBufferStride);
        var img2Row = bitmap2Buffer + (y * bitmap2.BackBufferStride);
 
        for (int x = 0; x < width; x++)
            for (int i = 0; i < PIXEL_SIZE; i++)
                row[x * PIXEL_SIZE + i] = (byte)(((img1Row[x * PIXEL_SIZE + i] * alphaLevel) + (img2Row[x * PIXEL_SIZE + i] * ialphaLevel)) >> 8);
    }
 
    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
    bitmap2.Unlock();
    bitmap1.Unlock();
    bitmap.Unlock();
 
    return bitmap;
}

The method above will probably work best if the 2 images are of the same size. I hope you found this information useful.

How to convert an image to gray scale in WPF

I’ve been playing with the Windows Presentation Foundation today and I had a task where I needed to convert an image to gray scale to do some image analysis on it. I’ve done this a bunch of times before using GDI methods or by accessing the BitmapData class in .NET. For this short post I’d like to demonstrate how to manipulate images using the WriteableBitmap class.

The easiest way to convert an image to gray scale is to set the RGB values of every pixel to the average of each pixels RBG values.
R = (R + B + G) / 3
G = (R + B + G) / 3
B = (R + B + G) / 3

Here’s a code snippet for manipulating a BitmapSource object using the WriteableBitmap class into a gray scale image:

public unsafe static BitmapSource ToGrayScale(BitmapSource source)
{
    const int PIXEL_SIZE = 4;
    int width = source.PixelWidth;
    int height = source.PixelHeight;
    var bitmap = new WriteableBitmap(source);
 
    bitmap.Lock();
    var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
    for (int y = 0; y < height; y++)
    {
        var row = backBuffer + (y * bitmap.BackBufferStride);
        for (int x = 0; x < width; x++)
        {
            var grayScale = (byte)(((row[x * PIXEL_SIZE + 1]) + (row[x * PIXEL_SIZE + 2]) + (row[x * PIXEL_SIZE + 3])) / 3);
            for (int i = 0; i < PIXEL_SIZE; i++)
                row[x * PIXEL_SIZE + i] = grayScale;
        }
    }
    bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
    bitmap.Unlock();
 
    return bitmap;
}

Another way to to convert an image to gray scale is to set the RGB values of every pixel to the sum of 30% of the red value, 59% of the green value, and 11% of the blue value. Hope you find this useful.