Developing a Robust Data Driven UI Using WPF - Stock DataModel Sample

Posted in  |  | .  

On the previous post in this series we looked into the DataModel component in our architecture in detail and defined  an abstract DataModel base class to derive our models from.

On this post we'll implement a concrete data model to represent a stock's value. Why stock? It's an object with a changing value that requires our DataModel constantly refresh and keep its data "alive", and it's simple to implement which makes it a perfect example for our first DataModel.

The first thing we'll do when defining our Stock DataModel is abstract the data source. This way we can easily implement several data sources for fetching a stock's data and instantiate the DataModel with the right one (for example, read from Yahoo at runtime, read from fake data source during unit testing):

/// <summary>
/// Defines the interface allowing <see cref="StockDataModel"/> to read quotes from various providers.
/// </summary>
public interface IStockDataProvider
{
    /// <summary>
    /// Gets a given stock symbol's (given by <paramref name="symbol"/>) data.
    /// </summary>
    /// <param name="symbol">The stock's symbol.</param>
    /// <param name="name">The stock's company name.</param>
    /// <param name="quote">The last stock's quote.</param>
    /// <param name="change">The stock's change value.</param>
    /// <param name="open">The stock's open value.</param>
    /// <returns><b>True</b> if data was retrieved successfully; otherwise, <b>False</b>.</returns>
    bool TryGetData(string symbol, out string name, out double quote, out double change, out double open);
}

Now that we have our data source defined we can implement different stock data providers for our DataModel to consume.
Now, lets go over the StockDataModel class:

public class StockDataModel : DataModel
{
    private string _symbol;
    private IStockDataProvider _quoteProvider;

    public StockDataModel(string symbol, IStockDataProvider provider)
    {
        _symbol = symbol;
        _quoteProvider = provider;

        this.State = DataModelState.Fetching;

        // Queue a work item to fetch the symbol's data
        if (!ThreadPool.QueueUserWorkItem(new WaitCallback(FetchDataCallback)))
        {
            this.State = DataModelState.Invalid;
        }
    }

    public string Symbol
    {
        get { return _symbol; }
    }

Our StockDataModel constructor takes the stock symbol that the model represents and an IStockDataProvider to fetch the stock's data from.
We set the initial DataModel state to Fetching and queue a work item for a background thread to update our model with the stock's data - company name, quote, change value and open value. If we fail to queue the work item than we put the model in an invalid state.

Next, we need to define the properties exposed by StockDataModel for data binding.

public string Name
{
    get 
    {
        VerifyCalledOnUIThread();
        return _name; 
    }
    private set
    {
        VerifyCalledOnUIThread();
        if (_name != value)
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}
public double Quote
{
    get
    {
        VerifyCalledOnUIThread();
        return _quote;
    }
    private set
    {
        VerifyCalledOnUIThread();
        if (_quote != value)
        {
            _quote = value;
            OnPropertyChanged("Quote");
        }
    }
}
...

We're sign a private setter to update the property values and trigger a PropertyChanged event if required.
You can also add calculated properties. For example:

        public double ChangePercent
        {
            get
            {
                if (double.IsNaN(Change)) return double.NaN;
                if (double.IsNaN(Open)) return double.NaN;

                try
                {
                    double change = (Change / Open) * 100;
                    return change;
                }
                catch
                {
                    return double.NaN;
                }
            }
        }

In this case, it is important to remember to trigger the property change event for ChangePercent too when the values it depends on change...

Now for the implementation of the FetchDataCallback. This method will be called by a background thread to update the stock data.
Since this method is called by a background thread we're free to perform expensive operations, such as calling a web service to fetch the stock's data from an online provider (like Yahoo).

private void FetchDataCallback(object state)
{
    string fetchedName;
    double fetchedQuote;
    double fetchedChange;
    double fetchedOpen;
    if (_quoteProvider.TryGetData(_symbol, out fetchedName, out fetchedQuote, out fetchedChange, out fetchedOpen))
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
            new ThreadStart(delegate
            {
                this.Name = fetchedName;
                this.Quote = fetchedQuote;
                this.Change = fetchedChange;
                this.Open = fetchedOpen;
                this.State = DataModelState.Active;
            }));
    }
    else
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
            new ThreadStart(delegate { this.State = DataModelState.Invalid; }));
    }
}

On the previous post, on the WPF threading model overview we noted the following:

