Nick Parker
My ramblings on .NET...

UIPAB Survey

Tuesday, 19 September 2006 22:30 by nickp

The patterns & practices team is currently holding a survey about the direction of a new project aimed to fill the gaps and extend where the UIPAB left off. I am curious if they will be integrating Windows Workflow into the project as it seems to be a good fit. At TechEd this summer there were several presentations on Windows Workflow within ASP.NET by the ASP.NET team, hopefully Microsoft isn't creating two different projects with the same goals in mind. This wouldn't happen would it - Windows Communicator, Windows Messenger, MSN Messenger ;-) Go ahead and let them know what you think.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Model View Presenter Redux

Tuesday, 12 September 2006 15:53 by nickp

The Model View Presenter (MVP) pattern seems to be all the rage within the last year; it must be the new pink. While I agree this is a great pattern to decouple various logical layers within a system, I think we are missing an important core piece to the puzzle.

In my opinion, humble of course, the Model is purely a representation of my data, and I prefer to depict that in the form of a Data Transfer Object (DTO), this is the ubiquitous PONO (Plain Old .NET Object) - (Edit: Domain Model's are welcome too) . The View is typically defined as an interface that my UI will provide as implementation. The Presenter will then orchestrate the interaction of my Model to my View. But wait, where does my Model come from? This is where a Service layer comes into play. While there are many different terms for this layer, this layer is responsible for extracting our Model from somewhere (i.e., service implementation). Most commonly, our Presenter will perform specific requests from the Service layer in its orchestration process. I would like to refer to this pattern from now on as MVPS (Model View Presenter Service). I’d love to hear feedback on this, in particular if you don’t agree with me – who doesn’t love a hearty debate?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Dirty SOAP

Tuesday, 13 June 2006 19:43 by nickp
I just came from Scott Hanselman and Patrick Cauldwell's session on dynamically endpoints without ASMX. Their session was great and I had the opportunity to talk with Scott for a little bit afterwards. Scott's company uses dynamic endpoints to allow their customers to easily integrate with their financial software by providing WS-I compliant web services to support integration with disparate client software. Using a dynamic adapter, they are well suited to evolve with the eminent release of WCF. Three days into TechEd and the only things missing are power strips in the session rooms (shouldn't this be an obvious requirement for a technical conference?) and sleep. Sleeping is so overrated.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Dependency Injection with StructureMap

Wednesday, 31 May 2006 20:19 by nickp
I have posted previously about using Spring.NET as an IoC container and how we can implement some of this out of the box with the System.ComponentModel namespace. StructureMap is another dependency injection framework that in my opinon is much more approachable than Spring out of the box. Why? - Let's take a look at what it takes to start requesting services from the StructureMap container.

 

IRule rule = ObjectFactory.GetInstance<IRule>();
or for .NET 1.1

 

IRule rule = ObjectFactory.GetInstance(typeof(IRule)) as IRule;
To begin with, StructureMap now supports generics (granted the 1.0.2 release of Spring does as well), however what is important is I didn't have to create an IResource to initialize an XmlObjectFactory to begin requesting services (again there are some shortcuts in Spring as well but lets continue on). Custom backing stores can be defined for the configuration by deriving from MementoSource in StructureMap. Something that I think is important to note here is that if you aren't using generics, you will request a particular service via a Type, which is different from Spring in which you provide a string as the look up key within the configuration. In my opinion this is nice as it gives me compile time confirmation that I am requesting a type that exists, whereas I could possibly misspell the string if I were using Spring and the compiler wouldn't skip a beat.

Another nice aspect about StructureMap is the ability use attributes to decrease the amount of configuration data that needs to be stored within an XML file. One of the major complaints with Spring is the excess configuration information. This also allows for code to be refactored without making changes to the configuration file. Also, configuration data can be broken up into several config files or even stored as embedded resources. StructureMap comes with StructureMapExplorer as well as StructureMapDoctor to help diagnose problems. I did have to apply the [STAThread()] attribute to the Main method for the StructureMapExplorer code, without that, an instance of the AxWebBrowser could not be created and the application would crash. Since they are targetting .NET 2.0, maybe they will consider using the new WebBrowser class? Overall Jeremy Miller and Jeffrey Palermo have created a very nice product, well worth checking into for your next design.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Extending Enterprise Library 2.0

Thursday, 20 April 2006 18:33 by nickp
Brian Button, formerly of the Patterns and Practices team just held a webcast covering how to provide custom design time extensions to the Enterprise Library console. I missed his session, however after reviewing the slide deck which he has provided, extending Enterprise Library appears much easier than when I had to do it only a year ago. Definitely worth checking out if you would like to integrate your own custom extensions within Enterprise Library.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Service Locator with System.ComponentModel

Friday, 14 April 2006 12:03 by nickp
Javier mentioned from my previous post that it would be nice to be able to request an object directly from .NET, without a reliance on the Spring Framework. To a certain extent, this is provided in the System.ComponentModel and System.ComponentModel.Design namespaces. You can create a ServiceContainer and register services with it, then if you expose your ServiceContainer as an IServiceProvider, your client can then request services back from the container. It looks something like this:

IServiceContainer sc = new ServiceContainer();
sc.AddService(typeof(IDatabase), new Database());
// Add more services
IServiceProvider provider = sc as IServiceProvider;

Now, within another layer, assuming we have the IServiceProvider, I can do something like this:
IDatabase db = provider.GetService(typeof(IDatabase));

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Inversion of Control with Spring.NET

Tuesday, 11 April 2006 07:48 by nickp

I have previously mentioned using the Spring Framework for the AOP support the framework provides, however Spring is deeply rooted in providing dependency injection or Inversion of Control (IoC). Spring uses a configuration file to manage type relationship mappings to objects, which can be stored in its own external XML file, an embedded resource within an assembly, or directly within your web.config or app.config file. For a simple example, we will define our own XML file (spring.xml), with the following contents:

 

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object name="Database"
singleton
="false"
type
="SpringDemo.Database, SpringDemo">
<constructor-arg ref="SqlConnectionObject" />
<
constructor-arg ref="SqlCommandObject" />
</
object>
<object name="SqlConnectionObject"
singleton
="false"
type
="System.Data.SqlClient.SqlConnection, System.Data">
<constructor-arg type="System.String"
value
="Data Source=demo;Initial Catalog=pubs;User Id=sa;Password=pwd;" />
</
object>
<object name="SqlCommandObject"
singleton
="false"
type
="System.Data.SqlClient.SqlCommand, System.Data">
</object>
</objects>

With this example we define three objects; a Database, a SqlConnection and a SqlCommand. From this, we can provide Spring with our resource file and create an XmlObjectFactory that will allow our application to request services from it.

 

using System;
using
Spring.Core.IO;
using
Spring.Context;
using
Spring.Context.Support;
using
Spring.Objects.Factory;
using
Spring.Objects.Factory.Xml;

namespace
SpringDemo
{
class Program
{
static void Main(string[] args)
{
IResource resource
= new FileSystemResource("spring.xml");
IObjectFactory factory = new XmlObjectFactory(resource);
if
(factory != null)
{
IDatabase db
= factory.GetObject("Database") as IDatabase;
if
(db != null)
{
if (db.Connection != null)
{
Console.WriteLine(db.Connection.ConnectionString)
;
}
}
}
Console.WriteLine(
"Done");
Console.Read();
}
}
}

Note that when the "Database" is requested from our XmlObjectFactory, Spring identifies that it has two dependent objects, a SqlConnection and a SqlCommand object which need to be constructed prior to creating the "Database" object. In fact, the Database class has a constructor that takes an IDbConnection and IDbCommand. When the SqlConnection object is created, it uses the overloaded constructor to pass in a connection string which was defined as a constructor argument when the SqlConnection was created. Thus all dependent objects are created and passed into the Database object. Source code can be downloaded here.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Casting in C#

Friday, 16 December 2005 15:23 by nickp

Garrett Smith of ThoughtWorks discusses his thoughts on the two different ways of performing casting in C#. Garrett states that he prefers the C-style mechanism of casting as it "crashes early". Here's the distinction, when a cast is performed in C# using the C-style casting syntax such as the following:


SomeObject s = (SomeObject)hashTable[i];

An InvalidCastException will be thrown if the cast fails. So, with defensive programming techniques, we are encouraged to wrap our code in a try/catch block. Garrett then mentions that using the "as" operator to perform casting is problematic due to the fact that no exception is thrown. While this is true, when looking at the documentation for the "as" operator, it is noted that when the type conversion fails, null is returned. So in our particular case, we would want to write it as follows:

SomeObject s = hashTable[i] as SomeObject;
if
(s != null)
{
// continue on...
}
else
{
// decide what to do here.
}

Given this option, we now have the opportunity to control whether or not to create and throw an expensive exception or possibly dispatch control back to our application another way without continuing on with a null object reference. We could even further augment our check by using the “is” keyword to check to see if a type conversion will work before making the attempt to cast.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Test Driven Development on Google Groups

Saturday, 3 December 2005 01:05 by nickp
I have recently created a Google group for test driven development. If you want to discuss test driven development, regardless of the technology, feel free to stop by and join in!

http://groups.google.com/group/test-driven-development

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   Design Patterns | TDD
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Design by Contract with AOP Revisited

Wednesday, 19 October 2005 20:43 by nickp
Last night I posted a quick example of how we could place runtime requirements on methods. This is a common need by developers. I have since updated my example to clean it up a bit and make it more useable. The cleanup should make it much more extensible. In this example, I am placing two restrictions on our parameter. In order to call our function, the parameter being passed to it must be within both the minimum and maximum range defined in our PrologAttribute. What are your thoughts?

 

using System;
using
System.Reflection;
using
AopAlliance.Intercept;
using
Spring.Aop.Framework;
using
Spring.Aop.Interceptor;
using
Microsoft.VisualStudio.TestTools.UnitTesting;

namespace
DeveloperNotes
{
public class ConstraintInterceptor : IMethodInterceptor
{
public object Invoke(IMethodInvocation invocation)
{
MethodInfo mi
= invocation.Method;
if
(mi != null)
{
Object[] attrs
= mi.GetCustomAttributes(typeof(PrologAttribute), true);
if
(attrs != null && attrs.Length > 0)
{
bool results = false;
foreach
(PrologAttribute pl in attrs)
{
if (pl != null)
{
IEvaluator eval
= pl.Evaluator as IEvaluator;
if
(eval != null)
{
object[] args = invocation.Arguments;
results = eval.Evaluate(args[pl.Index]);
if
(!results)
break;
else
continue;
}
}
}
if(results)
return invocation.Proceed();
else
return null;
}
else
{
return invocation.Proceed();
}
}
return null;
}
}

public interface IEvaluator
{
bool Evaluate(object arg);
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple
=true, Inherited=true)]
public class PrologAttribute : Attribute
{
private int index;
public
IEvaluator evaluator;

public
PrologAttribute() { }

public PrologAttribute(int index, Type evalType, params object[] args)
{
this.Index = index;
Object obj = Activator.CreateInstance(evalType, args);
if
(obj != null)
this.evaluator = obj as IEvaluator;
}

public IEvaluator Evaluator
{
get { return evaluator; }
set { evaluator = value; }
}

public int Index
{
get { return index; }
set { index = value; }
}

public bool Evaluate(object arg)
{
return evaluator.Evaluate(arg);
}
}

public class StringLengthEvaluator : IEvaluator
{
private int min = 0;
private int
max = 0;

public
StringLengthEvaluator(int min, int max)
{
this.min = min;
this
.max = max;
}

public bool Evaluate(object arg)
{
int len = arg.ToString().Length;
return
(len <= max) && (len >= min);
}
}

public class ObjectFactory
{
public static K CreateObject<T, K>()
{
T obj
= Activator.CreateInstance<T>();
if
(obj != null)
{
ProxyFactory factory
= new ProxyFactory(obj);
factory.AddAdvice(new ConstraintInterceptor());
return
(K)factory.GetProxy();
}
return default(K);
}
}

public interface IPerson
{
void SayHello(string name);
}

public class Person : IPerson
{

[Prolog(
0, typeof(StringLengthEvaluator), 0, 5)]
public void SayHello(string name)
{
Console.WriteLine(
"Hello {0}", name);
}
}

class Program
{
static void Main(string[] args)
{
IPerson p
= ObjectFactory.CreateObject<Person, IPerson>();
if
(p != null)
{
p.SayHello(
"Nicholas");
p.SayHello("Nick");
}
Console.Read()
;
}
}
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   .NET | Design Patterns | AOP
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed