Welcome to MSDN Blogs Sign in | Join | Help
Extracting Styles from Silverlight Controls

There are various times where you often find yourself needing to change styles and then the key problem here is that you can’t grab hold of the styles. A classic example is that of trying to style things in the Silverlight Toolkit.

To get around this problem I use 2 great tools. One is called Silverlight Spy and the other Reflector.

Silverlight Spy allows you to take a sneak peak at what’s going on under the hood. Reflector is a .NET disassemble tool.

In this example I’m going to show you how to style a Calendar control from the Silverlight (System.Windows.Controls). In this example I’m going to change the backgrounds for the various day types (normal, selected, today).

So I have created a basic Calendar control on screen:
 image

I then load up Reflector and I get it to load the DLL of the Silverlight Controls. I then disassemble the DLL and load up the contents

image 

 

I then right click the themes/generic.xaml in the right pane and then Save As. I then open the saved file to find loads of styles for all the various components in the DLL. Now to get a greater understanding of what Style I want I use Silverlight Spy.

image

So I’ve decided that I’m going to change the background colours of the all the days so according to the Silverlight Spy I should be looking at CalendarDayButton, which just so happens to have a Style attached to it, which can be seen in the generic.xaml we downloaded. I need to change the Fill property of 3 Rectangles called TodayBackground, SelectedBackground and Background.

image

All I need to do it copy and paste the Style into my resources so it’s available to my Calendar control and hunt down those rectangles.

image

A few changes to the fill properties.

Now you need to make sure you do this checklist:

- Ensure you have the ResourceDictionary from the generic.xaml also pasted otherwise you will get loads of vsm errors.

- Name the Style so in this case I set the Key of the Style to myCalendarStyle.

- Don’t forget to apply the style to your control

<controls:Calendar CalendarDayButtonStyle="{StaticResource myCalendarStyle}" />

Load the page up again and:

image

Granted the colours aren’t great but you get the gist. :)

WPF FX Library

imageThanks to the great Hardware Acceleration of WPF you are able to take full advantage of Pixel Shaders although with time always being against us there is never enough time to write all the Math to get a decent Pixel Shader, well you need not worry anymore.

The release of the WPF FX Library has now solved this problem. To see more of what it can do visit:

http://channel9.msdn.com/shows/Continuum/WPFFXDemo/

I was really surprised at how easy it was to get this working, within just a few lines of code I had my images rippling, twirling, pinching, colour changing etc. etc…

LiveJournal Tags: ,
Touchless, iTable and Surface

Surface

One of many innovate products created by Microsoft is the Surface. Having had the fortunate experience of playing with a Surface machine it goes without saying that it is superb. The multi-touch capabilities make this an engaging and compelling experience for everyone using it.

On more research of the Surface I found that box consists of cameras inside facing upwards onto the glass. These cameras detect shadows/images on the glass and then can work out your movement.

 

imageThis gave me an idea, it would be wonderful if using just a web cam I could create the same effect. So… I decided to do some live searching and found an SDK that already that allows me to do this, it was called Touchless.

They already provide a demo application that will allow you to have a play around, I ended up playing the classic game of Pong with my flatmate. The experience was smooth and quite good fun. Touchless doesn’t use a glass table but allows you interact with your software in midair just with hand gestures. Similar to what is show in the film Minority Report.

The downside to this application is that it requires markers to monitor movement. So we ended up using bright red towels as the markers and then the application was able to monitor their movement. It works very much like a green screen, so this means it won’t work with your hands as the application sometimes thinks your face is an marker as well and gets all confused. May a bright coloured glove would work?

imageI thought I would do some more live searching on Surface and then found something called iTable. Contrary to it’s name, it’s not an Apple product nor does it run OS X. In fact it’s running Windows XP. This is basically a touch screen with multi-touch, described as a big iPod Touch/iPhone, maybe where the name iTable originated from. The video on the site shows some cool things like multi-touch World of War craft.

 

Does this mean that Surface is now obsolete in a market where multi-touch can be created with a simple use of a web cam? or even a cheaper alternative touch screen?.

The answer is definitely no.

Surface still has a lot more on offer than what is currently out there on the market.

Firstly, of all the technologies above Surface is the only that allows you to detect the position of the hand as it records shadows it can work out which way a person is facing.

The surface also has rotation, so unlike the others the user could be sitting around the table and the UI would adjust according which you would not get from the iTable, you’re not likely to use the Touchless stuff upside down.