If only the creator of a DispatcherObject can access it, how can a background thread interact with the user?
The background thread does not access the UI directly but it can ask the UI thread to perform a task on its behalf by registering work items to its
Dispatcher using it's Invoke (for a synchronous call that returns when the UI thread finished executing the delegate) or BeginInvoke methods (which runs asynchronously)

In the above code, after fetching the data on the _quoteProvider.TryGetData we need to communicate these changes back to the UI thread.
We use the Dispatcher to set the new values for the DataModel properties which ensures that our property change events will be triggered on the UI thread.

Keeping the Data Alive

So far, our code only fetches the stock data once. Lets see what it takes make out DataModel keep its data alive.

protected override void OnEnabled()
{
    _timer = new DispatcherTimer(DispatcherPriority.Background);
    _timer.Interval = TimeSpan.FromMinutes(5);
    _timer.Tick += delegate { ScheduleUpdate(); };
    _timer.Start();

    ScheduleUpdate();
}
protected override void OnDisabled()
{
    _timer.Stop();
    _timer = null;
}

private void ScheduleUpdate()
{
    VerifyCalledOnUIThread();

    // Queue a work item to fetch the quote
    if (ThreadPool.QueueUserWorkItem(new WaitCallback(FetchDataCallback)))
    {
        this.State = DataModelState.Fetching;
    }
}

The above code defines a timer that is active when the DataModel is Enabled. The timer calls ScheduleUpdate every 5 minutes to perform the same data update using a background thread logic we performed on our constructor.

We're using a DispatcherTimer so that the calls to ScheduleUpdate will be made using the Dispatcher's thread (the UI thread) so that we can update the DataModel's state without a hassle. If we had used System.Threading.Timer then ScheduleUpdate would be called on the timer's thread requiring the use of Dispatcher.BeginInvoke to update the state...

That's it...

We've got the basic DataModel implemented. You can using it in you're XAML window to see it working...

To get a basic XAML running you'll need to define a content control:

<ContentControl x:Name="_content" />

And set its content to a StockDataModel instance on your codebehind:

_content.Content = new StockDataModel("AAPL", someProvider);

Then all you need to do is define a data template for the StockDataModel type to control it's appearance. Here's a simple template for example:

        <DataTemplate x:Name="StockTemplate" DataType="{x:Type local:StockDataModel}">
            <StackPanel Orientation="Horizontal" mdb:EnableModel.DataModel="{Binding}" Height="30px" Width="Auto" ClipToBounds="True">
                <TextBlock Text="{Binding Name}" Foreground="#737271" Width="120" Padding="3,0,0,3" Style="{StaticResource StockText}" />    
                <TextBlock Text="{Binding Quote}" Foreground="#737271" Width="55" Padding="0,0,0,3" Style="{StaticResource StockText}" />
            </StackPanel>
        </DataTemplate>

You can find the code discussed in this article plus my own implementation for an IStockDataProvider that reads stock data from Yahoo here:

On the next post we'll discuss DataModel unit testing and see how the StockDataModel tests are implemented.

kick it on DotNetKicks.com


Developing a Robust Data Driven UI Using WPF - The DataModel

Posted in  |  | .  

imageIn the first post in the series I gave an overview of the pattern we'll be using.
This post will go deeper into the DataModel, as defined in the previous post:

The DataModel is defined exactly as the Model in MVC; it is the data or business logic that stores the state and does processing of the problem domain.
The DataModel abstracts expensive operations such as data fetching without blocking the UI thread. It can keep data "alive" fetching it periodically from source (example: stock ticket), merge information from several sources etc.
The DataModel is completely UI independent and pretty much straightforward to unit test.

The DataModel exposes data in a way that makes it easily consumable by WPF. As such, all if its public APIs, called by WPF for data-biding, must be called on the UI thread only. It must not block the UI thread because we want a robust functional UI so it usually performs operations on a background thread using the Dispatcher to send results back to the UI thread.

Therefore, the simplest DataModel implementation exposes several public Properties that expose data, implements INotifyPropertyChanged and/or INotifyCollectionChanged, and it abstracts the way information is fetched (using background threads to avoid blocking the UI thread when fetching the data is an expensive operation).

For two-way binding a commit and rollback mechanism, a dirty flag, etc.  We'll get to that later on...

