30 March, 2011

SimpleMvvmToolKit – now with navigationsupport

Having used the SimpleMvvmToolKit for a while, I’ve come to see that this also is missing out on the inherent problem about navigation in a WP7 application when you are using MVVM as design foundation. According to Tony Sneed, the way navigation should be taken care of is by using the MessageBus and/or Notifications. I find this to be a little too loosely coupled for my taste. I feel that a WP7 framework should at least support navigation from the ground up and not be some kind of an afterthought?

Previously, I’ve been discussing a dedicated NavigationController (at that time referred to as ApplicationController) in a WP7 application. This concept is quite a good invention, as it allows you to specify the whereabouts of your Views in one place only. And next navigate in the application in a type safe way using enums as references. Last but not least, you leave the navigation functionality to dedicated controller that handles this very task: to navigate. I severely prefer the Separation of Concern principle. Due to this reason, I’ve added support for NavigationController in an improved version of the SimpleMvvmToolKit.

image

How do you use this NavigationController baked into the SimpleMvvmToolKit?
First – you need to create a simple enum that states the various Views that exists in your application.

public enum ViewType
{
Home,
Security,
Settings,
Trade,
PropertyEditor,
About,
Theory,
SecurityHistoryView,
ErrorView
}

In you app.xaml (where life starts); you register this enum alongside their location in your application.

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
void Application_Launching(object sender, LaunchingEventArgs e)
{
//init data
PortfolioManager.InitializeDataStorage();
IsolatedStorageHelper.ClearRuntime();

SetupNavigationController();
}