Surface also has a neat trick of using byte patterns that allow you to tag items, this was demonstrated with the demo of wines which is a perfect example of where they tag a bottle of wine. This allows them to work out what you’ve ordered and add it to your bill, make recommendations on what else you might like, or even being able to tag your credit card and therefore the bar would always make sure they have your wine in stock, loyalty points, the possibilities are endless…

Surface has Bluetooth technology that makes sending information via smart phones, digital cameras a breeze. In fact with a home server as well the table could become even more powerful taking data from a streaming source. The concierge service on the Surface allows you to plan your day using Virtual Earth and other services and then uploads that information to your mobile device so your calendar and all the details are stored on your phone ready for you go.

I think with all this under the hood it still makes Surface a market leader.

Changing the UI in a Multi-Threaded WPF Application

About
This whitepaper is based on the various ways in which a thread can access the user interface in a multithreaded WPF application.

Although the example provided in this document is very simple, it is designed to give a foundation of the concepts of what is a core topic for anyone aspiring to be a WPF developer.

Intended Audience
This white paper is intended for people with an intermediary understanding of WPF. They should have knowledge of XAML and the basic ways in which the code behind communicates with the user interface. The reader should also have firm knowledge of threads and understand the difference between synchronous and asynchronous calls.

Why is this topic important?
The WPF architecture is designed to have the entire user interface of a window running on a single thread, the reason for this is simple. The single thread design increases simplicity and removes any complications that can occur when threads access the user interface across a multithreaded environment and finally performance is increased because thread affinity avoids locking, which would normally in a multithreaded environment increase overheads.

All user interface objects have thread affinity, which means that it belongs to the particular thread and that other threads don’t have direct access to it. It is therefore vital that you are able to jump onto (if needs be) the user interface thread and make the changes efficiently without blocking it from other processes.

 

This whitepaper will show you the various implementations to achieve this.

The Example
The example used in this whitepaper ‘spoofs’ a WPF application that is loading a large image progressively from a web service. It does this by calling a web service specifying the resolution it requires (Low, Medium and High). The web service returns the image which is then deserialized at the client side and finally displayed on screen. A progress bar and text box showing how many seconds each process takes is also displayed.

 

clip_image002
Left to right: Asynchronous call, Synchronous call, and BackgroundWorker

The DispatcherObject
In the previous section I wrote that all of the user interface objects have thread affinity, but what about the types that do not belong to the user interface, how can you tell which objects have thread affinity and which ones do not? The answer lies within looking at the base class, those that derived from the DispatcherObject class have the thread affinity requirement.

 

clip_image003

 

 

 

 

 

 

 

 

 

 

 

 

 

If an object is derived from the DispatcherObject you need to work out if you are currently on the right thread, to do this the DispatcherObject has two methods, CheckAccess() and VerifyAccess().

CheckAccess is a method that returns a Boolean to let you know if you are on the right thread

VerifyAccess will throw an exception if you are not on the right thread; this is probably used more if it is critical that your code is on the UI thread.

WPF itself uses VerifyAccess if you are trying to access an object on the wrong thread, hence why you get an exception. The Image below shows me calling out of the UI Thread :

asyncImage.Source = GetImage(Resolution.High);

 

clip_image005

WPF object frequently call the VerifyAccess() to protect themselves from being executed on the wrong thread. They do not call VerifyAccess() in every operation otherwise this would cause a massive performance overhead.

A problem with calling VerifyAccess everytime that you want to make a UI change is that once your application has many threads running then you should avoid directly accessing these objects as it could cause locking. To ensure that you can make updates to the user interfaces on the UI thread from various threads you should use the dispatcher to jump onto the user interface thread.


The Dispatcher
Every thread that creates a user interface object needs a Dispatcher object, the Dispatcher owns the thread, which in effect runs a loop that dispatches input messages to the appropriate handlers. As well as handling the input it also ensures that we are put on the right thread to make the changes to the user interface.

Obtaining the Dispatcher
All the objects that have thread affinity have the base class of DispatcherObject, this class has a property Dispatcher which will return the Dispatcher object for the thread that the object belongs to.

To access the dispatcher for the current thread you can call the Dispatcher.CurrentDispatcher static property.

Getting onto the Right Thread with a Dispatcher
Any changes to the user interface needs to be made on the user interface thread. To ensure you jump onto this thread the Dispatcher object provides you with methods that allow you to invoke your code on the thread to make the changes.