As the DataModel implementation needs to abstract expensive data fetching operations and work with multiple threads we need some basic understanding of WPF's threading model before we look at the DataModel implementation...

WPF Threading Model - A Quick Overview

A typical WPF uses two threads:

  • Rendering thread - runs in the background and handles rendering
  • UI thread - Receive inputs, handles events, paints the screen and runs application code.

The UI thread queues work items in a Dispatcher object. The Dispatcher object selects work items on a priority basis and runs each one to completion.
Every UI thread must have at least one Dispatcher, and each Dispatcher can only use one thread to execute work items.

Therefore, in order to build responsive UI that doesn't block the UI thread, the application has to maximize the Dispatcher's throughput by keeping work items small as to minimize the time the Dispatcher spends on processing them - which keeps other work items waiting causing the UI to lag.

In order to perform expensive operations without blocking the UI thread we can use a separate thread that will run in the background, leaving the UI thread free to process items in the Dispatcher queue. When the background thread is done processing it can report results back to the UI thread for display.
Doing this isn't trivial as Windows only allows UI elements to be accessed by the thread that created them. This means that the background thread we used for some long-running task cannot access and update our UI when it is finished (or during work to show progress) - a background thread updating a control (such as a list box) during its rendering can cause strange UI behaviors that this limitation is there to prevent.

WPF uses the following design to enforce this kind of coordination between the UI thread and other threads:
Most of the classes in WPF derive from DispatcherObject. During construction, a DispatcherObject stores a reference to the Dispatcher linked with the current running thread - creating an association between itself and the thread that created it.
At the beginning of every method in the DispatcherObject, it calls VerifyAccess which compares the Dispatcher associated with the current thread with the Dispatcher stored during the object's construction - if they do not match it throws an exception.

If only the creator of a DispatcherObject can access it, how can a background thread interact with the user?
The background thread does not access the UI directly but it can ask the UI thread to perform a task on its behalf by registering work items to its Dispatcher using it's Invoke (for a synchronous call that returns when the UI thread finished executing the delegate) or BeginInvoke methods (which runs asynchronously)

The DataModel Class

So now, after the brief discussion on the use of the Dispatcher we can start coding our base DataModel class.
We'll start with the simple class and constructor definition:

public abstract class DataModel : DispatcherObject, INotifyPropertyChanged
{
    public DataModel()
    {
    }


We're deriving from DispatcherObject because we need to have the Dispatcher available so that we can run background jobs that dispatch results to the UI thread.

As discussed earlier, each call to the DataModel should be made on the UI thread. Therefore we would like to enforce that limitation at the beginning of each publicly exposed API. The DispatcherObject class that we derived from contains a VerifyAccess() method that does just that. The method is public but unfortunately marked with the [EditorBrowsable(EditorBrowsableState.Never)] attributes which will make it hard to find for developers using driving their data model from our class.

To resolve this I simply defined a protected method as follows:

/// <summary>
/// Makes sure the call is in the correct thread (the UI thread) by comparing the current dispatcher
/// object with the dispatcher we got when the DataModel was created.
/// </summary>
[System.Diagnostics.Conditional("Debug")]
protected void VerifyCalledOnUIThread()
{
    this.VerifyAccess();
}

This method will be visible to anyone deriving from our class and it simply calls VerifyAccess to make sure code is made from the UI thread.
The Conditional attribute makes this code execute only in debug bits avoiding this kind of assertion on retail bits - some performance gain.

In order to support asynchronous data fetching the DataModel should encapsulate the information about its state - valid (data fetched), invalid (error fetching data), fetching (processing).

public enum DataModelState
{
    /// <summary>
    /// The model is fetching data
    /// </summary>
    Fetching,
    /// <summary>
    /// The model is in an invalid state
    /// </summary>
    Invalid,
    /// <summary>
    /// The model has fetched its data
    /// </summary>
    Active
}

The data model's state is exposed using a property:

public DataModelState State
{
    get
    {
        VerifyCalledOnUIThread();
        return _state;
    }
    set
    {
        VerifyCalledOnUIThread();
        if (value != _state)
        {
            _state = value;
            OnPropertyChanged("State");
        }
    }
}

We also implement INotifyPropertyChanged to allow the model to communicate changes in its values.
Since adding\removing event handlers to the PropertyChanged event is a public API exposed by the DataModel, it also requires verification that calls to it are made from the UI thread. We'll define our own add\remove handlers in order to perform this verification:

protected virtual void OnPropertyChanged(string propertyName)
{
    VerifyCalledOnUIThread();

    if (_propertyChangedEvent != null)
    {
        _propertyChangedEvent(this, new PropertyChangedEventArgs(propertyName));
    }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged
{
    add
    {
        VerifyCalledOnUIThread();
        _propertyChangedEvent += value;
    }
    remove
    {
        VerifyCalledOnUIThread();
        _propertyChangedEvent -= value;
    }
}
#endregion

Any property that we'll add to our data model will call OnPropertyChanged on its setter in order to notify it has changed.

It's Alive!

One more ability we'd like to add to our DataModel class is the ability to enable\disable it.
As defined earlier, the DataModel encapsulates the logic of fetching data and keeping it "alive" and up to date. To do that, it'll need to keep some internal timer for updating information or register to some change notification event on its source.
This will keep the DataModel alive and can result in memory leaks, which is why we need some way to turn the DataModel on and off, allowing it to unregister from its data sources when that connection is no longer required:

public bool Enabled
{
    get
    {
        VerifyCalledOnUIThread();
        return _isEnabled;
    }
    set
    {
        VerifyCalledOnUIThread();
        if (value != _isEnabled)
        {
            _isEnabled = value;
            OnPropertyChanged("Enabled");
        }
    }
}
public void Enable()
{
    VerifyCalledOnUIThread();

    if (!_isEnabled)
    {
        this.Enabled = true;
        OnEnabled();
    }
}

public void Disable()
{
    VerifyCalledOnUIThread();

    if (_isEnabled)
    {
        this.Enabled = false;
        OnDisabled();
    }
}
protected virtual void OnEnabled()
{
}
protected virtual void OnDisabled()
{
}

When binding UI elements to the DataModel we'll need some mechanism to enable the DataModel when the element is loaded and disable it when the element is unloaded. There's an elegant way to implement this behavior which we'll implement in a future post.

That's it! We've got a basic class to derive out data models from. Note that we're only addressing one-way data binding for the moment. We'll address a two-way data model (which requires the ability to commit\rollback data etc.) in future post.

On the next post we'll look into a concrete DataModel implementation for our Stocky application.

You can download the code for this post from here:

 

Further Reading

kick it on DotNetKicks.com


Developing a Robust Data Driven UI Using WPF - Introduction

Posted in  |  |  | .  

WPF, Microsoft's not-so-new-anymore UI technology offers new capabilities allowing both developers and designers to work together to achieve a stunning experience for their applications.

Power, however, does not come without complexity, and WPF does not provide a framework or a model to solve many of the problems faced by developers and designer when building an application:

1. Handling Rich Data Forms. Many applications, especially when it comes to enterprise applications, rely heavily on displaying and manipulating data. Fetching the data while keeping the UI alive and responsive is a complicated task that's also hard to debug and requires an experienced developer doing the work.
Can we come up with a framework that will simplify data fetching?

2. Testability is a Requirement for Software Development Framework. Development organizations are no longer satisfied with simple reduction of costs for initial development and there's a growing demand for frameworks and tool to facilitate a sustainable and agile development process.
Can we come up with a model that will allow writing tests for the application's UI and behavior?

3. Metadata Driven User-Interface. WPF provides XAML as a meta-model for UI definitions. However there is no clear separation between metadata and code which is a mess when it comes to designer and developers working together.
Can we come up with a model to allow developers provide all the UI logic as closed building blocks that designer can just use in a plug-and-play manner?

Providing a Framework for Building Robust, Data-Driven UIs

The Model\View\Controller (MVC) architectural pattern has long been used by complex applications to present large amount of data to the user.
The pattern allows developers to separate the actual data (Model) from the user interface (View) and the business logic manipulating the data (Controller).

In the following set of articles I will present a variation of the MVC pattern tailored for modern UI development (in WPF) where we'd like the View to be the responsibility of a designer rather than a classic developer writing code.

I'll be using the DataModel\ViewModel\View terminology to describe the pattern (although you may find the same pattern described using various other terminologies when browsing the net).

Introducing the DataModel\ViewModel\View Pattern

As mentioned earlier, the DataModel\ViewModel\View pattern is a variation of the MVC pattern. Its focus is on making the View, which is the actual UI presented to the user, the responsibility of a designer - a person who is generally more oriented towards graphics, art and interaction than to classic coding.

The design of the view should be done in a declarative form (XAML) using a WYSIWYG tool (Expression Blend).
In short, the actual UI is developed using different tools and languages by a person with a different skills set than business logic and data backend.

In order to understand the meaning behind the DataModel\ViewModel\View terminology lets look at the following diagram describing
typical architecture for our application's presentation using this pattern:

image

The DataModel

The DataModel is defined exactly as the Model in MVC; it is the data or business logic that stores the state and does processing of the problem domain.
The DataModel abstracts expensive operations such as data fetching without blocking the UI thread. It can keep data "alive" fetching it periodically from source (example: stock ticket), merge information from several sources etc.
The DataModel is completely UI independent and pretty much straightforward to unit test.

The View

The View consists of visual elements and represents the actual user interface presented to the users (buttons, windows, graphics, etc.). It also defines interaction for keyboard shortcuts and other input devices .

The View is defined declaratively in XAML by the designer (usually using a tool such as Expression Blend).
Using such a declarative model makes it to harder to represent some state that the original  View from the MVC pattern was meant to deal with - this includes dealing with multiple modes of interaction (such as "view mode" and "edit mode") that change the visuals and behavior of the controls.

This is where we make use of WPF's advanced data binding mechanism. In a simple scenario we can simply bind the View to the DataModel and use binding expressions to perform one-way binding for display only values or two-way binding to allow editing values in the DataModel.

In most scenarios, however, only a small subset of the application's UI can be bounded directly to the DataModel. This can be the case when the DataModel is a pre-existing class or data schema over which the application developer has no control. The values exposed by the DataModel are likely to require some processing in order to allow binding to UI elements. There may also be several complex operations that require code implementation and do not fit into the strict declarative-only definition for a View but are too application specific to be part of the DataModel (which we might not have control over).
We may also want to save some view state such as view mode (view\edit\etc.) or item selection etc.

To bridge this gap between the declarative View and the DataModel we define the ViewModel...

The ViewModel

The ViewModel bridges between the DataModel and the View and performs all the tasks mentioned in the previous paragraph.
The terms is meant to describe a "Model of a View" which basically means that the ViewModel  abstracts all the behavior logic behind a specific screen (View) in the application.
The ViewModel include converters that can transform DataModel types into View types, Commands that can be executed the the View's control and interact with the DataModel and general behaviors that can be attached to UI elements in the View.

Summary and Next Steps

stockyscreen

The DataModel\ViewModel\View defines a simple yet powerful pattern allowing developers and designers to collaborate on building a robust, data-driver WPF UIs.

It allows separating the data layer from the view layer and the UI to support easier development of granular components that are also unit-testable.

To demonstrate how the various pattern components are developed and used we'll be going over the development process of a stock ticker widget-like application dubbed Stocky (screenshot on the right) and see how this development pattern simplifies the creation of an otherwise quite complicated little application.

 

 

 

 

 

 

 

References:

kick it on DotNetKicks.com


Managed Quake 3 Arena

Posted in  |  | .  

Now that's pretty cool...  A .NET port of the Quake 3 Arena source code.

ManagedQuake3Screenshot


HEROES Happen {here}

Posted in  |  |  | .  

A new site dedicated to the launch events of Windows 2008, Visual Studio 2008 and SQL Server 2008
has been unveiled at http://www.heroeshappenhere.com/

Currently it contains some videos of Microsoft professional sharing their feelings about the launch but it'll soon contain some more information regarding the event:

Coming soon this site will provide you the portal for all launch information, event registration, learning resources and new and fun way where you can highlight how technology has made you a Hero. You will be able to experience launch in a whole new way from interactive community tools and forums, new demonstrations and online training options, and even a never before seen surprise from Microsoft which will enable you to experience launch in a new and exciting way. Heroes Happen Here, and make sure you don't miss out.

I guess I'll have to stay tuned then...


Introduction to LINQ

Posted in .  

I'm doing a 1 hour Introduction to LINQ session at SAP tomorrow.
Below is a link to the presentations and I'd be happy to hear comments about it if anyone has any...

IntroToLINQ


kick it on DotNetKicks.com

What's wrong with this code? #2

Posted in  |  | .  

Check out the following code snippet:

        static decimal Division(int a, int b)
        {
            return a / b;
        }

kick it on DotNetKicks.com

What's wrong with this code? #1 - Discussion

Posted in  |  | .  

The Singleton implementation in the snippet I gave works fine as a lazy, thread-safe Singleton as it ensures only one thread can create the instance.
However, there's a big performance hit caused by the fact that we acquire a lock each time the Singleton's instance is requested.

Yoav, suggested to fix this performance problem by checking for null twice - outside the lock and inside the lock:

        public static Singleton Instance
        {
            get
            {
                if (Singleton._insatnce == null)
                {
                    lock (_syncRoot)
                    {
                        if (Singleton._insatnce == null)
                        {
                            Singleton._insatnce = new Singleton();
                        }
                    }
                }
                return Singleton._insatnce;
            }
        }

This code, known as "Double-Check Locking" doesn't work in the presence of either an optimizing compiler or  shared memory multiprocessor.
The main reason for this (as explained by Brad) is that the CLR's memory model allows non-volatile read\writes to be reordered as long as that change cannot be noticed from the point of view of a single thread.
This means that the compiler can reorder write to _instance during initialization and its construction write, causing another thread to see _instance as set even though it wasn't initialized yet (appears on stress testing).

To prevent such optimizations we can declare _instance to be volatile or by explicitly specifying a memory barrier before accessing the data member using System.Threading.Thread.MemoryBarrier(). Using Thread.MemoryBarrier() is more efficient than volatile as it allows compiler optimization when barrier is not required:

        public static Singleton Instance
        {
            get
            {
                if (Singleton._insatnce == null)
                {
                    lock (_syncRoot)
                    {
                        if (Singleton._insatnce == null)
                        {
                            Singleton newInstance = new Singleton();
                            // Ensure all writes used to construct new value have been flushed.
                            System.Threading.Thread.MemoryBarrier();
                            Singleton._insatnce = newInstance;         // publish the new value
                        }
                    }
                }
                return Singleton._insatnce;
            }
        }

 Another way of doing the same thing is using System.Threading.Interlocked.CompareExchange() which also enforces a memory barrier.

Omer, suggested creating the instance of Singleton in the static constructor (which is guaranteed to be thread-safe) rather than in the Instance accessor.
While in this implementation you lose some of the flexibility of controlling exactly at which point in time the Singleton instance is created, this kind of control is not really required in most cases and giving up on it allows making the code shorter and less confusing...

kick it on DotNetKicks.com

What's wrong with this code? #1

Posted in  |  | .  

I decided to start a new column gathering all sorts of "what's wrong with this code?" snippets.
Why?

  1. Its fun.
  2. Its good for interview questions.
  3. It starts discussions. More interesting than just talking (or writing) to myself.

So, here's what I plan:

  1. I post a code snippet (most probably C# but I'm not setting constraints on myself)
  2. You comment on what's wrong with the code on the snippet
  3. I post my answer, interesting comments, etc. (you can comment on my answer too :-))

* Note that these posts are syndicated on blogs.microsoft.co.il (and maybe some other places) so please leave your comments at the main blog - www.ekampf.com/blog/

** I know there are many "What's wrong with this code?" out there already. I'll try not to recycle (too much ;))

When looking at these snippets note the following "Bad Code" classifications: Confusing code, Overly complex code, Performance Issues, Buggy.

So, to start with an easy one (I think), check out the following Singleton implementation:

    public sealed class Singleton
    {
        private Singleton() { }

        private static Singleton _insatnce;
        private static object _syncRoot = new Object();

        public static Singleton Instance
        {
            get
            {
                lock (_syncRoot)
                {
                    if (Singleton._insatnce == null)
                    {
                        Singleton._insatnce = new Singleton();
                    }

                    return Singleton._insatnce;
                }
            }
        }
    } 

Update July 16th, 2007:
I've posted the answer and a summary on the comments at the following post.

kick it on DotNetKicks.com

WPF Overview

Posted in  |  |  | .  

Acropolis uses XAML to define business logic components

Posted in  |  | .  
A lot of developers are mistaking XAML to be an exclusively WPF technology. The truth is, that as it's name (Extensible Application Markup Language) suggests, it can be used to represent all kinds of application mechanisms, not just the UI.
David Hill has written a post with a brief explanation as to why Acropolis uses XAML instead of code to represent its business logic component. Check the "Why XAML?" section under this post.

Using a declarative approach like this, though, provides a number of benefits:

  • Using XAML gives you a very concise way to express the structural aspects of your component - not just the external ‘class interface', but how it is structured internally. For example, it allows you to cleanly define how any child components or services that your component uses are configured or interact with each other.
  • It allows you to concentrate more on the code that defines the actual implementation of your component. In other words, we want to make it so that 99%+ of the code that you do write is the actual code that will solve your business problem and not plumbing or glue code.
  • It is much easier for us (or you) to build visual designers or other tools (including test tools) for your component since its structure is more easily ‘machine-parsable'. It also allows for a looser coupling between the application model and the tools allowing each of them to evolve more quickly.

Since there is very little documentation I could find on the subject, I wonder how complicated is to create my own application markup and a designer for Visual Studio...
Anyone has any good pointers on this?


Build an Outlook 2007 UI Clone using WPF

Posted in  |  |  |  | .  
Two engineers from Microsoft Switzerland, Ronnie Saurenmann and Ruihua Jin, have put together this 90-page hands-on lab that takes you through the process of building a business application that has the same UI as Outlook 2007 using Expression Blend.
You can check out the xbap, read the hands-on-lab manual, or look at the source.

More details on this here:


Getting the Full Name of the Current User

Posted in  | .  

One of the developers in our team recently encountered a problem of getting the display name of the current user.
The .NET framework exposes the user name through Environment.UserName or System.Security.Principal.WindowsIdentity.GetCurrent().Name but there's no API to get the user's display name.
The simplest implementation to get the display name would be using DirectoryServices:

        public static string GetUserFullName(string domain, string userName)
        {
            DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
            return (string)userEntry.Properties["fullname"].Value;
        }

The above method can be called with the current user name and domain to get the user's fullname:

GetUserFullName(Environment.UserDomainName, Environment.UserName)

This method will fail to provide a correct result of the fullname property is not configured in ActiveDirectory.
Windows provide an unmanaged API called GetUserNameEx that can be called using interop:

    /// <summary>
    /// Wraps the GetUserNameEx API in secur32.dll
    /// </summary>
    /// <see>
    /// http://msdn2.microsoft.com/en-us/library/ms724435.aspx
    /// </see>
    public static class GetUserNameExUtil
    {
        #region Interop Definitions
        public enum EXTENDED_NAME_FORMAT 
        {
            NameUnknown = 0,
            NameFullyQualifiedDN = 1,
            NameSamCompatible = 2,
            NameDisplay = 3,
            NameUniqueId = 6,
            NameCanonical = 7,
            NameUserPrincipal = 8,
            NameCanonicalEx = 9,
            NameServicePrincipal = 10,
            NameDnsDomain = 12,
        }
        [System.Runtime.InteropServices.DllImport("secur32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize);
        #endregion

        public static string GetUserName(EXTENDED_NAME_FORMAT nameFormat)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return null;
            }

            StringBuilder userName = new StringBuilder(1024);
            int userNameSize = userName.Capacity;
            if (GetUserNameEx((int)nameFormat, userName, ref userNameSize) != 0)
            {
                string[] nameParts = userName.ToString().Split('\\');
                return nameParts[0];
            }

            return null;
        }
        public static string GetUserFullName()
        {
            return GetUserName(EXTENDED_NAME_FORMAT.NameDisplay);
        }
    }

Just call GetUserNameExUtil.GetUserDisplayName() to get the user's display name...


Acropolis News

Posted in  |  |  | .  

It seems there's a lot of new stuff about Acropolis from TechEd:

Acropolis sounds like a very promising new technology for smart-clients (unlike CAB which I hated).
I'll try to drill more into this new framework in the near future...


A C# 3.0 Ray Tracer

Posted in  | .  

C# PM Luke Hoban has posted a simple C# Ray Tracer code that utilizes the new C# 3.0 language capabilities.

On the same note, you can also check Scott Guthrie's posts about the new C# 3.0 language features:

  • Automatic Properties, Object Initializer and Collection Initializers
  • Extension Methods
  • Lambda Expressions

     


    Technorati Tags: , ,

  • Managed Library for Nintendo's Wiimote

    Posted in  |  | .  
    Want to develop your own Wiimote enabled demo?
    Here's the library you need - http://msdn.microsoft.com/coding4fun/hardware/article.aspx?articleid=1879033