private void SetupNavigationController()
{
NavigationController<ViewType>.Current.Clear();

////add known views
NavigationController<ViewType>.Current.Register(ViewType.About, new Uri("/Views/AboutView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.ErrorView, new Uri("/Views/ErrorView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.Home, new Uri("/MainView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.PropertyEditor, new Uri("/Views/PropertyView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.Security, new Uri("/Views/SecurityView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.SecurityHistoryView, new Uri("/Views/SecurityHistoryView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.Settings, new Uri("/Views/SettingsView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.Theory, new Uri("/Views/TheoryView.xaml", UriKind.Relative));
NavigationController<ViewType>.Current.Register(ViewType.Trade, new Uri("/Views/TradeView.xaml", UriKind.Relative));
}

After having made these registrations, navigation is quite easy anywhere in your application. It is as simple as calling like this:

public void NavigateToAbout()
{
//navigate to the About view...
NavigationController<ViewType>.Current.NavigateTo(ViewType.About);
}

You will never misspell or do anything wrong using this approach. All addresses are written in one place only (app.xaml) and you refer to them as an enum-value.


Download the improved version here: www.clauskonrad.net/download.ashx?id=13


Technorati Tags: ,

WP7: “Hello World” using SimpleMvvmToolkit framework

Having been playing with a number of different frameworks for MVVM, I’ve now come to the simplest possible solution, the Tony Sneed framework called SimpleMvvmToolkit. It is presented (by Tony Sneed!) as the simplest possible way of doing MVVM. Well – that’s easy to say when you’ve made the framework, dude!

I would say (having 12 years+) experience, that it is not that easy after all, Tony! A “Getting-started” solution is presented on codeplex; but even that one is not that trivial and easy/straight forward and leaves a lot to wish for. So based on that experience, a proper “Hello world” is due!

Let’s first establish some terminology:

View (V):
The pure UI-elements. Handles rendering of UI to the end user. Has no knowledge of the ViewModel (VM) nor the Model (M).

ViewModel (VM):
UI-logic and notification of the UI when values are changed.

Model (M):
The object (e.g. Customer) to present in the UI (view). This is basically a DTO (Data Transfer Object) with little logic embedded. The properties of a Model is what is reflected in the View (using bindings).

Service:
A provider or Factory that can “provide” model-objects to the ViewModel.

ViewModelLocator (helper):
A provider of ViewModels and Services to the system.


The overall architecture of MVVM  (in the SimpleMvvmToolkit implementation) is seen here:

image

As seen in the figure – a number of classes/objects are in play here. The main players (View, ViewModel, Model and Service) are the green boxes, where as the yellow boxes are helpers. The View has as previously mentioned no knowledge of the Model or it’s properties. The “knowledge” required to render data in the View is entirely made using XAML-bindings in WPF/Silverlight. This is where the magic lies in the powerful binding implementation presented by XAML.

Hello World
The solution we are after, is the simplest possible implementation on a WP7 phone.

image             image

As seen in the solution view (above), the known players (M-V-VM) are in their own folders. In addition, a dedicated “Services” folder is presented.

Model
The model needs to inherit from ModelBase<T> (part of SimpleMvvmToolKit) to allow it to notifiy the View by means of INotifiyPropertyChanged support.

namespace MVVM_HelloWorldWP7.Models
{
public class HelloModel : ModelBase<HelloModel>
{
public HelloModel()
{
Greeting = "Hello world!";
}

private string m_greeting;
public string Greeting
{
get { return m_greeting; }
set
{
m_greeting = value;
NotifyPropertyChanged(m => m.Greeting);
}
}
}
}

ViewModel
The ViewModel is a bit more advanced. This guy needs to inherit from ViewModelDetailBase (part of SimpleMvvmToolkit). By inheriting from this baseclass and presenting the “HelloModel” as detailType, the VM will present a property called “Model” of the proper type (HelloModel in this case). As you can also see,the VM is equipped with 2 constructors; one with the Model as argument, one with a “Service” as argument. By constructing the VM with these arguments, you are actually able to inject other implementations from the outside. This is not shown in this simple example though.

namespace MVVM_HelloWorldWP7.ViewModels
{

public class HelloViewModel : ViewModelDetailBase<HelloViewModel, HelloModel>
{
#region Initialization and Cleanup

private IHelloService serviceAgent;

// Default ctor
public HelloViewModel() { }

public HelloViewModel(HelloModel model)
{
base.Model = model;
}

public HelloViewModel(IHelloService serviceAgent)
{
this.serviceAgent = serviceAgent;
}

#endregion

#region
Notifications

// TODO: Add events to notify the view or obtain data from the view
public event EventHandler<NotificationEventArgs<Exception>> ErrorNotice;

#endregion

#region
Properties

// TODO: Add properties using the mvvmprop code snippet

#endregion

#region
Methods
/// <summary>
///
ICommand to be called by declaration in the view (Click to load-button)
/// </summary>
public ICommand LoadDataCommand
{
get
{
return new DelegateCommand(LoadHelloModel);
}
}
public void LoadHelloModel()
{
this.Model = serviceAgent.GetModel();
}

#endregion

#region
Completion Callbacks

// TODO: Optionally add callback methods for async calls to the service agent

#endregion

#region
Helpers

// Helper method to notify View of an error
private void NotifyError(string message, Exception error)
{
// Notify view of an error
Notify(ErrorNotice, new NotificationEventArgs<Exception>(message, error));
}

#endregion
}
}

Service
The service presenting the VM with Models, consists of a declaration in the form of an Interface (good design!) as well as an implementation (mock in this case). The Service here was what confused me in the beginning; it is not a service in it’s traditional sense, but should be considered in a more broad terminology as a (simple) provider of Models. It does so by asking database, web services or other means of logic. Ultimately, it will present the VM with an instance of a Model (HelloModel in our example).

namespace MVVM_HelloWorldWP7.Services
{
public interface IHelloService
{
HelloModel GetModel();
}
}
namespace MVVM_HelloWorldWP7.Services
{
public class HelloServiceMock : IHelloService
{
public HelloModel GetModel()
{
return new HelloModel();
}
}
}


ViewModelLocator
The ViewModelLocator is what ties the entire MVVM-system together. Hence, it’s a quite important part of the entire setup here. The ViewModelLocator is responsible for presenting VM’s to the system when they are requested.

namespace MVVM_HelloWorldWP7
{
public class HelloWorldModelLocator
{

private IHelloService serviceAgent;

/// <summary>
///
Initializes a new instance of the ViewModelLocator class.
/// </summary>
public HelloWorldModelLocator()
{
//init the service (agent)
serviceAgent = new HelloServiceMock();
}

private HelloViewModel m_helloVM;
/// <summary>
///
Gets the HelloViewModel.
/// </summary>
public HelloViewModel HelloViewModel
{
get { return m_helloVM ?? (m_helloVM = new HelloViewModel(serviceAgent)); }
}
}
}

To allow the components of the system to gain access to the single ViewModelLocator in the system, it is declared in AppResources (App.xaml). Note the x:key=”Locator”; this is a convention in SimpleMvvmToolkit and can not be changed. As the ViewModelLocator has a default constructor, it can be instantiated by WPF automatically and presented to the rest of the system at will.


Press image to see larger version


View (part 1)
The final part of this system is the UI (the View). This is pure XAML and declarations. It knows (luckily) nothing about anything but how to render UI elements. As seen, you need of-course to set the datacontext to the ViewModelLocator (remember the x:key=”Locator” above ?)


Press image to see larger version


With this context set, you can now reference the various display fields like this (Model.<propertyName>).


Press image to see larger version


View (part 2)
To make this example a little more than just display a text, support for Click events of a button is also presented. This is wired up using declarations and attached properties like below. It does however mean, that the UI is completely free of code as this will link Click events to the ViewModel directly.


Press image to see larger version


To make these aliases work, you need to add a reference to them at the top of the page


Press image to see larger version


So – finally it is working and everybody are happy! Not that simple after all…
But, hopefully someone gains from this as well.


Download the above sample here: www.clauskonrad.net/download.ashx?id=14


Technorati Tags: ,,

24 March, 2011

MEF: A simple introduction

Using MEF (Managed Extensibility Framework) can be somewhat of a steep learning experience as a number of new concepts are introduced. However, once these concepts are established it proves quite easy to get your head around it.

But first - why should you even bother learning this pretty new (read: .NET 4.0) framework? Well – you can not miss it; a large number of other frameworks are using MEF as the underlying plumbing system. So, you are kind of forced to learn the concept or at least make an overall acquaintance with it. This was my experience when adopting the Caliburn.Micro framework. In addition - as MEF (System.ComponentModel.Composition) comes as a built-in framework in .NET 4.0, it is easy to just reference in VS 2010 and start using it; no need to download a third-party library. At least that’s the sales pitch coming out of the “evangelists” from the empire in Redmond (or their local apprentices).

So – what to do?
MEF presents the following (new) concepts:

Composable Part (simple, a part):
Any member taking part in the composition presented by MEF

Container:
A runtime entity handling instances of Exporting and Importing members. It does so using a Catalog.

Catalog:
Holds a discoverable list of types/assemblies decorated with [Export] and [Import] attributes.

[Import] (attribute):
An attribute you apply to a property/field on a consuming type.

[Export] (attribute):
An attribute you apply to a class that exports some interface/type

These new concepts are used by MEF to perform the runtime composition in your system.

Solution:
The overall solution is seen below. It contains an exe-file (Console) that references a Contracts (library). Furthermore, 2 implementations exists (SqlLogger and TxtLogger) which reference the Contracts assembly to be able to implement the interface ILogger.

image

The solution is seen below in Visual Studio.

Solution (Visual Studio 2010)

Console:
The console (exe-file) is completely unaware of what’s happening. It lives happily without knowing anything (and that’s actually a good thing). The only reference it knows of is the LoggingFacade.

class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Starting client...");

var facade = new LoggingFacade();
facade.Write("Hello World"); //just write!

System.Console.WriteLine("Done - press key");
System.Console.Read();
}
}


Contracts:
The contracts assembly is where the meat in this solution is. It contains an interface and the fa├žade that makes use of MEF. Pay attention to the [Import] attribute on the property ConcreteImplementation (note that this property is private). This is what tells MEF that LoggingFacade needs (Imports) a type of ILogger.

/// <summary>
///
A logger abstraction
/// </summary>
public class LoggingFacade
{
/// <summary>
///
Initializes a new instance of the <see cref="LoggingFacade"/> class.
/// </summary>
public LoggingFacade()
{
//create catalog of exporting/importing types from the directory where the exe-file is located
var catalog = new DirectoryCatalog(Environment.CurrentDirectory);

//create composition container (doing the composition)
var container = new CompositionContainer(catalog);

//compose (hook together the types behind the scenes)
container.ComposeParts(this);
}

/// <summary>
///
Gets or sets the concrete logger.
/// This simply states that it consumes an 'ILogger' (of some implementation)
/// </summary>
/// <value>
///
The concrete logger.
/// </value>
[Import]
ILogger ConcreteImplementation { get; set; }

/// <summary>
///
Writes the specified message using what ever implementation is presented (found).
/// </summary>
/// <param name="msg">
The MSG.</param>
public void Write(string msg)
{
if (ConcreteImplementation == null) //it not set - return
return;

ConcreteImplementation.Write(msg); //use implementation.
}
}


SqlLogger:
This implementation is very simple. It simply states that it exports a type of ILogger to the world. Who ever wants to use that are free to do so (which in our case is the CompositionContainer in LoggingFacade).

[Export(typeof(ILogger))]
public class SqlLogger : ILogger
{
public void Write(string msg)
{
Console.WriteLine("I'm a SQL implementation...");
}
}


Finally – running the console will present you with this window:



image



Note: By default, MEF will only accept ONE export of each type. Due to this reason, only the SqlLogger is shown here. If you present more than one export of the same type to the CompositionContainer, you have gain an exception (“more than one implementation found!”).




Technorati Tags: ,

DropBox: how to upload files to DropBox using code

DropBox is a great little service that simply “just works”. If you have a DropBox account and wish to operate this from code, you have to know a great deal about REST and other “webby” stuff to communicate with the DropBox account. But, a great little library exists that shields you from all of this. On “github” (what ever that means?) ) you will find the DropNet library that helps you out here. It will allow you to operate the DropBox account quite easily.

How to do ?
1) Register a developer account at Dropbox.com
2) Obtain the ‘key’ and ‘secret’ from DropBox.com (found under ‘My Apps’)
3) Call into the users DropBox account like below

