0

Using a generic base class control in WPF

Posted in C#, WPF at June 26th, 2009 by Gerrod / No Comments »

One thing that I find myself doing all the time is creating some type of base class for my windows/controls in WPF:


namespace Editors {
    public class EntityEditorControlBase<TModel> : UserControl
        where TModel : class, IEntityEditorModel {

        public TModel Model {
            get { return DataContext as TModel; }
            protected set { DataContext = value; }
        }
    }
}

Since this is a generic control you need to specify the concrete type arguments when you subclass it. You can do this in your WPF markup via the x:TypeArguments attribute:


<Editors:EntityEditorControlBase
    x:Class="ConcreteEntityEditorControl"
    x:TypeArguments="Models:ConcreteEntityEditorControlModel"
    xmlns:Editors="clr-namespace:Editors">

    <UserControl.Resources>
        <ResourceDictionary Source="../Resources/EditorResources.xaml" />
    </UserControl.Resources>

    <!-- control content here -->

</Editors:EntityEditorControlBase>

One important thing to note: when you want to attach a resource dictionary to the class, you do so using the <UserControl.Resources> tag!

0

Abstracting the Data Access Layer

Posted in .Net, C#, Development at May 18th, 2009 by Ben / No Comments »

This article endeavours to describe how to use the Repository Pattern to abstract and control access (CRUD operations) to a data model locally, through mocks and over-the-wire using the Entity Framework and ADO.Net Data services respectively.

By exposing your Data Access model through a defined interface you can replace your data access implementation to suit your needs whether it be for unit testing or to change the data access frameworks you use.

Background:

Microsoft is pushing the ADO.Net Entity Framework as the ORM of choice going forward.

It’s usually a good idea to get behind Microsoft’s frameworks as you know they will build all sorts of cool utilities and other frameworks on top of them and we all want these goodies. (NOTE: I say usually, because sometimes they cease to support frameworks they’ve pushed before eg. Linq-to-Sql).

The E.F has a number of issues that you will find lots of complaints about on the net, with the most annoying being no support for Persistence Ignorance (i.e. POCOs). However, if you can work around this or are fortunate enough to start a new project where your conceptual model hasn’t been defined yet you might still consider using the E.F.

This article won’t go into the arguments for and against the E.F. and is aimed at people who are happy to head down the E.F. path.

When you use the E.F. you’re next step might be to utilize the RESTful framework they’ve built on top of it called ADO.Net Data Services (formerly Astoria). By simply plugging in your E.F. model you can easily expose portions of your data model over the web via a RESTful nature.

Getting automatic exposure to your data model over http is very exciting due to its simplicity and that universal appeal that any client can interact with your server code.

Let’s get started.

The Repository Pattern:



/// 
/// Generic CRUD Repository operations.
/// 
public interface IRepository : IDisposable
{
    T Single<T>(Expression<Func<T, bool>> whereCondition, params string[] includes);
    Collection<T> Get<T>(Expression<Func<T, bool>> whereCondition, params string[] includes);
    Collection<T> Get<T, TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> orderBy, bool ascending, params string[] includes);
    Collection<T> Get<T, TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> orderBy, bool ascending, int startRow, int pageLength, out long totalCount, params string[] includes);
    Collection<T> GetAll<T>();
    void Delete<T>(T entity);
    void Add<T>(T entity);
    void SaveChanges();
    bool IsDisposed();
}

First we define the Repository interface. The repository interface exposes a generic set of Create, Read, Update and Delete (CRUD) operations to work against any type of Entity – T.

It’s worth noting that the Get operations take a list of “include” parameters. These “includes” explicitly define which relationship properties to explicitly (eagerly) load when returning the Entity (or collection of Entities) of type T.

For example:


var order = repository.Single<Order>(o => o.OrderID == 10250);

When you call Single on an Order entity the Order entity will be returned; however its Customer property will be null by default.

If you wish to return the Order entity with its Customer relationship eagerly loaded you must specify this explicitly.


var order = repository.Single<Order>(o => o.OrderID == 10250, "Customer");

(NOTE: The IRepository interface has been defined this way for two reasons:

  1. The Entity Framework doesn’t support lazy loading of dependent properties (yet!)
  2. Because we are using the same interface for local access to a data store and also for access across the wire using ADO.Net data service it’s best to explictly know exactly what you are pulling across
    from the underlying datastore for bandwidth and performance reasons.

)

