Sunday, December 30, 2007

Wind of changes and happiness at the end of this year - Welcome Santiago!

I'm very sorry because I know, there were several days without any post on this blog, but I think you'll understand the reasons.

First of all, I have left Q4Tech after almost 8 years of great experiences and lot of friends there. It's just time to go ahead and continue my way. The selected destination was Clarius Consulting where I've already started working as Dev Lead. I've previously worked with Daniel Cazzulino (Kzu) on the development of the Patterns & Practices Mobile Client Software Factory, and some Microsoft Live Labs projects, so this is a familiar place to work for me, and I'm really happy to start this new stage on my professional life with such hi-level team.

But there is another big, huge reason to be happy at this end of 2007, my first son was born on December 24th, What a Christmas present!! The Best one!

Well, he is just 6 days old (or young), and I'm so proud of let you know him, Santiago Gallardo is here:

SantiGallardo

He's the reason because I don't remember what is to sleep 3 hours in a row ;)

Happy New Year for all of you! I'll continue posting about mobility on 2008... see you then!

Tuesday, December 11, 2007

Adaptative UI sample using our multiline MeasureString implementation

I've decided to post a sample application showing how to use the multiline MeasureString code provided on my previous post, to build a dynamic/adaptative UI. It also support screen rotation.

Here you have some screenshots:

image

After changing the text and pressing "Relayout" you can get something like this:

image

And rotating the screen:

image

Finally, this is the source code, enjoy it!

Wednesday, December 5, 2007

Multi-line Graphics.MeasureString implementation on .Net CF

If you have ever tried to build a dynamic UI for a .Net Compact Framework application, probably you've had to build adjustable multi-line labels or text-boxes. It's hard to solve because the only supported overload for Graphics.MeasureString on .Net CF is:

public SizeF MeasureString ( string text, Font font )

When you need to resize or position the controls dynamically in runtime, it's very important to know what should be the size, particularly the height of the multi-line label or multi-line text-box. It's the same problem if you're building a new custom control with a complex layout and you need to measure a potential multi-line string.


Having only this overload on .Net CF, we cannot get a multi-line string size because it calculates just the size of a single-line string. If the string is longer than the string, it gets a big SizeF result but as a single-line text.


Solving the problem


The only solution here is to implement our own multi-line MeasureString method.


To solve the problem, we'll use the native API DrawText. It will calculate the size of the text according with the uFormat parameter and using the graphics (device context) selected font.

[DllImport("coredll.dll")]
static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref Rect lpRect, int wFormat);

Additionally, if the control if a text-box, we should use the DT_EDITCONTROL flag and add extra 6 pixels (3 pixels at top and 3 pixels at bottom) to the calculated size.


Remember, if you have an empty string, you'll probably need to force one-line size for your controls.


Here's the CFMeasureString sample class source code:

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace MeasureStringSample
{
public class CFMeasureString
{
private struct Rect
{
public int Left, Top, Right, Bottom;
public Rect(Rectangle r)
{
this.Left = r.Left;
this.Top = r.Top;
this.Bottom = r.Bottom;
this.Right = r.Right;
}
}

[DllImport("coredll.dll")]
static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref Rect lpRect, int wFormat);
private const int DT_CALCRECT = 0x00000400;
private const int DT_WORDBREAK = 0x00000010;
private const int DT_EDITCONTROL = 0x00002000;

static public Size MeasureString(Graphics gr, string text, Rectangle rect, bool textboxControl)
{
Rect bounds = new Rect(rect);
IntPtr hdc = gr.GetHdc();
int flags = DT_CALCRECT|DT_WORDBREAK;
if (textboxControl) flags |= DT_EDITCONTROL;
DrawText(hdc, text, text.Length, ref bounds, flags);
gr.ReleaseHdc(hdc);
return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top + (textboxControl? 6 : 0));
}
}
}

And you can use it to resize a label in the following way:

label1.Height = CFMeasureString.MeasureString(CreateGraphics(), label1.Text, label1.ClientRectangle, false).Height;

Now we can start using it and build a dynamic UI on .Net CF.


Update: To support different font sizes, please take a look at this post which shows a good improvement (a.k.a. fix ;)).

Sunday, December 2, 2007

Working with forms in Windows Mobile

As we've already seen, a mobile application UI is naturally modal. Does it mean every form should be open using Form.ShowDialog()?

Of course it doesn't. There are several business requirements (like complex navigation schemas), design and architectural constrains or even basic requirements like the need of implement a wizard that require a different approach. Here's where we need to face new design challenges to provide a rich user experience in our application.

How to show a form in Windows Mobile

It depends on the use case, but you should take care of the form title, the Running Programs window and how it interacts with the multitasking environment.

PocketPC and the Running Programs list