static void Main(string[] args)
{
//client
var client = new DropNet.DropNetClient("32131rwzxynxo50t", "fwwesodkiwud8");

//login
client.Login("user@domain.com", "password");

Console.WriteLine("Uploading file...");

//update file (testfile1.txt) -> dropbox
byte[] rawData = File.ReadAllBytes("textfile1.txt");
var result = client.UploadFile("Test", "textfile1.txt", rawData);

Console.WriteLine("Status = {0}", result.StatusCode);
}


As evident from the sample, you can stream the file to DropBox using the client.UploadFile(<folder>, <filename>, <raw bytes>).



Technorati Tags: ,

DropBox: how to enumerate files from code

DropBox is a great little service that simply “just works”. If you have a DropBox account and wishes to operate this from code, you have to know a great deal about REST and other “webby” stuff to communicate with the DropBox account. But, a great little library exists that shields you from all of this. On “github” (what ever that means?) ) you will find the DropNet library that helps you out here. It will allow you to operate the DropBox account quite easily.

How to do ?
1) Register a developer account at Dropbox.com
2) Obtain the ‘key’ and ‘secret’ from DropBox.com (found under ‘My Apps’)
3) Call into the users DropBox account like below

 

 //client
var client = new DropNet.DropNetClient("u1liluz34reo50t", "werfrewdf9zdptb4u");

