Saturday, June 27, 2009

WPF patterns : MVC, MVP or MVVM or…?

Introduction
Since XAML things have become a bit complicated in trying to conceptualize MVC architectures for Windows applications. The gap between web and win is narrowing and the whole WPF thing adds diverse possibilities to one’s toobox. What to use? Model-view-controler, the model-view-presenter or the new paradigm called model-view-viewmodel?
I have tried to understand what it’s all about and this is what I found out.
What’s the problem?
WPF has changed a few things:
through declarative programming (i.e. XAML) a lot of plumbing is created for you which especially in the context of databinding saves a lot of code. Another area is e.g. animations and styling; what previously had to be programmed in C# is now possible inside XAML through triggers or events.
in the MVC pattern the View is presenting the data from the Model but now XAML does this job and sometimes need things like value converters or the ObservableCollection to update the presentation
user controls in WPF allow you to define a default generic.xaml style which can be overriden when used inside an application, i.e. styling of existing controls is a new feature which adds flexibility to the presentation of the Model
XAML allows a wide variety of mechanisms to change things or to react to user actions; through the ICommand that is now defined in the framework, through triggers in XAML, through animations, through event bubbling or tunneling (which is also new)
The MVVM architecture
Overview








DataModel
DataModel is responsible for exposing data in a way that is easily consumable by WPF. All of its public APIs must be called on the UI thread only. It must implement INotifyPropertyChanged and/or INotifyCollectionChanged as appropriate. When data is expensive to fetch, it abstracts away the expensive operations, never blocking the UI thread (that is evil!). It also keeps the data “live” and can be used to combine data from multiple sources. These sorts of classes are fairly straightforward to unit test.

ViewModel
A ViewModel is a model for a view in the application (duh!). It exposes data relevant to the view and exposes the behaviors for the views, usually with Commands. The model is fairly specific to a view in the application, but does not subclass from any WPF classes or make assumptions about the UI that will be bound to it. Since they are separate from the actual UI, these classes are also relatively straightforward to unit test.
View
A View is the actual UI behind a view in the application. The pattern we use is to set the DataContext of a view to its ViewModel. This makes it easy to get to the ViewModel through binding. It also matches the DataTemplate/Data pattern of WPF. Ideally, the view can be implemented purely as Xaml with no code behind. The attached property trick comes in very handy for this.

The lines between DataModels and ViewModels can be blurry. DataModels are often shown in the UI with some DataTemplate, which isn’t really so different than the way we use ViewModels. However, the distinction usually makes sense in practice. I also want to point out that there’s often composition at many layers. ViewModels may compose other ViewModels and DataModels. And, DataModels may be composed of other DataModels.
The ViewModel is a model of the view. That means: You want to DataBind a property fromyour DataObject (model) to a property from your ViewObject (view) but you sometimes cannot bind directly to a CLR property of the model (because of converting or calculating). This is when ViewModel comes into play. It propagates the already calculated or converted value from your model, so you can bind this property directly to the view property.
The main thrust of the Model/View/ViewModel architecture seems to be that on top of the data (”the Model”), there’s another layer of non-visual components (”the ViewModel”) that map the concepts of the data more closely to the concepts of the view of the data (”the View”). It’s the ViewModel that the View binds to, not the Model directly.

The model
Using the INotifyPropertyChanged you can bubble changes up the stack. The reason that public methods should be on the UI thread is because the model could call long running or async stuff which would block the UI, though there are methods to let the UI thread handle property changes from a separate thread. See the doc on the Dispatcher object and the WPF threading model for more on this. Note in this context that you can let things happen in the background by means of the BeginInvoke()method of the Dispatcher and the paramter that specifies the priority. The SystemIdle in particular is interesting to be used when the Dispatcher is not busy.
The DataModel you can find in the download is mimiced from the Dan Crevier’s sample and can serve as an abstract base class for your own models.

Dispatcher things
The DispatcherTimer is reevaluated at the top of every Dispatcher loop.
Timers are not guaranteed to execute exactly when the time interval occurs, but are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. For an example of using a System.Timers.Timer, see the Disable Command Source Via System Timer sample. Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

A DispatcherTimer will keep an object alive whenever the object’s methods are bound to the timer. So, the right way to schedule things inside the WPF UI is something like;
[csharp]
private DispatcherTimer _timer;timer = new DispatcherTimer(DispatcherPriority.Background);timer.Interval = TimeSpan.FromMinutes(5);
timer.Tick += delegate { ScheduleUpdate(); };timer.Start();
[/csharp]
the timer is injected implicitly in the thread associated to the dispatcher of the UI.

Thursday, June 18, 2009

Concordance implementation in C#3.0

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Concordance
{
class Program
{
/// Method Name: Main
/// Description:
/// This method is the main method to perform the Concordance .
/// Limitations of the Program:As of now this program is tested to identify
/// that it cannot recognize ACRONYMS like i.e. etc
///
static void Main(string[] args)
{
string strString =
"Given an arbitrary text document written in English, write a program that will generate a concordance, i.e. an alphabetical list of all word occurrences, labeled with word frequencies. Bonus: label each word with the sentence numbers in which each occurrence appeared.";
// Get the list of all words from the input text.
string[] inputTextArray =
strString.ToLower().Split(
new char[] {'.', '?', '!', ' ', ';', ':', ','},
StringSplitOptions.RemoveEmptyEntries);
// Group each word based on the occurecnces
var groupItems = from word in inputTextArray
orderby word
group word by word into wordValueandCountPair
select new { Key = wordValueandCountPair.Key, Count = wordValueandCountPair.Count() };
char[] atozCharArray =
Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
int indexCount = 0;
int iteration = 0;
string indexString = string.Empty;
// Print each word in the desired output format.
foreach (var item in groupItems)
{
// Get the number of sentences.
string[] SentenceArray =
Regex.Split(strString.ToLower(), @"(?<=['""a-z0-9][\.\!\?])\s+(?=[a-z])");
string paraIndexString = string.Empty;
// Loop through each sentence and find the occurence of the each word
// in that sentence to identify the senetence number.
for (int index = 0; index < SentenceArray.Length; index++)
{
var paraItems =
from paraItem in SentenceArray[index].Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries)
where paraItem == item.Key
group paraItem by item.Key into paraIndexandCountPair
select new { Key = paraIndexandCountPair.Key, Count = paraIndexandCountPair.Count() };
// Get the occurences of each word in the selected sentence
foreach (var worditem in paraItems)
{
for (int count = 0; count < worditem.Count; count++)
{
if (!string.IsNullOrEmpty(paraIndexString))
{
paraIndexString = string.Format("{0},{1}", paraIndexString, (index + 1).ToString());
}
else
{
paraIndexString = (index + 1).ToString();
}
}
}
}
if (indexCount == atozCharArray.Length)
{
indexCount = 0;
iteration++;
indexString =
GetIndexString(atozCharArray[indexCount++], (iteration+1));
}
else
{
indexString =
GetIndexString(atozCharArray[indexCount++], (iteration+1));
}
string outPutString =
string.Format("{0,-15:D}", item.Key.ToString()) + "{" +
string.Format("{0}:{1}", item.Count.ToString(), paraIndexString) + "}";
string FormattedoutPutString =
string.Format("{0,-5:D} {1}", indexString, outPutString);
Console.WriteLine(FormattedoutPutString);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
/// Method Name: GetIndexString
/// Description:
/// This method returns the formatted string based on the input character
/// and number of character .

/// Parameter: char charachterToPrint
/// This parameter is the character toprint.

/// Parameter: int charachterCount
/// This parameter is the character count to format the output.

/// Returns:
/// - Returns the formatted string such as a. b. .... aa. bb..
///

///
static string GetIndexString(char charachterToPrint, int charachterCount)
{
string charachterToPrintString = string.Empty;
if (charachterCount != 0)
{
char[] charachterToPrintArray = new char[charachterCount];
for (int count = 0; count < charachterCount; count++)
{
charachterToPrintArray[count] = charachterToPrint;
}
charachterToPrintString =
string.Format("{0}{1}", new string(charachterToPrintArray), ".");
}
return charachterToPrintString;
}
}
}

Search This Blog