You can show a .Net CF form using Form.Show() or Form.ShowDialog(). In both you'll get in the Running Programs list one instance for each open form, as they were different applications, and you can navigate to any form from that list directly (it will appear disabled if using Form.ShowDialog()).

The first method to prevent this, is every time you show a form, you should change the current form title to an empty string (String.Empty), in the Running Programs List you'll see only the new form title. When you come back, you should change the title (Form.Text property) again to the original title and it will be the one on the Running Programs List. Here you have a sample code:

private void menuItem1_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
this.Text = String.Empty;
form.Show();
}
private void Form1_Activated(object sender, EventArgs e)
{
this.Text = "Form1";
}

The second method is using Form.Owner (valid only for .Net CF 2.0+). In this case you should set the Form.Owner property of the new form to the current form, and the title will remain the current form's title. Due to this, we need to change the current title to the new form title and set it back when we come back to the form.

It makes sense if you're using Form.ShowDialog() or if you have a controller form and you're showing kind of a wizard opening different forms and all of them have the same "controller form" as the owner (which is where you start and where you finish the wizard).

Here is the sample code for method 2:

private void menuItem2_Click(object sender, EventArgs e)
{
Form3 form = new Form3();
form.Owner = this;
this.Text = form.Text;
form.Show();
}
private void Form2_Activated(object sender, EventArgs e)
{
this.Text = "Form2";
}

Handling Form_Activate and Form_Deactivate events

Form_Activate is not only useful to set the form title back when the user returns to the form. As we've seen before, Windows Mobile is a multitasking environment and we should deal with it. Here's when Form_Activate and Form_Deactivate are fully helpful.

You can stop unnecessary expensive processes if the application is in background on Form_Deactivate, and start them again when Form_Activate in order to preserve processor, memory and fundamentally battery.

Keep it in mind when you develop more mobile applications.

Tuesday, November 20, 2007

The Modal Nature of Mobile Applications

Probably the most typical design error made on any mobile application development is facing it as a traditional desktop development; especially, regarding the user experience side.

As we can see during almost any mobile development, achieve a good user experience is the hardest goal we have to face. On that way, we should prioritize "simplicity" in our applications.

The simplest user interface you have the best user experience you get. And here, as in most of the mobile development topics, we should get the right balance.

Simplicity for a mobile application UI means:

  • Show less graphic elements as possible, but show all the information required.
  • Show few options but enough to let the user do what he need in the less number of steps possible.

Windows Mobile is a very different environment compared to a desktop platform where you can have a 15" or bigger screen. Due to this constrain, a Windows Mobile application, even each form /dialog on the application, should take ownership of almost all the screen in order to provide the best possible user experience. Actually it's not weird to find full screen applications.

If we need almost all the screen to show any form or dialog, then we can only show one form/dialog at the same time. This is what defines the modal nature of mobile applications. Having a modal approach, a mobile application is closer to get simplicity.

That's the reason because dialogs are full screen by default in any Windows Mobile device. But screen size is not the only constrain on that way, input devices are also constrained and it makes almost inviable a modaless mobile application. Background operations on mobile applications are typically limited to synchronization tasks, and even sync should be performed in foreground very often.

It doesn't mean the user cannot switch between apps. If we don't have explicit business constrains regarding it, multitasking is a good feature and it's not only welcomed, it should be preserved.

Today is highly common to find devices with cellular telephony support. Smartphones and Pocket PC phone edition require the application let the user switch easily to and from phone features.

Multitasking is the reason of having a smart minimize button on the top right corner of Pocket PC forms, or the reason of having a back button on smartphone switching between apps. Home and Phone buttons also allows switching to the device main screen or phone functionality.

On that scenario, our modal mobile application should also be prepared for multitasking, and be prepared for handle the background state preserving processor and battery.

Line of business applications use to have a transactional-approach and high memory consumption. It makes essential in many cases to have an explicit "exit" option. It allows you to verify the complete business operation during the application usage, and free taken resources for other applications.

Next time you design a mobile application, remember: a mobile application should be simple. Being modal it's closer of being simple. But it should also interact with a multitasking environment.

Tuesday, November 13, 2007

Creating a Splash screen for your .Net CF Application

As you already know, performance is a critical issue in any mobile solution. We have to take care of many things, but probably the more important aspect of any mobile development improvement, should be the UI responsiveness.

If the user press a button and wait for 15 seconds with no feedback until the action is finally done, he'll feel the sensation of something going wrong with the application, or probably the need to press the button again. Sometimes a good option is to initialize some load-expensive resources at start-time. The problem here is we already have performance expensive tasks while the application is being launched, and due to adding optimization tries we can found ourselves running an application which takes 20 seconds until the first form is show.