Now that we have a generic Repository interface it’s simply a matter of creating the implementations you require. You can create any implementation to wrap whatever Data Access framework you want, including Linq-to-Sql, Entity Framework, NetTiers, NHibernate, Sonic, your own framework, etc.

For the purposes of this article, I have created two implementations:

  1. An entity framework repository.
  2. An ADO.Net Data Service (.Net Client) repository.

The EntityFrameworkRepository implementation works with a VS2008 generated .EDMX ObjectContext instance and utilizes the Microsoft EFExtensions project to add support for SPROC access.

The DataServiceRepository implementation requires ADO.Net Data Services CTP 1.5 to be installed on your machine to utilize query performance improvements (count) and the INotifyPropertyChanged and INotifyCollectionChanged interface implementations on the client proxy objects to implement change-tracking on the entities.

(NOTE: In the future I hope to create a .Net Data Service (Silverlight Client) repository too.)

Once the desired IRepository implementations have been created you may consider creating an IRepositoryFactory implementation to manage the Repository location and lifecycle operations for you.



    /// 
    /// Factory to return instances of .
    /// 
    public interface IRepositoryFactory
    {
        /// <summary>
        /// Get an instance of <see cref="IRepository"/>
        /// </summary>
        /// <param name="name">the name of the repository to return</param>
        /// <returns>an instance of <see cref="IRepository"/></returns>
        IRepository GetRepository(string name);
    }

Access the EF model in-process:


var repository = repositoryFactory.GetRepository("Northwind_Local");
Orders order = repository.Single<Orders>(o => o.OrderID == 10250);

Or to go over the wire:


var repository = repositoryFactory.GetRepository("Northwind_DataService");
Orders order = repository.Single<Orders>(o => o.OrderID == 10250);

Or to mock out for unit testing:


IRepository mockRepository = MockRepository.GenerateMock<IRepository>();
Expression<Func<Orders,bool>> whereCondition = o => o.OrderID == 3;
mockRepository.Stub(r => r.Single(whereCondition)).Return(new Orders() { OrderID = 3 });
RepositoryFactory.SetRepository("Northwind_Local", mockRepository);

IRepository repository = _repositoryFactory.GetRepository("Northwind_Local");
Orders order = repository.Single(whereCondition);

Where to next:

Download the Repository Pattern VS 2008 SP1 Solution.

Install the ADO.Net Data Services CTP 1.5 installer found under /3rdPartyAssemblies/ADONETDataServices_v15_CTP1.exe in the zip file download.

Then set an environment variable dscodegen_databinding value to 1.
This ensures service reference generation in VS2008 uses CTP version and not the old school version. View the video in this link for more info.

Once you are setup, open up the various unit test classes to see how to utilize the various implementations. The EF model is generated against the Northwind database (included as a file reference).

Reference Links:

Persistence Ignorance
http://blogs.msdn.com/dsimmons/archive/2007/06/02/persistence-ignorance-ok-i-think-i-get-it-now.aspx

Repository Pattern
http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx

Repository Pattern with EF

Data Access with Repository
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/12/data-access-with-the-entity-framework.aspx

Testable Data Access with the Repository Pattern
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/14/testable-data-access-with-the-repository-pattern.aspx

Entity Framework – Some Common Hurdles
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/17/entity-framework-some-common-hurdles.aspx

ADO.Net Data Services CTP – 1.5

ADO.Net Data Services Blog
http://blogs.msdn.com/astoriateam/default.aspx

Data Binding (ie.implements INotifyPropertyChanged and INotifyCollectionChanged interfaces)
http://blogs.msdn.com/astoriateam/archive/2009/03/21/ado-net-data-services-v1-5-ctp1-data-binding-overview.aspx

Microsoft EFExtensions
http://code.msdn.microsoft.com/EFExtensions

2

Coding better: It’s the little things.

Posted in C# at February 25th, 2009 by Gerrod / 2 Comments »

I really don’t like inefficiency in code. Some people would say I’m quite the coding nazi when it comes to stuff like this; I’m sorry, but I just don’t like having code that exists just because someone thinks “it makes it read more like english”. Sorry, but C# != English.

Don’t get me wrong; I’m all for writing clear, concise code. I strongly encourage using descriptive method names, and fully expressed variable names (e.g. “requestContext” instead of “rc”). But all I’m saying is, don’t over-do it! Here are three small tips you can use to work around small inefficiencies in your code.

