UI Updates – Part 1

Updating the UI is a problem and it is tricky. There are very few simple rules to follow. Let’s see Here we’ll see  some smart ways to perform UI updates on Console applications, Windows Forms, WPF, ASP.NET, Silverlight, Windows Phone and Windows Store apps.

Console Applications

Do they have UI ? No. But we’ll check how different threads perform updates on Console applications. Look at the following code. It has a main thread and another thread (worker thread) perform some time consuming task and updates the UI. Main thread shows a rotating bar till the worker thread completes.

   1: class Program

   2:     {

   3:         static void Main(string[] args)

   4:         {

   5:             Console.WriteLine("Application Start");

   6:             Thread worker = new Thread(PerformTask);

   7:  

   8:             worker.Start();

   9:  

  10:             ShowConsoleWaitAnimation(worker);

  11:  

  12:             Console.WriteLine("Application End");

  13:             Console.ReadKey();

  14:  

  15:         }

  16:  

  17:  

  18:         private static void PerformTask()

  19:         {

  20:             // job time 4 - 10 seconds

  21:             int time = new Random().Next(4,11);

  22:             Thread.Sleep(1000 * time);

  23:             Console.WriteLine("Hello from worker - ran for {0} seconds",time);

  24:         }

  25:  

  26:  

  27:         private static void ShowConsoleWaitAnimation(Thread thread)

  28:         {

  29:             while (thread.IsAlive)

  30:             {

  31:                 Console.Write("Processing - /\r");

  32:                 Thread.Sleep(100);

  33:                 Console.Write("Processing - -\r");

  34:                 Thread.Sleep(100);

  35:                 Console.Write("Processing - \\\r");

  36:                 Thread.Sleep(100);

  37:                 Console.Write("Processing - |\r");

  38:                 Thread.Sleep(100);

  39:             }

  40:         }

  41:     }

 

Windows Forms

Look at the below code. In a simple Windows Forms application, for a button click event, a time consuming task runs in a separate thread and tries to update a Label control.

   1: private void BtnStartWork_Click(object sender, EventArgs e)

   2: {

   3:     Thread worker = new Thread(PerformTask);

   4:     worker.Start();

   5: }

   6:  

   7: private void PerformTask()

   8: {

   9:     // job time 4 - 10 seconds

  10:     int time = new Random().Next(4, 11);

  11:     Thread.Sleep(1000 * time);

  12:     LblStatus.Text = String.Format("Work completed - ran for {0} seconds", time);

  13: } 

 

When you run the above code, you will get this famous Exception. Because the Label control is created in UI thread and our worker thread tries to reach it. Cross thread referencing cannot happen as this is a violation of operating system thread handling policies. ( Do not mistake the cross thread communication and cross thread referencing, cross thread communication can happen among threads)

image

There are plenty of solutions for this problem, but the ready made one is to use BackgroundWorker class. The below code shows how you can use BackgroundWorker class and perform UI updates and also shows a progress bar on the UI. Events are coded inline to reduce the number of methods for this small demo.

   1: public partial class Form1 : Form

   2: {       

   3:        private BackgroundWorker _bgWorker = new BackgroundWorker();

   4:        private string _result = String.Empty;

   5:  

   6:        public Form1()

   7:        {

   8:            InitializeComponent();

   9:        }

  10:  

  11:        private void BtnStartWork_Click(object sender, EventArgs e)

  12:        {

  13:            _bgWorker.WorkerReportsProgress = true;

  14:  

  15:            _bgWorker.DoWork += (s, ev) =>

  16:                {

  17:                    _result = PerformTask();

  18:                };

  19:            

  20:            _bgWorker.ProgressChanged += (s, ev) =>

  21:                {

  22:                    workerProgressBar.Value = ev.ProgressPercentage * 100;

  23:                };

  24:  

  25:            _bgWorker.RunWorkerCompleted += (s, ev) =>

  26:                {

  27:                    LblStatus.Text = _result;

  28:                };

  29:  

  30:            _bgWorker.RunWorkerAsync();

  31:        }

  32:  

  33:  

  34:        private string PerformTask()

  35:        {

  36:            // job time 4 - 10 seconds

  37:            int time = new Random().Next(4, 11);

  38:            int fullTime = time;

  39:  

  40:            while (time >= 0)

  41:            {

  42:                Thread.Sleep(1000);

  43:                _bgWorker.ReportProgress(1 - (time / fullTime));

  44:                time--;

  45:            }

  46:  

  47:            return String.Format("Work completed - ran for {0} seconds", fullTime);

  48:         }

  49:           

  50: } 

 

WPF

In WPF we can use the BackgroundWorker, but also there’s a well refined solution in the WPF is to use the Dispatcher object. WPF model has Dispatcher object common across all the controls. So we can use this to update the UI.

Little modification in the PerformTask() and make it return the result.

   1: private string PerformTask()

   2: {

   3:     // job time 4 - 10 seconds

   4:     int time = new Random().Next(4, 11);

   5:     int fullTime = time;

   6:  

   7:     Thread.Sleep(time);      

   8:  

   9:     return String.Format("Work completed - ran for {0} seconds", fullTime);

  10: } 

Button click event.

   1: private void BtnWork_Click(object sender, RoutedEventArgs e)

   2: {

   3:     Thread thread = new Thread(() =>

   4:         {

   5:             string result = PerformTask();

   6:             Dispatcher.Invoke(() =>

   7:                 {

   8:                     TxtStatus.Text = result;

   9:                 });

  10:         });

  11:     thread.Start();

  12: }