//login
client.Login("user@domain.com", "password");

//get root data
var data = client.GetMetaData(string.Empty);

Console.WriteLine("Path = {0}", data.Path);
data.Contents.ForEach(x => Console.WriteLine("name = {0}", x.Name)); //write out all folders/files

As you can see in the sample, you create a DropNetClient instance providing the ‘key’ and ‘secret’. Next you simply login using the User id (email) and password.  GetMetaData(string.empty) is a method call for retrieving all entries from the root-folder. Every ‘metadata’ contains a boolen property (.IsDirectory) that allows you to determine whether you are handling a folder or a file.


Technorati Tags: ,

21 March, 2011

WP7: Usage logging of application using Flurry

Not having to write this framework myself, I’m happy to learn that some guys have been busy establishing a nice business that addresses usage logging, error logging and general usage monitoring of your Windows Phone Application. Something that Microsoft did not provide out of the box to the developer experience. And it’s darn easy to use as well. Good work, guys!

Might I add, that Flurry.com supports (BlackBerry, iPhone, Android, Windows Phone 7); so they got them all covered.

image

 

How do you use this stuff?
1) Signup for a new account => you receive an application key to uniquely identity your application
2) Download their API (single assembly) from their website
3) Insert FlurryWP7SDK.Api.StartSession(<sessionKey>) in Activated/Launching events (see below)
4) That’s it!

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
void Application_Launching(object sender, LaunchingEventArgs e)
{
//register dispatcher class (Galasoft)
DispatcherHelper.Initialize();

//init data
PortfolioManager.InitializeDataStorage();
IsolatedStorageHelper.ClearRuntime();



//UNDONE: register channel with PUSH-notification service

//flyrry
StartFlurrySession();

}

private void StartFlurrySession()
{
//Api.StartSession(Constants.FLURRY_KEY);
FlurryWP7SDK.Api.SetVersion(Utilities.GetVersion());
FlurryWP7SDK.Api.StartSession(Constants.FLURRY_KEY);
}

That’s basically all there is to it! You can access data afterwards on their reporting website.


Technorati Tags:

18 March, 2011

How to: WCF and custom Authentication (username/password)

This post details how you can customize the way users of your WCF-services are authenticated. But, before engaging in this procedure, let’s first establish some terminology/concepts:
Authentication: to establish the identity of an individual/entity.
Authorization: to determine whether an authenticated (identified) individual is allowed access to a system. You Authorize access to a system.
This post is about Authentication (identity establishment)
Authentication is a subject that is pretty hard to deal with yourself. A number of proven and established mechanisms already are in place solving this functionality out-of-the-box in WCF. Due to the very nature of an identity token (it carries the “identity” of an individual), it is shielded with proper usage of cryptography. Therefore – it is very hard to do much in this area yourself. It a completely different story when it comes to Authorization (another post).
Where does Authentication fit into the overall picture? As evident from the figure – the Authentication is the first action taken when an incoming request is received. It makes actually a lot of sense, as it is not possible to perform Authorization before you have established the identity (Authentication) of the incoming user/system.
image
In native WCF - the following security token types (credential types) are supported:
    • Username Token (points by default to an ASP.NET database)
    • X.509 Certificate Token (digital certificates)
    • Kerberos Token (Windows Active Directory)
    • SAML Token (generic Security Assertion Markup Language; also signed with certificate)
As seen, a number of implementations are already in place. So - when would you have a need for this proposed customization? The only one I can think of is, if you are not using e.g. the standard ASP.NET Membership database, but you have rolled your own user storage. In such scenario, it might make sense to use this customization. And the customization in play here would most often be: username/password authentication.
 How do you establish your own Username/Password Authentication?
The entire solution is seen here. It is a Client console, Server Console and a shared library with Contracts (ICalculatorService). Sharing a contract between the two makes sense when you have control of both Client and Server as is the case in this example.
image
The various parts are seen below.
Shared ContractThe shared contract is simply a type safe way of having both Client/Server knowing the types and methods used.
[ServiceContract]
public interface ICalculatorService{
    [OperationContract]
    int Add(int a, int b);

    [OperationContract]
    int Subtract(int a, int b);
}