To run your code you need to call the Invoke() or BeginInvoke() methods which accept any delegate and an optional list of parameters. Both methods invoke the delegate’s target on the dispatcher’s thread however the difference is that the Invoke() method is synchronous and the BeginInvoke() method is asynchronous.

An example of the BeginInvoke() method is shown below (Calling the web service to return an image to display on the user interface):

private delegate void syncImageDelegate(Resolution resolution);

 

private void ProcessAsyncImage()
{
     
asyncImageDelegate invokeImage = SetAsyncImage;
     
asyncImage.Dispatcher.BeginInvoke(DispatcherPriority.Normal, invokeImage, Resolution.Low);  
}

private void SetAsyncImage(Resolution resolution)
{
     
asyncImage.Source = GetImage(resolution);
}

 

You can see from the code above that:

-       A Delegate is created call syncImageDelegate,

-       the method ProcessAsyncImage() is called (not shown in code snippet)

-       This then firstly creates an invokeImage which is a variable of type asynchImageDelegate

-       invokeImage is assigned the method SetAsyncImage method.

-       asyncImage (image object in xaml) has a dispatcher which is then told to asynchronously invoke the delegate. The first parameter is the Priority (Normal in this case). The second parameter is the delegate, and the final parameter is the parameters to pass to the method.

-       The SetAsyncImage method is called which is now running on the UI Thread, allowing the Image source to be set.


DispatchTimer
A common task that is needed is timer feature which is used to trigger of code on an interval basis. When you need to make changes to the UI on a common interval the best way to do this is to use the DispatchTimer object.

 

The DispatchTimer object as the name suggest is a Dispatcher with a timer feature on it. It will allow you to set an interval, and create an event handler everytime the interval happens.

The only main difference between DispatchTimer and theTimer class is the DipatchTimer class ensures that the code is ran on the UI Thread.

 

/// <summary>
/// the event handler for when the load image button is clicked to start all the threads off
/// </summary>
/// <param name="sender">load button</param>
/// <param name="e">RoutedEventArgs from the button</param>
private void Button_Click(object sender, RoutedEventArgs e)
{
//Timer Setup
    
dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
    
dispatcherTimer.Interval =  TimeSpan.FromSeconds(0.1);
    
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    
start = DateTime.Now; ;

     //Starts the downloading of the images
    
dispatcherTimer.Start();
}

 

/// <summary>
/// An event handler that is called when the interval is met to update the time of each timer text
/// </summary>
/// <param name="sender">DispatcherTimer</param>
/// <param name="e">EventArgs</param>
void dispatcherTimer_Tick(object sender, EventArgs e)
{
    
if (asyncProgress.Value != 100)
    
{
        
asyncTime.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString("#0.00") + " seconds";
    
}

     if (syncProgress.Value != 100)
    
{
        
syncTime.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString("#0.00") + " seconds";       
    
}

     if (bwProgress.Value != 100)
    
{
         
bwTime.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString("#0.00") + " seconds";
     }
}

Here you can see that when the button is clicked it creates the DispatchTimer which updates the UI so you can see how long each method is taking to load. Just as you would do with the Timer you set the properties for the Interval which requires a TimeSpan and also set an event for Tick.

The BackgroundWorker
As seen in the previous sections you can create plenty of Threads and just start them off however this ‘no frills’ version can pose possible dangers of locking on shared resources or even blocking on the UI Thread. The safest way is from existing .net 2.0 technology, a component called the BackgroundWorker found in the System.ComponentModel namespace ensures that time consuming threads are not taking up valuable processor time. It also uses the dispatcher object in the background and is the fool proof way of writing a multi-threaded application. It uses an event based model to avoid marshalling issues.

 

The BackgroundWorker has several useful event handlers:

-       DoWork

-       ProgressChanged

-       RunWorkerComplete

The DoWork is the code that is to be executed, maybe a calculation or business logic. Note that you would not do UI changes here. The code reports the progress, sets a backgroundResolution variable to what the next call should ask for, and also assigns a property called e.Result.

 

The DoWorkEventArgs has two important properties called Argument and Result. When you assign these properties they are transferable to the RunWorkerCompleted method as well. In this case we are saying that the e.Result is new resolution that the background should ask for next.

/// <summary>
/// Called when the background worker has to do work
/// </summary>
/// <param name="sender">BackgroundWorker</param>
/// <param name="e">DoWorkEventArgs</param>
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    
//Thread has been put to sleep to slow the call down so that you can see the difference in speed
    