Use System.Math
How many times have you come across a segment of code like this?


if (waitTimeMillis < MaxPingTime) {
    waitTimeMillis *= 2;
    if (waitTimeMillis > MaxPingTime) {
        waitTimeMillis = MaxPingTime;
    }
}

Sure, it looks pretty harmless, but we need to read three lines of code to work out that there is an upper limit on waitTime. We can better express that using the Math.Min function:


if (waitTimeMillis < MaxPingTime) {
    waitTimeMillis = Math.Min(waitTimeMillis * 2, MaxPingTime);
}

A boolean is a boolean
I remember one of our lecturers at uni first pointed this one out to me when we were learning java. Comparing a boolean expression to true or false is redundant - just evaluate the expression instead. So, don't do this - ever:


if (MyClass.IsInitialised == true) {
    RunPostInitialisation();
}

No folks, I don't want to see "== true" or "== false" in your code, ever. I guess it could be worse, you could have "!= true"... - either way, lets keep it simple:


if (MyClass.IsInitialised) {
    RunPostInitialisation();
}

Use ternary expressions instead of if/else
Do you really need that if/else clause?


if (house.NumberOfOccupants > 1) {
    house.MaximumNumberOfPets = 3;
} else {
    house.MaximumNumberOfPets = 2;
}

There are circumstances where an if/else clause may be justifiable; but in general, they aren't needed. A ternary expression is much more succinct:


house.MaximumNumberOfPets = house.NumberOfOccupants > 1 ? 3 : 2;

Where the values that you're using for the true/false evaluation of the expression are a bit more complex, you can separate this on to multiple lines to read a bit more clearly:


Type type = Instruments.ContainsKey(instrumentType)
    ? Instruments[instrumentType]
    : UnknownInstrumentType;

Code better!

2

Selecting an item in a TreeView in WPF

Posted in .Net at December 11th, 2008 by Gerrod / 2 Comments »

I have to admit that I much prefer WPF over Windows Forms (but prefer ASP.Net to either). However, the programming model is still a bit immature (in my opinion), and sometimes things that you wish were simple just aren’t. Case and point: trying to programmatically select an item in a TreeView control; it just ain’t easy!

Anyway, after scrubbing the web and finding a few solutions that really didn’t appeal (e.g. using reflection; surely it’s not that hard!) I came up with this extension method which does the trick quite nicely.


/// <summary>
/// Walks the tree items to find the node corresponding with
/// the given item, then sets it to be selected.
/// </summary>
/// <param name="treeView">The tree view to set the selected
/// item on</param>
/// <param name="item">The item to be selected</param>
/// <returns><c>true</c> if the item was found and set to be
/// selected</returns>
static public bool SetSelectedItem(
    this TreeView treeView, object item) {

    return SetSelected(treeView, item);
}

static private bool SetSelected(ItemsControl parent,
    object child) {

    if (parent == null || child == null) {
        return false;
    }

    TreeViewItem childNode = parent.ItemContainerGenerator
        .ContainerFromItem(child) as TreeViewItem;

    if (childNode != null) {
        childNode.Focus();
        return childNode.IsSelected = true;
    }

    if (parent.Items.Count > 0) {
        foreach (object childItem in parent.Items) {
            ItemsControl childControl = parent
                .ItemContainerGenerator
                .ContainerFromItem(childItem)
                as ItemsControl;

            if (SetSelected(childControl, child)) {
                return true;
            }
        }
    }

    return false;
}

(Forgive formatting; the code window is only so-wide.)

The trick, you see, is to use the ItemContainerGenerator on the ItemsControl – which TreeView and TreeViewNode both inherit from – to try to find the container for the item you are selecting. This will only work for the immediate children of the control that you’re calling it on – so asking your root node for the container for an item which is three nodes deep is fruitless; hence, you have to walk down the tree asking each branch node if it contains the item.

It’s possibly not the fastest executing code in the world – walking a tree rarely is – but you could speed things up if you knew where the parent node was; then you could just call the recursive method directly.

Enjoy!

1

How do you hide bad code smells?

Posted in .Net, C#, Development at November 26th, 2008 by Ben / 1 Comment »

Ever come across some code that just wreaks?