ServerThe server side is the place where the “meat” is. But, as WCF is constructed in a very clever “stack-like” manner, security is deliberately kept out of the business logic (of the Calculator in this case!). Therefore, you do not see anything security related in the below service implementation. The security is kicking in long time before in the stack before the call ultimately reaches the below business-logic (see the illustration above).
public class CalculatorService : ICalculatorService {
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }
}

The security (and in this case Authentication-part) is created as a custom override of UserNamePasswordValidator. If the incoming credentials do not match user=”Ole” and password=”Pwd”, an AuthenticationException is thrown. These values are of-course to be looked up in your own user storage (a database or…?) Should the credentials however match an identity in your store, no exceptions are thrown.
/// <summary>
/// Custom impl. of u/p validation./// </summary>class UsernameAuthentication : UserNamePasswordValidator {
    /// <summary>
    /// When overridden in a derived class, validates the specified username and password.
    /// </summary>
    /// <param name="userName">The username to validate.</param><param name="password">The password to validate.</param>
    public override void Validate(string userName, string password)
    {
        //TODOs: Lookup match in user storage (DB?).
        var ok = (userName == "Ole") && (password == "Pwd"); 
        if(ok == false)
            throw new AuthenticationException("u/p does not match");
    }
}

Important: Now – you might ask yourself - where is the identity matching the provided credentials actually being set? After all, this is what we are after here; to convert a set of credentials => an identity? As long as we are inheriting from the UserNamePasswordValidator, this is taken care of for us behind the scenes. The UserNamePasswordValidator will create a NameClaim in the authentication chain taking the username as “name”. The NameClaim (= username) is considered an Identity in this scenario.

Server Configuration
To make your service use this custom validation stuff, you need to tweak some settings in <app>.config for the service. Especially, the <usernameAuthentication> settting needs to have a validationMode = “Custom”.
<configuration>
  <system.serviceModel>
    
    <services>
      <service name="Server.CalculatorService" behaviorConfiguration="customCred">
        <endpoint address="net.tcp://localhost:9090/CalcSvc"
                  binding="netTcpBinding"
                  bindingConfiguration="secUP"
                  contract="SharedContracts.ICalculatorService"/>
      </service>
    </services>
    
    <bindings>
      <netTcpBinding>
        <binding name="secUP">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    
    <behaviors>
      <serviceBehaviors>
        <behavior name="customCred">
          <serviceCredentials>
            <!--Service identity + encryption certificate-->
            <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" 
                                storeLocation="LocalMachine" storeName="My" />
            
            <userNameAuthentication userNamePasswordValidationMode="Custom"
              customUserNamePasswordValidatorType="Server.Auth.UsernameAuthentication, Server" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

As seen, a (reasonable) simple configuration is required.



ClientThe clients needs to provide some credentials to the service (we just set this up!).
static void Main(string[] args)
{
    Console.WriteLine("Client - starting...");
    Console.WriteLine("Press key to start...");

    Console.Read();

    var fac = new ChannelFactory<ICalculatorService>("tcpEP");
    //set credentials
    fac.Credentials.UserName.UserName = "Ole"; 
    fac.Credentials.UserName.Password = "Pwd";

    var prox = fac.CreateChannel();
    using (prox as IDisposable)
    {
        var res = prox.Add(1, 2);
        Console.WriteLine("Result: {0}", res);
    }

    Console.Read();
}

That’s about what it takes to create a custom username/password validation against your own data store. Happy coding, guys!

Update: Download project here
http://www.clauskonrad.net/download.ashx?id=15


Technorati Tags: ,

17 March, 2011

How to: Create a simple Chain-Of-Responsibility (COR) implementation

When creating a generic system, that should be able to handle a large (and potentially unknown) number of incoming requests – you can basically go 2 routes:

1) A very large switch-statement
2) Create an COR-chain

Examples of such system needs could be:

1) File Parsing system
2) Http-Request handler implementation
3) Product requests of various kind.

A switch statement very fast proves to be a bad idea. First of all, you need to recompile every time a new request type has arrived. Secondly, it becomes messy and is really bad practice to be honest. It also violates the Separation Of Concern principle that mandates “keep classes focused and do one thing only”.

A COR-chain is a way better approach. It allows you to create focused classes that does one thing only. It makes maintenance and evolution of the system a lot easier. And we all know that systems tend to evolve often sooner than later.

COR-chain principle

So - how do one create a simple implementation of such COR-chain?

The architectural overview is this. The Client only knows of an abstract base class, that is returned to the Client by means of a Factory [ChainFactory] that has the single responsibility of constructing a working chain. The Client only knows what a HandlerBase looks like (see the separation of concern here as well?).

Overall architecture

Implementation
The implementation of the above structure is seen here.

HandlerBase:
The below is the baseclass from which all implementations inherit. This is actually the most important part of the COR-system as it lays down the business logic of the system. All concrete implementations should inherit from this class and implement their own version of the 2 abstract methods.  Also seen - if the current handler is not able to handle the incoming request, it will delegate this to the next in line.