Thread.Sleep(5000);
    
switch (backgroundResolution)
    
{
              
case Resolution.Low:
                    backgroundWorker.ReportProgress(66);
                    backgroundResolution = Resolution.Medium;
                    e.Result = Resolution.Medium;
                    break;
                case Resolution.Medium:
                    backgroundWorker.ReportProgress(100);
                    backgroundResolution = Resolution.High;
                    e.Result = Resolution.High;
                    break;
                default:
                    backgroundWorker.ReportProgress(33);
                    backgroundResolution = Resolution.Low;
                    e.Result = Resolution.Low;
                    break;
     
}
}

 

The ProgressChanged event allows you to make changes to UI to give updates on the progress of the execution, this method is only called if the backgroundWorker has explicity had it’s ReportProgress method called, we make this call in the DoWork method which updates the progress bar.

/// <summary>
/// Called when the ReportProgress method is called on the BackgroundWorker, this executes on the UI Thread
/// </summary>
/// <param name="sender">BackgroundWorker</param>
/// <param name="e">ProgressChangedEventArgs</param>
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    
bwProgress.Value = e.ProgressPercentage;
}

The RunWorkerComplete event is called when the work has been completed, this method runs on the UI thread and is advisable that all the UI changes are made here. The code assigns the image to the bwImage(Image Object in XAML) it also checks the result from the DoWork to check if a call has to be made, if the high resolution image is loaded then there is no need to make the call.

/// <summary>
/// When the background worker is complete the image is updated by deserializing the image object
/// </summary>
/// <param name="sender">BackgroundWorker</param>
/// <param name="e">RunWorkerCompletedEventArgs</param>
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
       
bwImage.Source = GetImage((Resolution)e.Result);
       
if ((Resolution)e.Result != Resolution.High)
       
{
            
backgroundWorker.RunWorkerAsync();
       
}
}

The BackgroundWorker also supports event cancellation so that whilst in the middle of a  process it can be cancelled, once cancelled the RunWorkerComplete is called with the argument e.Cancelled equalling true.

Results
When the application is ran it is clear to see that the Asynchronous calls were quicker because the Thread does not wait for the current process to finish before it starts the next process.

In Second place is the Synchronous call because a process can not execute until the prior process has finished executing, this can potentially lead to blocking up a thread having a dominio effect on the overall process.

Finally in last place is the BackgroundWorker, the reason for this is pretty simple, it’s because the ThreadPrority is set lower on the BackgroundWorker by default so it will run with less processor time.

All methods had their threads put to sleep so that the updates could be seen.

Creating a Menu in ASP.NET

After spending some time wondering how to create an effective menu I stumbled accross the System.Web.UI.WebControls Menu Class, It was really easy to implement, in your aspx file you just write some code that looks like this:

<asp:Menu ID="myMenu" runat="server" orientation="Vertical">
    <Items>
        <asp:MenuItem Text="This is a menu Item 1" />
        <asp:MenuItem Text="This is a menu Item 2" />
        <asp:MenuItem Text="This is a menu Item 3" />
    </Items>
</asp:Menu>

And there you have it a simple Menu control out of the box that you can sit on any aspx page. It's also worth mentioning that it has loads of styles you can add to it as well. To read up more have a look at:

http://msdn2.microsoft.com/en-gb/library/system.web.ui.webcontrols.menu.aspx

WPF Layout Basics

Hi all,

 Well I've finally decided to kick start my blog so I thought the first thing that I would blog about is WPF Basic Layouts.

These layouts include:

-          Stack Panel

-          Wrap Panel

-          Dock Panel

-          Grid

-          Uniform Grid

-          Canvas

 

Stack Panel
As the name suggests the stack panel stacks objects; it can stack them either horizontally or vertically:

   

<StackPanel>

        <TextBlock Text="StackPanel with Vertical Orientation"/>

        <StackPanel>

            <Button Height="20" />

            <Button Height="20"/>

            <Button Height="20"/>

            <Button Height="20"/>

            <Button Height="20"/>

            <Button Height="20"/>

            <Button Height="20"/>

        </StackPanel>

        <TextBlock Text="StackPanel with Horizontal Orientation"/>

        <StackPanel Orientation="Horizontal">

            <Button Height="75" Width="20"/>

            <Button Height="75" Width="20"/>

           <Button Height="75" Width="20"/>

           <Button Height="75" Width="20"/>

           <Button Height="75" Width="20"/>

            <Button Height="75" Width="20"/>

            <Button Height="75" Width="20"/>

            <Button Height="75" Width="20"/>

            <Button Height="75" Width="20"/>

        </StackPanel>

    </StackPanel>

 