Part 2 – will discuss about UI updates in ASP.NET and Silverlight.

Advertisement

Programming Microsoft Surface

This post contains some high resolution images, please wait till all the images are loaded and click on them to enlarge.

Microsoft Surface computing is awesome and for me the business strategy behind the scenes are very very awesome. Microsoft released surface computer and very limited set people are using it right now. Because it is expensive and needs rich infrastructure as well. But in the business point of view MS released surface because surface computing needs lot of innovation from the hardware vendors. The first release was a big bulk desk, and the second release of Samsung SUR 40 it is slim; just 4 inches. So in the future it will be like a paper and the real surface. So when the world is really ready for the surface, the real surface will also be ready.

microsoft-surface-5

 

The world is not yet ready for the surface, so as the surface computing. So MS took the above strategy to make the surface mature and available when really the majority of the world is matured to have the surface.

Surface computing provides a software platform as like other devices of the IT industry. The surface software platform is built on top of WPF. It also includes the Power Shell administration.

To develop surface applications we do not need to have a surface computer. 🙂 You can develop and test the applications in your PC like you develop the WPF applications. To do this you have to install Surface SDK and the Surface runtime in your machine.You can download the Surface SDK (still in beta) from here

Once you installed them you will have surface application template in Visual Studio.

image

It offers surface type controls and you can do the programming with that. Some built in controls are really cool. UI is defined using XAML.

A sample application to view pictures and to arrange them in two stacks with a floating interface would be like this.

Note :

Surface computer is a very powerful hardware device. It has infrared sensors in built which can detect the objects placed on it and capable of connecting with them.

It is capable to take 52 touch inputs with pressure at a time. (In the future this may increase). If you consider a person dealing with the surface computer with all his fingers, it can still handle 5.2 people at a time. Mostly we use 2 points. So in a best scenario 26 people can interact with it. And all the touches are measured with the pressure.

When we develop our applications in the machine, we don’t need a touch enabled screen. But if you have a 2 point touch enabled screen it will be nice. (You can resize images, videos and more …) And another major limitation is, most of the PC monitors or laptops which are touch enabled detect the point of a touch. They cannot detect the pressure. SDK provides events and methods we can use with the pressure.

So when we do development in a PC we can neither check those hardware specific methods nor object detection.

But still we can have fun.

This is a sample code shows how you can create movable items in the surface. These are free moving and 2 point resizable objects.

ScatterView is the XMAL snippet for creating this free floating objects.

(Click the image to view the enlarged code)

image

As you can see the code is simple XAML , and we can place any number of and any type of controls inside the scatter view. I have used media element controls to put videos and Image tags to put images inside the ScatterView.

The transforms and the other settings are optional.

This single line create a multi touch enabled drawing panel. (Margins are optional)

image

I created a drawing board embedded with n image where we can color the image. (See how it works in action)

image

In the above image you can see the disadvantage of the point touch. I can draw thin lines (point lines)  since my laptop touch screen is not pressure sensitive. In the real surface you can draw with the thickness of your own finger which gives a real drawing experience. You can also adjust the thickness programmatically.

I tried something more with surface SDK with mixing the scatter view with traditional WPF features and created a stunning floatable windows in the desktop. Where you see only objects no any windows and cross overlaps on each other. It is bit advance and I didn’t explain the code here, but some images are given below.  Enjoy 🙂

Sorry for the white marks on the image and taskbar as I have to hide some files and programs.

Floating objects in desktop. (As you see three of them are media players and two image viewers)

1

They are completely independent and the coolest feature is they are not windows. They act as objects in separate frames. The below images show that, see how I’m interacting with the desktop while they are floating on the desktop.

This picture shows that I’m interacting with the desktop. I’m hovering on a file which is partially covered by one of the floating object, but still I can get the description of the file.

2

Here I’m interacting with the task bar and the start button.

3

Other than this surface SDK offers plenty of nice tools like StackLibrary and Containers. Flexible surface is another feature which creates a water like surface. When touch or click on the screen you can experience ripples.

I’ll try to put a video, I still do not have a YouTube account. 😛

Silverlight and WPF Browser Application

You can see there 2 templates in Visual Studio. One is Silverlight Application in the Silverlight category and the other one is WPF Browser Application in the Windows category.

We know both the Silverlight and the WPF use XAML to define their UI logic, and Silverlight is for web and browsers (not for sure, you can have Silverlight out of the browser applications).

So what is WPF Browser Application ? What is the difference between Silverlight and WPF Browser Application ?

WPF Browser Application needs .NET Framework 3.0 or above to run the application. It has full functionality from .NET Framework. If you develop XBAP, which means your whole web application is written in XAML and WPF.

Silverlight is a small subset of .NET Framework, but it does not need .NET Framework, it has its own small runtime engine. It is a browser add-in, and used for displaying rich contents on the web page. It can also interact with JavaScript. If you develop Silverlight, which means your web page can contains more rich contents, just like Applet or ActiveX control on the web page.

Since WPF Browser Application uses installed .NET Framework of the local machine, it can leverage the libraries that Silverlight does not. Though conceptually that is right WPF Browser Applications run inside a sandbox where it has limited privileges. So to read or write data to the local machine the Application has to be set in the Full Trust mode.

For example you can have access to the ADO.NET library in WPF Browser Application.

 

image

It throws a SecurityException, because by default WPF Browser Application is set to Partial Trust mode. Go to the Properties of your project and change the security settings to Full Trust and then your code will run.

image

But this is not preferable and a solution unless your client can allow the application to be Full Trusted. This is OK to do an intranet environment.