If no  implementation can handle the request, a NotSupportedException is throw by the handler.

/// <summary>
///
Baseclass for handling of file parsing.
/// </summary>
abstract class HandlerBase
{
/// <summary>
///
Next in line...
/// </summary>
protected HandlerBase m_Successor;

/// <summary>
///
Sets the successor.
/// </summary>
/// <param name="successor">
The successor.</param>
public void SetSuccessor(HandlerBase successor)
{
m_Successor = successor;
}

/// <summary>
///
Determines whether this instance can handle the specified file ext.
/// </summary>
/// <param name="fileExt">
The file ext.</param>
/// <returns>
/// <c>
true</c> if this instance can handle the specified file ext; otherwise, <c>false</c>.
/// </returns>
protected abstract bool CanHandle(string fileExt);

/// <summary>
///
Handles the specified file name.
/// </summary>
/// <param name="fileName">
Name of the file.</param>
public void Handle(string fileName)
{
if (CanHandle(fileName)) //can this impl. handle?
{
HandleCore(fileName);
return; //we are done.
}
if (m_Successor != null)
m_Successor.Handle(fileName); //attempt with next in line...
else
throw new
NotSupportedException("unknown fileformat"); //we can not handle!
}

/// <summary>
///
Core implementation (to be impl. in concrete handlers).
/// </summary>
/// <param name="fileName">
Name of the file.</param>
protected abstract void HandleCore(string fileName);
}

ChainFactory
The factory has only one function in this system. It is responsible for creating the chain, link them together and finally returning to the calling client, a reference to the first link in the chain.

/// <summary>
///
ChainFactory
/// </summary>
class ChainFactory
{
/// <summary>
///
Creates the chain.
/// </summary>
/// <returns></returns>
public static HandlerBase CreateChain()
{
var h1 = new TxtHandler(); //first handler
var h2 = new PdfHandler(); //second handler

h1.SetSuccessor(h2); //link togethr

return h1; //return first "link" in chain
}
}

Implementations (Txt, Pdf)
These 2 implementations are made with support for Txt and PDF. Each handler implementations state in the CanHandle-method, whether they can handle the incoming file request. In positive case, they will be handling this and we are done (see abstract HandlerBase).

/// <summary>
///
TxtHandler
/// </summary>
class TxtHandler : HandlerBase
{
protected override bool CanHandle(string fileExt)
{
return fileExt == ".txt";
}

protected override void HandleCore(string fileName)
{
throw new NotImplementedException(); //here should be txt impl.
}
}
/// <summary>
///
PdfHandler
/// </summary>
class PdfHandler : HandlerBase
{
protected override bool CanHandle(string fileExt)
{
return fileExt == ".pdf";
}

protected override void HandleCore(string fileName)
{
throw new NotImplementedException(); //here should be impl.
}
}

Finally, the calling client using this COR-chain is seen here. As seen, this client (called Manager) asks for a Chain from the ChainFactory and next lets the Chain handle the incoming file (fileName).

/// <summary>
///
Manager
/// </summary>
class Manager
{
public void HandleFile(string fileName)
{
//create chain
var ch = ChainFactory.CreateChain();

//throw in file (and let chain handle the reading...)
ch.Handle(fileName);

}
}

With this system, you are able to throw in new implementations (e.g. xml, doc, xls…) without affecting the client. Only the ChainFactory should know about these new implementations. It is very easy to extend and all is well ;-)


Technorati Tags:

16 March, 2011

How to: WCF and Custom Exception Handling (Custom Exceptions), part 2

This is an extension to another post about custom exception handling in WCF.
Part 1: http://blog.clauskonrad.net/2008/06/wcf-and-custom-exceptions.html

If you desire to communicate your own custom exceptions and at the same time include custom data in that exception, you are better off by using the built-in DataContractSerializer. This stands in contrast to the previous way (see above post) of declaring exceptions; but the ease and “ready-to-use” condition of the DataContractSerializer makes it very difficult to argue for rolling your own serialization mechanism.

WCF uses by default the DataContractSerializer to serialize/deserialize data on the wire between the Server and Client, hence this is already in operation out-of-the-box.

How to create this? In this scenario, I have full control of both Client and Server side – hence I can easily share a “contract” between the two. In the below image, you see the 3 projects in effect.

Shared Contracts "Contracts"

Shared Contract
The contract will declare my custom exception called CalculationFaultContract. Note, that this is decorated with [DataContract] attributes as well as [DataMember] attributes. This will make the DataContractSerializer able to serialize this object between Server –> Client just fine.

/// <summary>
///
A custom type to convey error data to the Client
/// </summary>
[DataContract]
public class CalculationFaultContract
{
/// <summary>
///
Gets or sets the argument A.
/// </summary>
/// <value>
///
The arg A.
/// </value>
[DataMember]
public int ArgA { get; set; }

/// <summary>
///
Gets or sets the argument B.
/// </summary>
/// <value>
///
The arg B.
/// </value>
[DataMember]
public int ArgB { get; set; }

}