Wrap Panel
The Wrap Panel is similar to a flow layout, it basically places items horizontally and then wraps the object to next line if the window is not big enough, and this tries to make the most of the real estate by providing a dynamic layout:

Wrap Panel 

    <WrapPanel>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

        <Button Width="75" Height="75"/>

    </WrapPanel>

 

Dock Panel
The Dock Panel is a very useful panel that creates a framed layout where you can specify if items belong on the left, right, top, bottom and centre. The order in which you specify the items depends one which ones get the more real estate as shown by the example below:

 

    <StackPanel>

        <TextBlock Text="A DockPanel when the Left and Right are set first" />

        <DockPanel Height="100">

            <Button DockPanel.Dock="Left">Left</Button>

            <Button DockPanel.Dock="Right">Right</Button>

            <Button DockPanel.Dock="Bottom">Bottom</Button>

            <Button DockPanel.Dock="Top">Top</Button>

            <Button>Middle</Button>

        </DockPanel>

        <TextBlock Text="A DockPanel with the Top and Bottom are set first"/>

        <DockPanel Height="100">

            <Button DockPanel.Dock="Bottom">Bottom</Button>

            <Button DockPanel.Dock="Top">Top</Button>

            <Button DockPanel.Dock="Left">Left</Button>

            <Button DockPanel.Dock="Right">Right</Button>

            <Button>Middle</Button>

        </DockPanel>

    </StackPanel>

 

Grid
The Grid layout lets you place objects by just setting their properties of Grid.Row and Grid.Column. It also allows you to set the height of the rows and the width of the columns either by pixels , percentage and absolute. The grid is also very flexible when it comes to placing UI elements; you are able to allow the element to take up more than one cell by setting the spanning property of the Grid.

 

    <Grid ShowGridLines="True">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="50" />

            <ColumnDefinition Width="100"/>

            <ColumnDefinition Width="*" />

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>

            <RowDefinition Height="25" />

            <RowDefinition Height="175" />

            <RowDefinition Height="*" />

        </Grid.RowDefinitions>

       

        <Button Grid.Column="0" Grid.Row="0">1</Button>

        <Button Grid.Column="1" Grid.Row="0">2</Button>

        <Button Grid.Column="2" Grid.Row="0">3</Button>

        <Button Grid.Column="0" Grid.Row="1" Grid.RowSpan="2">4</Button>

        <Button Grid.Column="1" Grid.Row="1">5</Button>

        <Button Grid.Column="2" Grid.Row="1">6</Button>

        <Button Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2">8</Button>

    </Grid>

 

Uniform Grid
The Uniform grid is the same as a normal grid however the size of the row and column are the same so that each cell is always the same size. Rather than explicitly stating the row and column the items are displayed in order.

 

    <UniformGrid Rows="5" Columns="3">

        <Button>1</Button>

        <Button>2</Button>

        <Button>3</Button>

        <Button>4</Button>

        <Button>5</Button>

        <Button>6</Button>

        <Button>7</Button>

        <Button>8</Button>

        <Button>9</Button>

        <Button>10</Button>

        <Button>11</Button>

        <Button>12</Button>

        <Button>13</Button>

        <Button>14</Button>

        <Button>15</Button>

    </UniformGrid>

 

Canvas
A Canvas layout is where the UI Elements that you want to put on screen have to be given the properties Canvas.Left and Canvas.Top, this means that you essentially can put objects on top of each other and by the ordering of the XAML depends on what is on top, the last Element of the XAML code is the one that sits on top. Every item needs to be explicitly stated its postion.

Canvas   

<Canvas>

        <Button Canvas.Top="50" Canvas.Left="20" Height="50" Width="50">1</Button>

        <Button Canvas.Top="50" Canvas.Left="80" Width="50" Height="50">2</Button>

        <Button Canvas.Top="80" Canvas.Left="50" Height="50" Width="50">3</Button>

        <Button Canvas.Top="50" Canvas.Left="50" Height="50" Width="50">4</Button>

        <Button Canvas.Top="20" Canvas.Left="50" Height="50" Width="50">5</Button>

    </Canvas>

Page view tracker