I’m talking the kind of smells like 500 line method implementations or methods that are located in the wrong class.

It’s amusing to see how developers go out of their way to hide their problems rather than fix them.

There are two code-smell hiding techniques I often see utilized in the C# Visual Studio space.

  1. Wrap the offending code in a #region (and hope that others don’t have region expansion on by default)
  2. Move the distracting/inappropriately placed members into a partial class

Most often though I find that developers seem proud of the smells as they don’t even bother to hide the fact that they’ve just left a big stinky guff for the next person to walk right into.

What code-smell hiding techniques have you been witness to? Or more importantly how do you hide your own smells?

I’ve often seen code that tries to get a numeric bit (1, 0) value for a boolean.

I know of three ways you can do it:

  1. Manual condition checking
  2. Use the GetHashCode() method
  3. Use the built in .Net Convert class

All three approaches do the job however I find that using the Convert.ToByte(boolValue) makes the most sense from a readability stance.

The following examples mix it up a bit and accommodate a Nullable<bool>.

Let’s start with the scenario where true is 1 and false and null are 0.


   bool? tVal = true;
    bool? fVal = false;
    bool? nVal = null;

    // true = 1, false = 0, null = 0

    Assert.AreEqual(1, tVal.HasValue && tVal.Value ? 1 : 0);
    Assert.AreEqual(0, fVal.HasValue && fVal.Value ? 1 : 0);
    Assert.AreEqual(0, nVal.HasValue && nVal.Value ? 1 : 0);

    Assert.AreEqual(1, tVal.GetHashCode());
    Assert.AreEqual(0, fVal.GetHashCode());
    Assert.AreEqual(0, nVal.GetHashCode());

    Assert.AreEqual(1, Convert.ToByte(tVal));
    Assert.AreEqual(0, Convert.ToByte(fVal));
    Assert.AreEqual(0, Convert.ToByte(nVal));

Now let’s mix it up a bit and say that a null value should represent a TRUE or 1 value by default.
i.e. true = 1, null = 1, false = 0,



    bool? tVal = true;
    bool? fVal = false;
    bool? nVal = null;

    Assert.AreEqual(1, !tVal.HasValue || tVal.Value ? 1 : 0);
    Assert.AreEqual(0, !fVal.HasValue || fVal.Value ? 1 : 0);
    Assert.AreEqual(1, !nVal.HasValue || nVal.Value ? 1 : 0);

    Assert.AreEqual(1, (tVal ?? true).GetHashCode());
    Assert.AreEqual(0, (fVal ?? true).GetHashCode());
    Assert.AreEqual(1, (nVal ?? true).GetHashCode());

    Assert.AreEqual(1, Convert.ToByte(tVal ?? true));
    Assert.AreEqual(0, Convert.ToByte(fVal ?? true));
    Assert.AreEqual(1, Convert.ToByte(nVal ?? true));

Is there an easier, better or another alternate way to do this?

I’d love to hear your thoughts?

This article collates some good answers to resistive arguments for using Object Relational Mappers.

2

Writing clean, usuable CSS

Posted in Development, css at November 13th, 2008 by Ben / 2 Comments »

This article demonstrates 21 techniques you can employ to write usable CSS.

0

Creating Custom Exception Types

Posted in .Net, Development at November 10th, 2008 by Ben / No Comments »

One of the things that pops up over and over in project development is the issue of when to create Custom Exceptions.

To come to any form of conclusion it’s necessary to understand the reason why you might create your own Exception class.

1. To allow typesafe error detection and act appropriately.
2. To add context specific data.
3. There’s no existing framework exception that signifies the error.

1. To allow typesafe error detection.

Creating a customized exception allows the receiver to act upon a specific error. Using this approach the receiver is forced to detect that specific error to perform any useful action.
Examples where creating a custom exception for this scenario to make sense include;

- situations where you may need to prompt a user to correct a problem (e.g. disk full exception)
or
- where you need to log specific exceptions.

2. To add context specific data.

By adding more context to an exception, the receiver of the exception can use this information to help track down and recover from the error.

An example; say the validation rules for an object instance fail, by attaching the validation rules to the exception the receiver may use them to display appropriate error messages on screen to help recover from the error.

E.g.


public class ValidationException : Exception {

  public ValidationException(ValidationResults results) : base(results.ToString())
  {
Results = results;
  }

  public ValidationResults Results {get;set;}
} 