Server Side
On the server side, you still need to declare what exceptions your methods will throw. This is done using the [FaultContract]-attribute like below. This will inform WCF, that your method will throw this kind of exception to the Client in case of an error has occurred.

/// <summary>
///
/// </summary>
[ServiceContract]
public interface ICalculator
{
/// <summary>
///
Adds the specified arguments.
/// </summary>
/// <param name="a">
A.</param>
/// <param name="b">
The b.</param>
/// <returns></returns>
[OperationContract]
[FaultContract(typeof(CalculationFaultContract))]
int Add(int a, int b);

/// <summary>
///
Subtracts the specified arguments.
/// </summary>
/// <param name="a">
A.</param>
/// <param name="b">
The b.</param>
/// <returns></returns>
[OperationContract]
[FaultContract(typeof(CalculationFaultContract))]
int Subtract(int a, int b);
}

The ICalculator-implementation will, in case of an error, throw the fault like below. Note, that when programming with services, we are principally dealing with “Faults” over “Exceptions”. An exception is a platform specific entity, that can not be carried from Server –> Client. Remember, the Client could potentially be running on a Java-platform, so how would you communicate a .NET exception to this platform?

/// <summary>
///
Calculation implementation.
/// </summary>
public class CalculatorService : ICalculator
{
/// <summary>
///
Adds the specified arguments.
/// </summary>
/// <param name="a">
A.</param>
/// <param name="b">
The b.</param>
/// <returns></returns>
public int Add(int a, int b)
{
Console.WriteLine("Add called...");
//check not negative (to show exception)
if(a < 0)
throw new FaultException<CalculationFaultContract>(
new CalculationFaultContract(){ArgA = a, ArgB = b}, "Argument is negative");

//normal operation
return a + b;
}

Also note, that the message set in the fault (“Argument is negative”) is a so-called FaultReason. Again this is an abstraction that makes the WCF/WS-paradigm operational cross-platform. It is not tied to a specific platform.


Client Side
Finally, on the Client side you surround the proxy-call to the CalculatorService in a try/catch structure of the proper kind. You need to anticipate FaultException<T> here, to be able to receive the proper values from the Server side.

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting CLIENT...");
Console.WriteLine("Press key to call..");
Console.Read();

var fac = new ChannelFactory<ICalculator>(
new NetTcpBinding(),
"net.tcp://localhost:9000/CalculatorService");

var proxy = fac.CreateChannel();
using (proxy as IDisposable)
{
try
{
//this SHOULD throw errors as 'a' < 0
proxy.Add(-3, 5);

}
catch (FaultException<CalculationFaultContract> ex)
{
var msg = string.Format("Caught the RIGHT exception. ArgA={0}, ArgB={1}, Error={2}",
ex.Detail.ArgA,
ex.Detail.ArgB,
ex.Reason);

Console.WriteLine(msg);
}

catch (CommunicationException ex)
{
Console.WriteLine("Caught the WRONG exception.");
}
}

Console.Write("Done");
Console.Read();
}
}

This is basically all there is to communicating your custom data to the calling Client from the server side. On the side note, you maybe can see that this allows you do declare a complete structure of appropriate exception types in your system to very precisely communicate the reason of error from the Server to the calling Client.


It is actually not all that difficult ;-)



Technorati Tags:

15 March, 2011

How to: Create a simple typesafe IOC container

This is an example on how to create the simplest IoC Container. The purpose is understanding the value of such principle, more than it is to produce production code here. Should you decide on using this in production, a number of improvement should be added. The aim here is understanding the concept though, hence have this in mind when reading through.

In the below client example, the program has a hard reference to an implementation called “TxtLogger”. This is fine as long as the Client knows where the TxtLogger implementation is.

class Program
{
static void Main(string[] args)
{
TxtLogger log = new TxtLogger(); //hard ref. to TxtLogger!
log.Log("A message is here...");


}
}
But, what should happen, if you instead did rely on an abstraction? 

Inversion Of Control: Principle ?
Why is IoC a nice principle? Instead of referencing directly to an implementation (that might change) like the above you can rely on an abstraction instead. Where a concrete implementation resides or what implementation is made; is from the Clients perspective not important. The Client should only know about an interface called ILogger in the above case. The Inversion Of Control principle basically takes the responsibility of instantiating an implementation out of the Client class, but lets the Client class rely on abstractions instead. Basically the IoC Container works as a Factory, that produces concrete implementations of a given interface/type. But, in difference to a Factory, the IoCContainer works also as a repository that holds concrete instances. When using the IoC container, you gain this usage scenario:

class Program
{
static void Main(string[] args)
{
//container (composer)
var ioc = new IocContainer();

//register impl.
ioc.Register<ILogger>("sql", new SqlLogger());
ioc.Register<ILogger>("txt", new TxtLogger());

//get real instance...
ILogger logger = ioc.Retrieve<ILogger>("txt");

}
}