Here's where splash screens help us. It's radically different an application that only shows a wait cursor during 20 seconds until the first form appears than an application which shows the splash screen after 4 seconds letting the user know something is going on, and showing progress during the next 25 seconds even if it's taking more than the original 20 seconds. The key here is feedback, information. The user knows what is going on. He has information, he knows the application is already running, even if it still being loaded.

image

Add a splash screen to your mobile application can looks like a piece of cake, but it's not. There are three important guidelines that you should follow if you want to get the advantages of having a splash screen:

  • It should be shown as soon as possible.
  • Show the splash screen should be a light weight process.
  • It should show progress (or activity at least).

As a .Net CF application usually starts showing a main form, it's recommendable to show the splash screen while the form is being initialized. As we've seen before, it should be a light weight process; ideally it should be as light as possible. A very good option is to create a very simple Splash Form and draw the splash screen directly overriding the OnPaint method. The Splash Form should be maximized (WindowState = Maximized) and totally empty (free of menus or controls).

Then, we can override OnPaintBackground leaving it empty to improve the performance (we don't need to paint a background here anyway), and draw the SplashScreen manually overriding OnPaint:

protected override void OnPaint(PaintEventArgs e)    
{
    Font font = new Font("Arial", 10, FontStyle.Bold);
    if (backgroundBmp == null)
        backgroundBmp = (Bitmap)Properties.Resources.ResourceManager.GetObject("SplashBitmap");
    e.Graphics.DrawImage(backgroundBmp, 0, 0);
    e.Graphics.DrawString("Splash Screen Sample", font, new SolidBrush(Color.Yellow), 37, 30);
    e.Graphics.DrawString("http://www.mobilepractices.com", font, new SolidBrush(Color.White), 7, 50);
    e.Graphics.DrawString("Loading...", font, new SolidBrush(Color.White), 65, 78);

    ShowProgress(0);
}

In this code, we're drawing the full splash screen, but the progress is painted in a different method called "ShowProgress". It will show the progress painting directly on the form graphics:

public void ShowProgress(int percentage)    
{
    Graphics gr = this.CreateGraphics();
    gr.DrawRectangle(new Pen(Color.Black), new Rectangle(32, 95, barwidth, 12));
    gr.FillRectangle(new SolidBrush(Color.Black), new Rectangle(32, 95, (barwidth * percentage) / 100, 12));
}

This method will update the progress quickly while your application is being initialized, without the need of paint the full splash screen for each update.

On the main form constructor on your application ("Form1.cs" in the sample code), you should create and show the splash form for first time, and let the system process the events (Application.DoEvents()) to get the splash visible. This will use OnPaint (and probably this will be the only time OnPaint is called) to draw the splash. From this point we'll use ShowProgress to update the splash showing progress, like in the following sample code (where thread.Sleep is used to simulate some expensive initialization tasks):

public void Initialize(SplashForm splash)    
{
    //Show the splash
    splash.ShowProgress(30);
    //... intialization first steps
    Thread.Sleep(1000);
    //... update splash
    splash.ShowProgress(50);
    //... some intialization steps

...

I'm including a sample application for Windows Mobile 6 Standard Edition (formerly Smartphone). Hope it helps:

Wednesday, November 7, 2007

Building a .cab installer which registers the assemblies in the .Net Compact Framework GAC

Update: I've recently posted a new article about How to create a Smart Device .Cab Installer which is intended for more general purposes than registering assemblies in the GAC. If you're looking for that it can be very helpful. (02/06/2008)

Continuing with the example in the previous post, let's see how we can use Visual Studio 2005 to create a .cab installer which will register the assemblies in the GAC.

The first step is to create a new Smart Device CAB Project:

image

Open the File System Editor (it could be already open) pushing the button on the Solution Explorer toolbar.

image

Create a new "Global Assembly Cache" folder on the file system editor: Right Click on "File System on Target" - "Add Special Folder" - "Global Assembly Cache Folder"

image

Add the assemblies to the "Global Assembly Cache Folder" using the context menu "Add - File" option or just drag & drop them to the folder:

image

Now, you have both files on the GAC Folder. You just need to build the .cab project.

If you take a look at the build result, you'll see the following files:

image

Please pay special attention to the "MyUI.GAC" file. This file is a .gac file with the following content:

%CE2%\MyCustomControls.dll
%CE2%\MyExtendedControls.dll

When the .cab is installed on the device, all the assemblies and the .gac file will be placed on the "\Windows" folder. The next time a .Net CF application is launched, the assemblies will be registered in the GAC.

If you uninstall the .cab from the device (i.e. using the "Remove Programs" option), the .gac file will be removed and the next time a .Net CF app is launched the also assemblies will be removed from the GAC, as we've seen in my previous post. It's just very simple! isn't it?