public class ValidationResults : IEnumerable<KeyValuePair<string,string>> {

  public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
    ...
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }
}

Usage:

try {
  ...
  ...
} catch (ValidationException ve) {
  foreach (var result in ve.Results) {
    Console.WriteLine("Error:" + result.Key + " : " + result.Value);
  }
}

Alternately, the System.Exception class contains a Data Dictionary property that can be used to attach context without having to create your own customized exception class:

E.g.


var exception = new InvalidOperationException("ValidationException"); 

var validationResults = new Dictionary<string, string>();
validationResults["Name"] = "The Name value is too long.";
validationResults["Postcode"] = "The Postcode is invalid.";
exception.Data.Add("ValidationResults", validationResults);

throw exception;

The lack of type safety in the Data dictionary may be off-putting but using extension methods you can add some type safety.


public static IDictionary<string, string> GetValidationResults(this InvalidOperationException ioe)
{
  if (ioe.Data.Contains("ValidationResults"))
  {
    return ioe.Data["ValidationResults"] as Dictionary<string,string>;
  }
  return new Dictionary<string, string>();
}

public static string GetValidationMessage(this InvalidOperationException ioe, string key)
{
  if (ioe.Data.Contains("ValidationResults"))
  {
    return ((IDictionary<string, string>) ioe.Data["ValidationResults"])[key];
  }
  return null;
}

I find that using the Data dictionary approach may save you the benefit of creating a Custom Exception but at the expense of more verbose and un-intuitive code.

3. There’s no existing framework exception that signifies the error.

The detail level to which you can specify an exception type is infinite. When it comes down to it there are few framework exception types that are valid for most scenarios:

Input value causes exception; throw one of

System.ArgumentException
System.ArgumentNullException
System.ArgumentOutOfRangeException

For all other errors a good default option is to use the System.InvalidOperationException.

Conclusion:

To sum up, think carefully about the specific scenario that is being addressed when writing exception logic, follow this checklist to help in your decision making.

Is there a need to act upon the specific exception and find a way to recover from it?

Yes -> Consider creating a generic custom exception.
For example create an exception named DuplicateEntityException rather than JobRateAlreadyExistsException.

No -> throw an existing exception type.

Do you need to log a specific error scenario?

Yes -> Consider creating a generic custom exception.
No -> throw an existing exception type.

Do you need extra information in the exception to respond effectively?

Yes -> Determine whether creating a custom exception with typesafe data members is more intuitive than using the Data dictionary on the System.Exception class.
No -> throw an existing exception type.

For all other scenarios default to throwing an existing exception type.

What are your thoughts and experiences on this issue?

0

Enterprise Library Walkthrough

Posted in .Net, C# at November 7th, 2008 by Ben / No Comments »

What is Enterprise Library?

Ent.Lib 4.1 – http://msdn.microsoft.com/en-us/library/dd203099.aspx

The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns (such as logging, validation, data access, exception handling, and many others).

The application blocks aim to encapsulate proven best-practice for enterprise .net development.

In total there are over 9 application blocks:

  • Caching
  • Cryptography
  • Data Access
  • Exception Handling
  • Logging
  • Policy Injection
  • Security
  • Unity – Dependency Injection (IoC) container
  • Validation

This article will address the Exception, Logging, Validation and Unity application block. The new Unity Application block encapsulates the Policy Injection block and as such will not be addressed in this article along with the Caching, Cryptography and Security blocks.

Download Ent. Library 4.1 here:
http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&displaylang=en

Important:

This article is just a rehash of information easily found in the Ent.Library documentation and online websites. To get a comprehensive understanding of how the blocks work download the Sample Code I’ve created here.

Alternately, for further demonstrations on how these blocks work, load up the included QuickStart tutorials included with the Ent. Lib download.

Note:
The solution is works with VS 2008 Team System. It utilizes the seperate Unity Application block but works with Ent. Library 3.1 for all other App. Blocks due to 3rd party software we use that has a dependency on Ent. Lib 3.1.

To migrate to Ent. Lib 4.1 just change all references for 3.1 app blocks to 4.1 app blocks.
You will also be able to remove out the the ApplicationCode/CallHandlers/*.cs files and use the 4.1 PolicyInjection CallHandlers.

NOTE: Be sure to read the rest of this article by clicking the link below.

Read the rest of this entry »