Note: The example is not all that real, as you still have a reference to TxtLogger/SqlLogger; but the focus here is how the IoC Container works internally, so please bare with me ;-)


IOC Container ?
How does it look inside? Basically an IoC Container is just a dictionary of names/types and implementations. Given the name, the client can retrieve an instance from the IoC Container (see the factory resemblance?). It is the responsibility of the IoC Container to return a concrete implementation of a type. The simplest implementation is the below IOCSplit.IocContainer class. As seen in the implementation, it has basically 2 methods:

- Register<T>
- Retrieve<T>

These two methods does what the name suggests. Register add an implementation to the dictionary (for later retrieval), whereas the Retrieve method returns a concrete implementation to the calling Client. As seen in the implementation, if you attempt to Register a concrete class and this class does not support the suggested interface, you receive an InvalidOperationException. Secondly, if you attempt to Retrieve a class that is not present in the dictionary, you receive an NotSupportedException. This (to throw appropriate exceptions); I consider good practice when developing frameworks.

namespace IOCSplif
{
/// <summary>
///
Container handling mapping of Types and Names
/// </summary>
class IocContainer
{
private readonly Dictionary<string, object> m_dictionary;

/// <summary>
///
Initializes a new instance of the <see cref="IocContainer"/> class.
/// </summary>
public IocContainer()
{
m_dictionary = new Dictionary<string, object>();
}

/// <summary>
///
Registers an implementation with the specified name.
/// </summary>
/// <param name="name">
The name.</param>
/// <param name="impl">
The type.</param>
public void Register<T>(string name, object impl)
{
if (m_dictionary.ContainsKey(name)) //don't double register
return;

//if not impl. T - then throw exceptions.
if (!typeof(T).IsAssignableFrom(impl.GetType()))
throw new InvalidOperationException("Implementation does not support Interface");

m_dictionary.Add(name, impl);
}

/// <summary>
///
Retrieves an implementation matching the specified name.
/// </summary>
/// <param name="name">
The name.</param>
/// <returns></returns>
public T Retrieve<T>(string name)
{
if(!m_dictionary.ContainsKey(name))
throw new NotSupportedException("The type is not known to the IocContainer");

               return (T) m_dictionary[name];
}
}
}

That’s really all there is to it. A number of full-fledged frameworks exists that does all this for you and to name a few you have:



  • Unity
  • MEF (some argue this is not an IOC implementation?)
  • Structure Map
  • Ninject

Technorati Tags: ,

How to build a 64 bit virtual machine

I today set out to create an x64 bit OS for testing purposes. My host system is a brand new installation of Windows 7 (x64), so all prerequisites should be present (I should learn different soon!).

My initial thoughts for options to host the x64 guest OS was to use the Microsoft Virtual PC, but this turned out to be a doomed attempt. The Microsoft Virtual PC software, even in its x64 version, does not support creating x64 bit Guest installations!

So, what do do? Well – Oracle has an offering that is quite promising. It is called Virtual Box and operates in the same way as Microsoft Virtual PC. And this guy does support running x64 bit OS inside!

Microsoft Virtual PC

No way, Jose. It won’t work.

 

Oracle Virtual Box

The Oracle Virtual Box is free for developers (like myself) and comes with installation support for Windows, Ubuntu and Linux. The last I don’t care about, but as long as the Virtual Box host-software can be installed on Windows 7 I’m happy.

image

As evident from the above figure, the Windows 2008 (64 bit) OS can be installed as a Virtual Machine using the Virtual Box. Expect to find largely the same features as in Virtual PC such as the ability to create SnapShots etc.

A great how-to is found here:
http://www.sysprobs.com/install-run-windows-2008-r2-x86-sun-virtualbox#wrap

Technorati Tags: ,

14 March, 2011

Can’t install Zune on Win7 (N), 64 bit

I today attempted to install Zune PC Client on a Windows 7N, x64 system. That’s a no-go!

Basically, the installation complained that it could not find some media SDK file, what ever? It seems that N-version of the Windows family does not come with Media features included, hence you need to download these yourself.

For N-versions (64 bit), you should go here:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=31017ed3-166a-4c75-b90c-a6cef9b414c4&displaylang=en

After having installed this update, you can go about installing the 64bit version of the Zune Client.

Ultimately, you end up with this:
image

13 March, 2011

WP7: Advanced File Explorer on WP7

Just found this interesting project on codeplex. It’s an unofficial application that allows you to browse the actual filesystem on the device (yes – it is still Win CE!).

ExploringTheFilesystem

In addition, you are able to transfer files to/from the device to your PC. It is all taken care of using a simple WCF-server running on the PC to receive/download the files.

Just for the record: This is not recommended, if you are uncertain on that WCF and WinCE means ;-)

Links:
http://sites.google.com/site/yaafdevelopers/projects/advanced-explorer-for-wp7
http://advancedexplorerwp7.codeplex.com/

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...