Look Ma! Real Proxies...

Wednesday, December 03, 2008 3:56:17 PM (Mountain Standard Time, UTC-07:00)

I took some time today to pull down the source code for SvnBridge today, and man, I was blown away. I started at Program.cs and made it to line 25 Bootstrapper.Start(). From there I went on to look at the hand rolled container, then the ProxyFactory.

In order for me to fully grasp the System.Runtime.Remoting API for creating proxies I had to re-write the code from SVN Bridge.... I just had too... it's just how I learn. It's like tracing over cartoons when you're a kid. I still do it!

In case you're interested, the attached code is the sample I put together that is derived from the source code of SvnBridge. If you haven't checked out the source for the project, you really should.

Pretty cool stuff.... Hopefully, this helps out anyone else who's just as curious

My reduced sample source code...

private static void Main(string[] args)
{
    var marshal_mathers = new Person("marshall mathers");
    var some_celebrity = ProxyFactory.Create<IPerson>(marshal_mathers, new MyNameIsSlimShadyInterceptor());
 
    try
    {
        var name = some_celebrity.what_is_your_name();
        name.should_be_equal_to("slim shady");
    }
    catch (Exception e)
    {
        Console.Out.WriteLine(e);
    }
    Console.Out.WriteLine("will the real slim shady please stand up...");
    Console.In.ReadLine();
}

#

Container Configuration

Sunday, November 09, 2008 8:19:45 PM (Mountain Standard Time, UTC-07:00)

In my last post I briefly mentioned how we were wiring some components in to our container.  The syntax looked like the following:

            container.AddProxyOf(
                new ReportPresenterTaskConfiguration(), 
                new ReportPresenterTask(
                    Lazy.Load<IReportDocumentBuilder>(),
                    Lazy.Load<IApplicationSettings>())
                    );

We're using Castle Windsor under the hood, but we have an abstraction over it that allows us to configure it as we like. Even switching the underlying implementation. Which we did, from our hand rolled container to Castle Windsor. The implementation of the above method looks as follows:

        public void AddProxyOf<Interface, Target>(IProxyConfiguration<Interface> configuration, Target instance)
            where Target : Interface
        {
            var builder = new ProxyBuilder<Interface>();
            configuration.Configure(builder);
            AddInstanceOf(builder.CreateProxyFor(instance));
        }

Wikipedia defines the Proxy design pattern as:

A proxy, in its most general form, is a class functioning as an interface to another thing.

To understand the ProxyBuilder<Interface> implementation you can checkout JP's strongly typed selective proxies. The "AddProxyOf" method creates an instance of a proxybuilder. It then passes it to the configuration to allow it to configure the proxy builder before building the proxy. Then it registers the proxy as a singleton in to the container.

    public interface IConfiguration<T>
    {
        void Configure(T item_to_configure);
    }
    public interface IProxyConfiguration<T> : IConfiguration<IProxyBuilder<T>>
    {
    }

In this case the proxy configuration looks like:

    public class ReportPresenterTaskConfiguration : IProxyConfiguration<IReportPresenterTask>
    {
        public void Configure(IProxyBuilder<IReportPresenterTask> builder)
        {
            var constraint = builder.AddInterceptor<DisplayProgressBarInterceptor>();
            constraint.InterceptOn.RetrieveAuditReport();
        }
    }

This guy adds a progress bar interceptor, that displays a progress bar as the report is getting generated via the "RetrieveAuditReport" method on the IReportPresenterTask.

#

Lazy Loaded Interceptors

Sunday, November 09, 2008 2:55:32 PM (Mountain Standard Time, UTC-07:00)

Patterns of Enterprise Application Architecture defines Lazy Load as:

An object that doesn't contain all of the data you need but knows how to get it.

 

A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....

container.AddProxyOf(
    new ReportPresenterTaskConfiguration(),
    new ReportPresenterTask(
        Lazy.Load<IReportDocumentBuilder>(),
        Lazy.Load<IApplicationSettings>())
    );

Lazy.Load<T> will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.

public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
{
    [Observation]
    public void should_forward_the_original_call_to_the_target()
    {
        target.should_have_been_asked_to(t => t.OneMethod());
    }

    protected override void establish_context()
    {
        target = dependency<ITargetObject>();

        test_container
            .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
            .will_return(target)
            .Repeat.Once();
    }

    protected override void because_of()
    {
        var result = Lazy.Load<ITargetObject>();
        result.OneMethod();
    }

    private ITargetObject target;
}

So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...

public static class Lazy
{
    public static T Load<T>() where T : class
    {
        return create_proxy_for<T>(create_interceptor_for<T>());
    }

    private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
    {
        Func<T> get_the_implementation = resolve.dependency_for<T>;
        return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
    }

    private static T create_proxy_for<T>(IInterceptor interceptor)
    {
        return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }
}

internal class LazyLoadedInterceptor<T> : IInterceptor
{
    private readonly Func<T> get_the_implementation;

    public LazyLoadedInterceptor(Func<T> get_the_implementation)
    {
        this.get_the_implementation = get_the_implementation;
    }

    public void Intercept(IInvocation invocation)
    {
        var method = invocation.GetConcreteMethodInvocationTarget();
        invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
    }
}

public static class func_extensions
{
    public static Func<T> memorize<T>(this Func<T> item) where T : class
    {
        T the_implementation = null;
        return () => {
                   if (null == the_implementation) {
                       the_implementation = item();
                   }
                   return the_implementation;
               };
    }
}

"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.

Download the source.

#

Opening Doors

Tuesday, November 04, 2008 1:27:12 PM (Mountain Standard Time, UTC-07:00)

joshka left a comment on my previous post that reads...

"... Can you talk about the Application Context and IKey stuff a little in a future post?"

The IKey<T> interface defines a contract for different keys that are put into a dictionary. It depends on the implementation of the key to know how to parse its value out of the dictionary.

public interface IKey<T>
{
    bool is_found_in(IDictionary items);
    T parse_from(IDictionary items);
    void remove_from(IDictionary items);
    void add_value_to(IDictionary items, T value);
}

An implementation of the key that we used for shoving an ISession into the HttpContext.Items collection is the TypedKey<T>. It creates a unique key based on type T.

internal class TypedKey<T> : IKey<T>
{
    public bool is_found_in(IDictionary items)
    {
        return items.Contains(create_unique_key());
    }

    public T parse_from(IDictionary items)
    {
        return (T) items[create_unique_key()];
    }

    public void remove_from(IDictionary items)
    {
        if (is_found_in(items))
        {
            items.Remove(create_unique_key());
        }
    }

    public void add_value_to(IDictionary items, T value)
    {
        items[create_unique_key()] = value;
    }

    public bool Equals(TypedKey<T> obj)
    {
        return !ReferenceEquals(null, obj);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof (TypedKey<T>)) return false;
        return Equals((TypedKey<T>) obj);
    }

    public override int GetHashCode()
    {
        return GetType().GetHashCode();
    }

    private string create_unique_key()
    {
        return GetType().FullName;
    }
}

It knows how to add a value in to the dictionary using it as the key, and how to parse values from the dictionary using it. The application context can be an adapter around the HttpContext, or a hand rolled context for win forms. An implementation on the web might look like....

public class WebContext : IApplicationContext
{
    public bool contains<T>(IKey<T> key)
    {
        return key.is_found_in(HttpContext.Current.Items);
    }

    public void add<T>(IKey<T> key, T value)
    {
        key.add_value_to(HttpContext.Current.Items, value);
    }

    public T get_value_for<T>(IKey<T> key)
    {
        return key.parse_from(HttpContext.Current.Items);
    }

    public void remove(IKey<ISession> key)
    {
        key.remove_from(HttpContext.Current.Items);
    }
}

When running your integration tests, you can swap out the implementation with an implementation specific to running unit tests.

#

Mocking Queryables

Tuesday, November 04, 2008 10:01:09 AM (Mountain Standard Time, UTC-07:00)

Recently, we've been mocking out IQueryable's as return values, which had led to setups that look like the following...

programs.setup_result_for(x => x.All()).Return(new List<IProgram> {active_program,inactive_program}.AsQueryable());

I just switched over to the following syntax... by creating an extension method.

programs.setup_result_for(x => x.All()).will_return(active_program,inactive_program);

The following are the extensions methods to make this work.

public static IMethodOptions<IEnumerable<R>> will_return<R>(this IMethodOptions<IEnumerable<R>> options,
                                                            params R[] items)
{
    return options.Return(items);
}

public static IMethodOptions<IQueryable<R>> will_return<R>(this IMethodOptions<IQueryable<R>> options,
                                                           params R[] items)
{
    return options.Return(new Query<R>(items));
}

and...

 internal classQuery<T> : IQueryable<T>
{
    private readonly IQueryable<T> query;

    public Query(params T[] items)
    {
        query = items.AsQueryable();
    }

    public Expression Expression
    {
        get { return query.Expression; }
    }

    public Type ElementType
    {
        get { return query.ElementType; }
    }

    public IQueryProvider Provider
    {
        get { return query.Provider; }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return query.GetEnumerator();
    }

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

 

Hope, this helps!

#

Intercepting Business Transactions

Monday, November 03, 2008 8:02:01 PM (Mountain Standard Time, UTC-07:00)

In Patterns of Enterprise Application Architecture, the Unit of Work design pattern is defined as:

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

NHibernate seems to have a great implementation of the unit of work, but understanding when to start and commit the unit of work without repeating yourself can be a little tricky. One thing we've been doing is starting a unit of work using an interceptor.

[Interceptor(typeof (IUnitOfWorkInterceptor))]
public class AccountTasks : IAccountTasks
{
    public bool are_valid(ICredentials credentials)
    {
        ...
    }
}

Account tasks is a service layer piece, that is decorated with an interceptor that will begin and commit a unit of work.

public interface IUnitOfWorkInterceptor : IInterceptor
{}

public class UnitOfWorkInterceptor : IUnitOfWorkInterceptor
{
    private readonly IUnitOfWorkFactory factory;

    public UnitOfWorkInterceptor(IUnitOfWorkFactory factory)
    {
        this.factory = factory;
    }

    public void Intercept(IInvocation invocation)
    {
        using (var unit_of_work = factory.create()) {
            invocation.Proceed();
            unit_of_work.commit();
        }
    }
}

The interceptor starts a new unit of work, before proceeding with the invocation. If no exceptions are raised the unit of work is committed. If a unit of work is already started, the unit of work factory returns an empty unit of work. This ensures that if a service layer method calls into another method that it doesn't start another unit of work.

public interface IUnitOfWorkFactory : IFactory<IUnitOfWork>
{}

public class UnitOfWorkFactory : IUnitOfWorkFactory
{
    private readonly IApplicationContext context;
    private readonly IDatabaseSessionFactory factory;
    private readonly TypedKey<ISession> key;

    public UnitOfWorkFactory(IApplicationContext context, IDatabaseSessionFactory factory)
    {
        this.context = context;
        this.factory = factory;
        key = new TypedKey<ISession>();
    }

    public IUnitOfWork create()
    {
        if (unit_of_work_is_already_started()) {
            return new EmptyUnitOfWork();
        }

        return create_a_unit_of_work().start();
    }

    private bool unit_of_work_is_already_started()
    {
        return context.contains(key);
    }

    private IUnitOfWork create_a_unit_of_work()
    {
        var session = factory.create();
        context.add(key, session);
        return new UnitOfWork(session, context);
    }
}

The implementation of the repository pulls the active session from the application context.

public class DatabaseRepository<T> : IRepository<T>
{
    private readonly IApplicationContext context;
    private readonly IKey<ISession> session_key;

    public DatabaseRepository(IApplicationContext context)
    {
        this.context = context;
        session_key = new TypedKey<ISession>();
    }

    public IQueryable<T> all()
    {
        return the_current_session().Linq<T>();
    }

    public void save(T item)
    {
        the_current_session().SaveOrUpdate(item);
    }

    public void delete(T item)
    {
        the_current_session().Delete(item);
    }

    private ISession the_current_session()
    {
        var current_session = context.get_value_for(session_key);
        if (null == current_session || !current_session.IsOpen) {
            throw new NHibernateSessionNotOpenException();
        }
        return current_session;
    }
}
For more information on Interceptors check out the Castle stack...

#

Collecting Errors

Tuesday, October 28, 2008 9:10:52 AM (Mountain Standard Time, UTC-07:00)

Validation is a tough subject. One that I'm constantly trying to think of better ways of doing. Some suggest that all validation should occur in the domain, and some prefer to check if the object is valid before proceeding. I lean towards the idea of not allowing your objects to enter an invalid state. So far the easiest approach I have found to do this is to raise meaningful exceptions in the domain to ensure this.

However, when there are several reasons why an object can be considered "invalid" and, those reasons need to be reflected in the UI, I haven't been able to figure out a clean way to do this in the domain. Suggestions are welcome.

Here's an approach that we've taken to some of our validation, when user input needs to be checked so that we can provide meaningful error messages to the end user.

First we have 2 core validation interfaces:

public interface IValidationResult
{
    bool IsValid { get; }
    IEnumerable<string> BrokenRules { get; }
}

and

public interface IValidation<T>
{
    IValidationResult Validate(T item);
}

The IValidation<T> is in essence a form of a Specification. Now to collect the errors we use a visitor. The following are the core visitor interfaces.

public interface IVisitor<T>
{
    void Visit(T item_to_visit);
}
public interface IValueReturningVisitor<TypeToVisit, TypeToReturn> : IVisitor<TypeToVisit>
{
    void Reset();
    TypeToReturn Result { get; }
}

We have an implementation of a IValueReturningVisitor that collects errors from visiting IValidations, then returns a validation result.

public class ErrorCollectingVisitor<T> : IValueReturningVisitor<IValidation<T>, IValidationResult>
{
    private readonly T item_to_validate;
    private readonly List<string> results;

    public ErrorCollectingVisitor(T item_to_validate)
    {
        this.item_to_validate = item_to_validate;
        results = new List<string>();
    }

    public void Visit(IValidation<T> item_to_visit)
    {
        var validation_result = item_to_visit.Validate(item_to_validate);
        if (!validation_result.IsValid)
        {
            results.AddRange(validation_result.BrokenRules);
        }
    }

    public void Reset()
    {
        results.Clear();
    }

    public IValidationResult Result
    {
        get { return new ValidationResult(results.Count == 0, results); }
    }
}

And a handy extension method for returning the value from visiting a set of validations.

public static Result ReturnValueFromVisitingAllItemsWith<TypeToVisit, Result>(
    this IEnumerable<TypeToVisit> items_to_visit, IValueReturningVisitor<TypeToVisit, Result> visitor)
{
    visitor.Reset();
    items_to_visit.Each(x => visitor.Visit(x));
    return visitor.Result;
}

An example of the usage for the visit can be seen below:

public IValidationResult Validate(IUser user)
{
    return userValidations
        .Select(x => x as IValidation<IUser>)
        .ReturnValueFromVisitingAllItemsWith(new ErrorCollectingVisitor<IUser>(user));
}

#

Droppin' Pennies on context specs...

Friday, August 15, 2008 8:07:20 AM (Mountain Standard Time, UTC-07:00)

First off I want to make it clear that I'm not a guru on the topic, but I do find it interesting. The topic of course is Context Based Specifications. I've seen an emergence in interest in writing context based specifications lately on the blogosphere. However, everyone seems to be advertising it slightly differently...

One of the things that our team tries to aim for is to keep technical language out of our specifications. They should be human readable sentences, not "Yoda" speak. This is crucial if we want non technical people to actually read our specs to make sure the code is inline with what the business is attempting to do. The goal, in our humble opinions, is to work closer towards the ubiquitous language. The benefit is that documentation is updated along with the code, because it is the code.

Something that reads..

when_the_account_controller_is_given_valid_arguments_on_the_register_account_action

Doesn't read as easy as:

when_registering_a_new_account

Another subtle change that our team made was to put the specs above establishing the context. In some cases it just seem to read better from top to bottom.

when_creating_a_new_account_for_a_user_with_a_valid_submission

- it_should_inform_the_user_that_the_account_was_created

- it_should_save_the_new_account_information

under_these_conditions

because_of

"It" being the system under test.

We don't always get it right, but by trying to drop the technical language we force ourselves to step away and think about the problem that we are ultimately trying to address.

Again... this is just my our 2 cents.

#

Parsing The Payload

Thursday, August 14, 2008 8:14:47 PM (Mountain Standard Time, UTC-07:00)

project_referencesSo this week we got to start working a brand spanking new MVC project. So far we're leveraging Castle Windsor, NHibernate, Fluent Nhibernate, and kind of running Linq to NHibernate. It's amazing how quickly you can get a project up and running in such a short amount of time. (BTW, Fluent NHibernate rocks!) When you're building off the trunk of these projects, it's almost like the contributors to all these great projects are extended members of the team. Thank you all!

Moving on... One of the things that are cool, but also slightly annoying, is how the MVC framework parses out items from the http payload to populate any input arguments on controller actions.

It's great how it just works, but it's a little annoying if it's under test and you have to add more fields, or remove fields from a form, then you have to go update the signature of the action then go update the test.... yada yada The changes just ripple down...

So one thing we tried out this week was to create a payload parser. What this guy does is take a DTO parse out the values for each of the properties on the DTO from the current requests payload and fill it. This makes it easy to package up the form parameters in a nicely packaged DTO and fire it off down to a service layer to do some work.

So instead of declaring an action method on a controller that looks like this, where the signature would have to change based on what fields are submitted on a form:

ViewResult register_new_account(string user_name, string first_name, string last_name)

We can write this...

public ViewResult register_new_account() {
    var accountSubmissionDTO = parser.MapFromPayloadTo<AccountSubmissionDTO>();
    var validationResult = task.Validate(accountSubmissionDTO);
    if (validationResult.IsValid) {
        task.Submit(accountSubmissionDTO);
        return View("Success", accountSubmissionDTO);
    }

    return View("Index", validationResult.BrokenRules);
}

This better allows us to adhere to the OCP. If we need to include additional fields on the form, we can add them to the form as long as the control name is the same as the name of the property on the DTO that it will be bound to. The implementation of the payload parser is quite primitive for now, but at the moment it's all that we needed.

First up the specs... simple enough, for now!

public class when_parsing_the_values_from_the_current_request_to_populate_a_dto : context_spec<IPayloadParser>
{
    [Test]
    public void should_return_a_fully_populated_dto()
    {
        result.Name.should_be_equal_to("adam");
        result.Age.should_be_equal_to(15);
        result.Birthdate.should_be_equal_to(new DateTime(1982, 11, 25));
        result.Id.should_be_equal_to(1);
    }

    protected override IPayloadParser UnderTheseConditions()
    {
        var current_request = Dependency<IWebRequest>();
        var payload = new NameValueCollection();

        payload["Name"] = "adam";
        payload["Age"] = "15";
        payload["Birthdate"] = new DateTime(1982, 11, 25).ToString();
        payload["Id"] = "1";

        current_request.setup_result_for(r => r.Payload).Return(payload);

        return new PayloadParser(current_request);
    }

    protected override void BecauseOf()
    {
        result = sut.MapFromPayloadTo<SomeDTO>();
    }

    private SomeDTO result;
}

public class when_parsing_values_from_the_request_that_is_missing_values_for_properties_on_the_dto :
    context_spec<IPayloadParser>
{
    private AccountSubmissionDTO result;

    [Test]
    public void it_should_apply_the_default_values_for_the_missing_properties()
    {
        result.LastName.should_be_null();
        result.EmailAddress.should_be_null();
    }

    protected override IPayloadParser UnderTheseConditions()
    {
        var current_request = Dependency<IWebRequest>();

        var payload = new NameValueCollection();

        payload["FirstName"] = "Joel";
        current_request.setup_result_for(x => x.Payload).Return(payload);

        return new PayloadParser(current_request);
    }

    protected override void BecauseOf()
    {
        result = sut.MapFromPayloadTo<AccountSubmissionDTO>();
    }
}

public class SomeDTO
{
    public long Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime Birthdate { get; set; }
}

The current implementation:

public interface IPayloadParser {
    TypeToProduce MapFromPayloadTo<TypeToProduce>() where TypeToProduce : new();
}

public class PayloadParser : IPayloadParser {
    private readonly IWebRequest current_request;

    public PayloadParser(IWebRequest current_request) {
        this.current_request = current_request;
    }

    public TypeToProduce MapFromPayloadTo<TypeToProduce>() where TypeToProduce : new() {
        var dto = new TypeToProduce();
        foreach (var propertyInfo in typeof (TypeToProduce).GetProperties()) {
            var value = Convert.ChangeType(current_request.Payload[propertyInfo.Name], propertyInfo.PropertyType);
            propertyInfo.SetValue(dto, value, null);
        }

        return dto;
    }
}

#

Ooops...

Monday, August 04, 2008 9:54:26 AM (Mountain Standard Time, UTC-07:00)

Mike left a comment on my last post on Windows Forms Databinding asking:

What do the tests look like?

On the ComboBox binding, why aren't you using adding the binding through DataBinding.Add?  With the way you have it now if you change the value the combobox is bound too it doesn't get pushed back to the screen.

Well Mr. Mike, on the view implementation there were no tests... *hang my head in shame* Yup, we went at it trying to understand how Windows Forms Data bindings works, but if we had gone at it test first, we would have found that leveraging the built-in data bindings are not very testable. It requires having a BindingContext setup, and in some cases the controls have to actually be displayed for the bindings to actually kick in. Second, if we had gone test first, we would have noticed the issue the Mike brought up in regards to the ComboBox.

Feeling a little guilty about publishing code that wasn't well thought out, I decided to go at it again, with a test first approach. The test started off very high level. I knew the API that I wanted to work with, in this case a fluent interface for defining a binding to a control. The end result was quite different..

    [Concern(typeof (Create))]
    public class when_binding_a_property_from_an_object_to_a_combo_box : context_spec {
        [Test]
        public void should_initialize_the_combo_box_with_the_current_value_of_the_property() {
            combo_box.SelectedItem.should_be_equal_to(baby_girl);
        }

        protected override void under_these_conditions() {
            combo_box = new ComboBox();
            thing_to_bind_to = Dependency<IAnInterface>();
            baby_girl = Dependency<IAnInterface>();
            baby_boy = Dependency<IAnInterface>();

            combo_box.Items.Add(baby_boy);
            combo_box.Items.Add(baby_girl);

            thing_to_bind_to
                .setup_result_for(t => t.Child)
                .Return(baby_girl);
        }

        protected override void because_of() {
            Create
                .BindingFor(thing_to_bind_to)
                .BindToProperty(t => t.Child)
                .BoundToControl(combo_box);
        }

        private ComboBox combo_box;
        private IAnInterface thing_to_bind_to;
        private IAnInterface baby_girl;
        private IAnInterface baby_boy;
    }

The end result doesn't leverage the Windows Forms databindings at all. It registers event handlers for events on the controls.

    public class ComboBoxPropertyBinding<TypeToBindTo, PropertyType> : IPropertyBinding<PropertyType> {
        private readonly IPropertyBinder<TypeToBindTo, PropertyType> binder;

        public ComboBoxPropertyBinding(ComboBox control, IPropertyBinder<TypeToBindTo, PropertyType> binder) {
            this.binder = binder;
            control.SelectedItem = binder.CurrentValue();
            control.SelectedIndexChanged +=
                delegate { binder.ChangeValueOfPropertyTo(control.SelectedItem.ConvertedTo<PropertyType>()); };
        }

        public PropertyType CurrentValue() {
            return binder.CurrentValue();
        }
    }

If you're interested in the rest of the source code download the source here. The moral of the story... Don't become complacent and take off your TDD hat, prematurely. In most cases it can, and should be, tested. Your design will probably come out much cleaner then going at the problem head on without tests to back you up. Not only that, but tests also give you extension points for making changes, and dealing with different contexts you probably wouldn't have thought of right off the bat.

#

Windows Forms Data Binding

Friday, August 01, 2008 10:35:09 PM (Mountain Standard Time, UTC-07:00)

A couple of weeks ago, Adam and I were pairing on a new screen in a windows forms application. He started showing me some stuff that he had learned about windows forms data bindings. I showed him a little bit of what JP tried to teach me, back in the Austin Nothin' But .NET boot camp, about Expressions and we decided to try a different way of binding domain object to screen elements in our application. The following is a method on the view that's invoked from a presenter. It's given an object from our model to display.

        public void Display(IActionPlan actionPlan)
        {
            Create
                .BindingFor(actionPlan)
                .BindToProperty(a => a.RecommendedAction)
                .BoundToControl(uxRecommendedAction);

            Create
                .BindingFor(actionPlan)
                .BindToProperty(a => a.AccountablePerson)
                .BoundToControl(uxAccoutablePerson);

            Create
                .BindingFor(actionPlan)
                .BindToProperty(a => a.EstimatedCompletionDate)
                .BoundToControl(uxEstimatedCompletionDate);

            Create
                .BindingFor(actionPlan)
                .BindToProperty(a => a.EstimatedStartDate)
                .BoundToControl(uxEstimatedStartDate);

            Create.BindingFor(actionPlan)
                .BindToProperty(a => a.RequiredResources)
                .BoundToControl(uxResourcesRequired);

            Create.BindingFor(actionPlan)
                .BindToProperty(a => a.Priority)
                .BoundToControl(uxPriority);
        }

Each of our controls are prefixed with "ux". What we did was bind different types of controls to property's on the object to display. This immediately changed that state of the object as the user filled out information on the screen. The BindToPropery() method is given the property on the object to bind too. The following was the implementation we came up with.

    public static class Create
    {
        public static IBinding<T> BindingFor<T>(T object_to_bind_to)
        {
            return new ControlBinder<T>(object_to_bind_to);
        }
    }
    public interface IBinding<TypeToBindTo>
    {
        IBinder<TypeToBindTo> BindToProperty<T>(Expression<Func<TypeToBindTo, T>> property_to_bind_to);
    }
    public interface IBinder<TypeOfDomainObject>
    {
        string NameOfTheProperty { get; }
        TypeOfDomainObject InstanceToBindTo { get; }
    }

The implementation of the BindToProperty method takes in an input argument of type Expression<Func<TypeOfDomainObject>>. This allows us to inspect the expression to parse out the name of the property the binding is for. It's like treating code as data. The IControlBinder implements two interfaces. One that's issued to client components (IBinding) which restricts what they can do with the type. (see above in the Create class) The second interface exposes enough information for extension methods to pull from to build bindings for specific windows forms controls.

    public interface IControlBinder<TypeToBindTo> : IBinding<TypeToBindTo>, IBinder<TypeToBindTo>
    {
    }

    public class ControlBinder<TypeOfDomainObject> : IControlBinder<TypeOfDomainObject>
    {
        public ControlBinder(TypeOfDomainObject instance_to_bind_to)
        {
            InstanceToBindTo = instance_to_bind_to;
        }

        public IBinder<TypeOfDomainObject> BindToProperty<TypeOfPropertyToBindTo>(
            Expression<Func<TypeOfDomainObject, TypeOfPropertyToBindTo>> property_to_bind_to)
        {
            var expression = property_to_bind_to.Body as MemberExpression;
            NameOfTheProperty = expression.Member.Name;
            return this;
        }

        public string NameOfTheProperty { get; private set; }

        public TypeOfDomainObject InstanceToBindTo { get; private set; }
    }

The BoundToControl overloads were put into extension methods, allowing others to create new implementations of bindings without having to modify the Control binder itself. The extension methods....

    public static class ControlBindingExtensions {
        public static IControlBinding BoundToControl<TypeOfDomainObject>(
            this IBinder<TypeOfDomainObject> binder,
            TextBox control) {
            var property_binder = new TextPropertyBinding<TypeOfDomainObject>(
                control,
                binder.NameOfTheProperty,
                binder.InstanceToBindTo);
            property_binder.Bind();
            return property_binder;
        }

        public static IControlBinding BoundToControl<T>(this IBinder<T> binder, RichTextBox box1) {
            var property_binder = new TextPropertyBinding<T>(box1,
                                                             binder.NameOfTheProperty,
                                                             binder.InstanceToBindTo);
            property_binder.Bind();
            return property_binder;
        }

        public static IControlBinding BoundToControl<T>(this IBinder<T> binder, ComboBox box1) {
            var property_binder = new ComboBoxBinding<T>(box1,
                                                         binder.NameOfTheProperty,
                                                         binder.InstanceToBindTo);
            property_binder.Bind();
            return property_binder;
        }

        public static IControlBinding BoundToControl<T>(this IBinder<T> binder, DateTimePicker box1) {
            var property_binder = new DatePickerBinding<T>(box1,
                                                           binder.NameOfTheProperty,
                                                           binder.InstanceToBindTo);
            property_binder.Bind();
            return property_binder;
        }
    }

For completeness... the control bindings...

    public class TextPropertyBinding<TypeToBindTo> : IControlBinding {
        private readonly Control control_to_bind_to;
        private readonly string name_of_the_propery_to_bind;
        private readonly TypeToBindTo instance_of_the_object_to_bind_to;

        public TextPropertyBinding(
            Control control_to_bind_to,
            string name_of_the_propery_to_bind,
            TypeToBindTo instance_of_the_object_to_bind_to
            ) {
            this.control_to_bind_to = control_to_bind_to;
            this.name_of_the_propery_to_bind = name_of_the_propery_to_bind;
            this.instance_of_the_object_to_bind_to = instance_of_the_object_to_bind_to;
        }

        public void Bind() {
            control_to_bind_to.DataBindings.Clear();
            control_to_bind_to.DataBindings.Add(
                "Text",
                instance_of_the_object_to_bind_to,
                name_of_the_propery_to_bind);
        }
    }
    public class ComboBoxBinding<TypeToBindTo> : IControlBinding {
        private readonly ComboBox control_to_bind_to;
        private readonly string name_of_the_propery_to_bind;
        private readonly TypeToBindTo instance_of_the_object_to_bind_to;

        public ComboBoxBinding(ComboBox control_to_bind_to,
                               string name_of_the_propery_to_bind,
                               TypeToBindTo instance_of_the_object_to_bind_to) {
            this.control_to_bind_to = control_to_bind_to;
            this.name_of_the_propery_to_bind = name_of_the_propery_to_bind;
            this.instance_of_the_object_to_bind_to = instance_of_the_object_to_bind_to;
        }

        public void Bind() {
            control_to_bind_to.SelectedIndexChanged +=
                delegate {
                    typeof (TypeToBindTo)
                        .GetProperty(name_of_the_propery_to_bind)
                        .SetValue(
                        instance_of_the_object_to_bind_to,
                        control_to_bind_to.Items[control_to_bind_to.SelectedIndex],
                        null);
                };
        }
    }
    public class DatePickerBinding<TypeToBindTo> : IControlBinding {
        private readonly DateTimePicker control_to_bind_to;
        private readonly string name_of_the_propery_to_bind;
        private readonly TypeToBindTo instance_of_the_object_to_bind_to;

        public DatePickerBinding(DateTimePicker control_to_bind_to,
                                 string name_of_the_propery_to_bind,
                                 TypeToBindTo instance_of_the_object_to_bind_to) {
            this.control_to_bind_to = control_to_bind_to;
            this.name_of_the_propery_to_bind = name_of_the_propery_to_bind;
            this.instance_of_the_object_to_bind_to = instance_of_the_object_to_bind_to;
        }

        public void Bind() {
            control_to_bind_to.DataBindings.Clear();
            control_to_bind_to.DataBindings.Add(
                "Value",
                instance_of_the_object_to_bind_to,
                name_of_the_propery_to_bind);
        }
    }

We found that using the fluent interface for creating bindings was pretty easy and made screen synchronization a breeze, however, our implementation wasn't the easiest thing to test. So far it's been good to us.

As a side note... go register for the Las Vegas course, it may cause you to love your job! Also, if you've already attended a boot camp, and you think you already know what the course is about, you have no idea, it keeps getting better and better.

#

Recursive Command

Friday, August 01, 2008 8:37:35 AM (Mountain Standard Time, UTC-07:00)

When building up a tree view that represents the directory structure of a file system, like the windows explorer, my first reaction was to use recursion to traverse the file system and build up a tree. I quickly found that doing something like that is a time consuming process, and required some optimization.

I came up with what I like to call the recursive command. Each Tree Node item on a tree view is bound to a command to execute. The command looks like this...

public interface ITreeNodeClickedCommand {
    void Execute(ITreeNode node);
}

When the command is executed, the command gets an opportunity to modify the state of the tree node that was clicked. In this case I wanted to lazy load the sub directories of a node that was clicked. The command implementation looks like this...

public interface IAddFoldersCommand : ITreeNodeClickedCommand {}

public class AddFoldersCommand : IAddFoldersCommand {
    private readonly DirectoryInfo the_current_directory;
    private bool has_executed;

    public AddFoldersCommand(DirectoryInfo the_current_directory) {
        this.the_current_directory = the_current_directory;
    }

    public void Execute(ITreeNode node) {
        if (!has_executed) {
            foreach (var directory in the_current_directory.GetDirectories()) {
                node.Add(new TreeNodeItem(directory.Name, ApplicationIcons.Folder, new AddFoldersCommand(directory)));
            }
        }
        has_executed = true;
    }
}

This command is executed each time the tree node that it is bound too is clicked, but will only build up the child tree node items once. Each of the child tree nodes are bound to a new instance of the same command. Hence, what I like to call the recursive command.

recursive_command

For more information on the command pattern check out WikiPedia's write up.

*Update 11:30 am MST, Friday, August. 01, 2008

After a little more inspection, I realized I was doing nothing more than just visiting each tree node item on the demand. Visitors are known to be great for recursive structures.... so ix-nay on the ecursive-ray ommand-kay.

The revised version:

public interface IAddFoldersToTreeVisitor : ITreeNodeVisitor
{
}

public class AddFoldersToTreeVisitor : IAddFoldersToTreeVisitor
{
    private readonly DirectoryInfo the_current_directory;
    private bool has_executed;
    private readonly IAddFilesToTreeVisitor add_files_visitor;
    private readonly IAddFoldersCommandFactory factory;

    public AddFoldersToTreeVisitor(DirectoryInfo the_current_directory, IAddFoldersCommandFactory factory,
                                   IAddFilesToTreeVisitor add_files_visitor)
    {
        this.the_current_directory = the_current_directory;
        this.factory = factory;
        this.add_files_visitor = add_files_visitor;
    }

    public void Visit(ITreeNode node)
    {
        if (!has_executed)
        {
            foreach (var directory in the_current_directory.GetDirectories())
            {
                node.Add(directory.Name, ApplicationIcons.Folder, factory.CreateFor(directory));
            }
            add_files_visitor.PreparedWith(the_current_directory);
            add_files_visitor.Visit(node);
        }
        has_executed = true;
    }
}

#

Holy Conditionals Batman...

Wednesday, July 09, 2008 7:17:32 PM (Mountain Standard Time, UTC-07:00)

In case you haven't you should read...

xUnit Test Patterns: Refactoring Test Code (The Addison-Wesley Signature Series)
by Gerard Meszaros

Read more about this book...

 

As a reminder, let's talk about a test smell described in the above mentioned book. It's called "Conditional Test Logic".

"Conditional Test Logic: A test contains code that may or may not be executed." xUnit Test Patterns

"A fully automated test is just code that verifies the behavior or other code. But if this code is complicated, how do we verify that it works properly?"

Warning bells should sound off in your head when you start to see looping or conditional constructs within a single unit test.

"Code that has only a single execution path always executes in exactly the same way. Code that has multiple execution paths presents much greater challenges and does not inspire as much confidence about its outcome."

For more information check this out...

Basically Ignore Logic... that could cause multiple execution paths within a single unit test.

#

Splish, Splash... I was..

Wednesday, July 09, 2008 9:18:50 AM (Mountain Standard Time, UTC-07:00)

Building a splash screen. (err... not taking a bath)

So one requirement we had this week was to add a splash screen to the project we're working on. My knowledge of threading is weak, so bare with me. As our application started to grow, the start up times started to grow so a splash screen is supposed to be a queue to the user that yes the app is running.

This is what the end result ended up...

using (new BackgroundThread(new DisplaySplashScreenCommand()))
{
    ApplicationStartUpTask.ApplicationBegin();
}

So what's happening is the Splash screen is loaded on a background thread, while the application start up continues on the main thread. When the application start up is finished, the background thread disposes of the command that it's executing. In this case it starts fading the splash screen away.

Here's the core interface that made this happen.

public interface ICommand
{
    void Execute();
}
public interface IDisposableCommand : ICommand, IDisposable
{
}
public interface IBackgroundThread : IDisposable
{
}

This is a pretty simple solution (IMHO). The actual splash screen is just a win form, that starts a timer and adjusts the opacity when it's asked to display, then fade away when it's asked to hide.

public partial class SplashScreen : Form, ISplashScreen
{
    private Timer timer;

    public SplashScreen()
    {
        InitializeComponent();
        Visible = false;
    }

    public void DisplayTheSplashScreen()
    {
        ApplyWindowStyles();
        StartFadingIn();
    }

    public void HideTheSplashScreen()
    {
        StartFadingOut();
    }

    private void StartFadingIn()
    {
        Opacity = .0;
        timer = new Timer {Interval = 50};
        timer.Tick += ((sender, e) => { if (Opacity < 1) Opacity += .05; });
        timer.Start();
        ShowDialog();
    }

    private void StartFadingOut()
    {
        if(timer != null && timer.Enabled){
            timer.Stop();
        }
        timer = new Timer {Interval = 50};
        timer.Tick += (delegate {
                               if (Opacity > 0) {
                                   Opacity -= .1;
                               }
                               else {
                                   timer.Stop();
                                   Close();
                               }
                           });
        timer.Start();
    }

    private void ApplyWindowStyles()
    {
        BackgroundImage = Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images/splash.jpg"));
        FormBorderStyle = FormBorderStyle.None;
        StartPosition = FormStartPosition.CenterScreen;
        ClientSize = BackgroundImage.Size;
        TopMost = true;
    }
}

For starting and running a non-blocking background thread, we're using the BackgroundWorker class which takes care of thread synchronization. (This comes in handy for synchronizing UI elements)

public class BackgroundThread : IBackgroundThread
{
    private readonly BackgroundWorker worker_thread;

    public BackgroundThread(IDisposableCommand command)
    {
        worker_thread = new BackgroundWorker();
        worker_thread.DoWork += delegate { command.Execute(); };
        worker_thread.Disposed += delegate { command.Dispose(); };
        worker_thread.RunWorkerAsync();
    }

    public void Dispose()
    {
        worker_thread.Dispose();
    }
}

Just so you get the rest of the code, here's the DisplaySplashScreenCommand, although I'm sure it was obvious.

public class DisplaySplashScreenCommand : IDisposableCommand
{
    private ISplashScreen splash_screen;

    public DisplaySplashScreenCommand() : this(new SplashScreen())
    {
    }

    public DisplaySplashScreenCommand(ISplashScreen splash_screen)
    {
        this.splash_screen = splash_screen;
    }

    public void Execute()
    {
        splash_screen.DisplayTheSplashScreen();
    }

    public void Dispose()
    {
        splash_screen.HideTheSplashScreen();
    }
}

Hope this helps anyone out there trying to implement a splash screen. PS. I can't stress the fact that my knowledge of Threading is limited, so if you know of a cleaner implementation... Please, please hook a brotha up!

The end result looks like...

splash_screen

#

Raise Up

Tuesday, July 08, 2008 6:03:41 PM (Mountain Standard Time, UTC-07:00)

So I got a phone call this morning that went something like this....

"Yo mO, what's happenin' homie?", voice on the phone.

"Ye'.... I'm just slingin some code wit my compadre, G. What's crackin'?", says mo!

"So word on the street is that you're slingin' some made Rhino Mocks 3 dot 5 ish? So lemme asks you, how do you bust out some event raisin' with the new ish?"

My response... "I gots no clue my man, no clue!"

After some quick digging here's what I found... (Please remember this is a contrived example!)

The old school way...

[TestFixture]
public class AnonymousPresenterTest {
    private IView view;
    private MockRepository mockery;
    private ITask task;

    [SetUp]
    public void SetUp() {
        mockery = new MockRepository();
        view = mockery.DynamicMock<IView>();
        task = mockery.DynamicMock<ITask>();
    }

    public IPresenter CreateSUT() {
        return new AnonymousPresenter(view, task);
    }

    [Test]
    public void ShouldDoSomethingUseful() {
        IEventRaiser raiser = null;
        using (mockery.Record()) {
            view.Load += null;
            raiser = LastCall.GetEventRaiser();

            Expect
                .Call(task.AllProvinces())
                .Return(new List<IProvince>());
        }

        using (mockery.Playback()) {
            CreateSUT();
            raiser.Raise(null, EventArgs.Empty);
        }
    }
}

Here's the new way.. that I quickly Googled for...

[Concern(typeof(AnonymousPresenter))]
public class when_the_view_is_first_loaded : context_spec<IPresenter> {
    private IView view;
    private ITask task;

    protected override IPresenter UnderTheseConditions() {
        view = Dependency<IView>();
        task = Dependency<ITask>();
        return new AnonymousPresenter(view, task);
    }

    protected override void BecauseOf() {
        view.Raise(v => v.Load += null, view, EventArgs.Empty);
    }

    [Test]
    public void should_do_something_useful() {
        task.should_have_been_asked_to(t => t.AllProvinces());
    }
}

So there you have it. Enjoy..

P.S.

I found the usage on Ayende's wiki here. Also, I am not a Rhino.Mocks guru, nor do I want to be, and yes the phone conversation was not as interesting as was previously illustrated.

#

Mocking Rhinos...

Sunday, July 06, 2008 8:07:42 PM (Mountain Standard Time, UTC-07:00)

I mean Grokking Rhino Mocks. My usage of Rhino Mocks has changed quite a bit since I first started using it a year ago, as well as the way I write tests.

First it was like this:

[TestFixture]
public class ConsoleTest {
    private MockRepository mockery;
    private IReportPresenter presenter;

    [SetUp]
    public void SetUp() {
        mockery = new MockRepository();
        presenter = mockery.CreateMock<IReportPresenter>();
    }

    [TearDown]
    public void TearDown() {
        mockery.VerifyAll();
    }

    [Test]
    public void ShouldInitializeTheReportPresenter() {
        var commandLineArguments = new[] {"blah"};
        presenter.Initialize();

        mockery.ReplayAll();
        new Console(presenter).Execute(commandLineArguments);
    }
}

Then it evolved to this...

[TestFixture]
public class ConsoleTest {
    private MockRepository mockery;
    private IReportPresenter presenter;

    [SetUp]
    public void SetUp() {
        mockery = new MockRepository();
        presenter = mockery.DynamicMock<IReportPresenter>();
    }

    [Test]
    public void ShouldInitializeTheReportPresenter() {
        var commandLineArguments = new[] {"blah"};

        using (mockery.Record()) {
            presenter.Initialize();
        }
        using (mockery.Playback()) {
            CreateSUT().Execute(commandLineArguments);
        }
    }

    private IConsole CreateSUT() {
        return new Console(presenter);
    }
}

Then for a short time I tried this...

[TestFixture]
public class when_giving_the_console_valid_arguments {
    private IReportPresenter presenter;

    [SetUp]
    public void SetUp() {
        presenter = MockRepository.GenerateMock<IReportPresenter>();
    }

    [Test]
    public void should_initialize_the_report_presenter() {
        var commandLineArguments = new[] {"blah"};
        CreateSUT().Execute(commandLineArguments);
        presenter.AssertWasCalled(p => p.Initialize());
    }

    private IConsole CreateSUT() {
        return new Console(presenter);
    }
}

Now I'm trying this...

[Concern(typeof (Console))]
public class when_the_console_is_given_valid_console_arguments : context_spec<IConsole> {
    private string[] command_line_arguments;
    private IReportPresenter presenter;

    protected override IConsole UnderTheseConditions() {
        command_line_arguments = new[] {"path", "testfixtureattributename"};
        presenter = Dependency<IReportPresenter>();

        return new Console(presenter);
    }

    protected override void BecauseOf() {
        sut.Execute(command_line_arguments);
    }

    [Test]
    public void should_initialize_the_report_presenter() {
        presenter.should_have_been_asked_to(p => p.Initialize());
    }
}

Now I'm generating reports from my tests specs using this. I wonder what's next...

#

In Depth With C#

Sunday, July 06, 2008 7:45:12 PM (Mountain Standard Time, UTC-07:00)

Tonight I finished reading...

C# in Depth: What you need to master C# 2 and 3
by Jon Skeet

Read more about this book...

This was an amazing book, and definitely offers a great in depth look at the C# language. Most importantly it answered a lot of my questions about elements introduced in C# 3.0, and taught me things I didn't know about C# 1.0. If you're looking for information on the following items, then this book is definitely for you.

  • Expression
  • IQueryable
  • IQueryProvider
  • Lamba's
  • Type Inferencing

Thanks JP for recommending this book!

Here are a few gems that I picked from this book.

Delegates

"You rarely see an explicit call to Delegate.Combine in C# code - usually the + and += operators are used."

var x = new EventHandler(delegate { });
var y = new EventHandler(delegate { });
x += y;
x = x + y;// same as above
x = (EventHandler) Delegate.Combine(x, y);// same as above

Static vs Dynamic Typing

"C# is statically typed: each variable is of a particular type, and that type is known at compile time. The alternate to static typing is dynamic typing, which can take a variety of guises. "

Explicit vs. Implicit Typing

"The distinction between explicit typing and implicit typing is only relevant in statically typed languages. With explicitly typing, the type of every variable must be explicitly stated in the declaration. Implicit typing allows the compiler to infer the type of the variable based on its use."

Covariant vs. Incovariant

object[] stuff = new string[]{"blah"}; // valid and is an example of covariance
List<object> more_stuff = new List<string>();// invalid and is an example of incovariance

Fluent Interfaces

Jon, the author, mentions a blog post by Anders Noras on Planning a fluent interface

Here's an example of a fluent interface for building menu's that I've been playing with.

CreateA.MenuItem()
.Named("&Close")
.BelongsTo(MenuGroups.File)
.CanBeClickedWhen(m => task.IsThereAProtocolSelected())
.WhenClickedExecute(closeCommand)
.Build();

Readability

"When it comes to getting the broad sweep of code, what is required is 'readability of results' - I want to know what the code does, but I don't care how it does it right now."

There's a lot of information on IQueryables, Expression Trees, and other goodness in this book. This is a great book and definitely worth reading, especially if you're as interested in the C# language as I am.

#

A Strongly Typed SQL Query API... almost!

Tuesday, June 10, 2008 9:19:17 PM (Mountain Standard Time, UTC-07:00)

An idea the team an I had today, was to build a more fluent interface for creating dynamic SQL queries. Here's what I mean:

[TestFixture]
public class when_creating_an_insert_query_for_two_or_more_columns {
    [Test]
    public void should_return_the_correct_sql() {
        var query = Insert.Into<CustomersTable>()
            .ValueOf("mo").ForColumn(c => c.FirstName())
            .And()
            .ValueOf("khan").ForColumn(c => c.LastName())
            .End();

        var expected =
            "INSERT INTO Customers ( FirstName, LastName ) VALUES ( @FirstName, @LastName );";
        query.ToSql().ShouldBeEqualTo(expected);
    }
}

It's the responsibility of the query object to prepare the command with the command parameter names and values, so in this test I'm just focused on the raw sql. One of the benefits of this API, is that it's strongly typed, so you can't stick a string in a column represented by a long.

For example, Imagine a customers table that looks like this:

public class CustomersTable : IDatabaseTable {
    public string Name() {
        return "Customers";
    }

    public IDatabaseColumn<long> Id() {
        return new DatabaseColumn<long>("Id");
    }

    public IDatabaseColumn<string> FirstName() {
        return new DatabaseColumn<string>("FirstName");
    }

    public IDatabaseColumn<string> LastName() {
        return new DatabaseColumn<string>("LastName");
    }
}

Here's what we've got so far for contracts...

public class Insert {
    public static ITableSelector<Table> Into<Table>() where Table : IDatabaseTable {
        return new TableSelector<Table>();
    }
}

public interface ITableSelector<Table> {
    IColumnSelector<Table, ColumnType> ValueOf<ColumnType>(ColumnType value);
}

public interface IColumnSelector<Table, ColumnType> {
    IChainedSelector<Table> ForColumn<TColumn>(Func<Table, TColumn> columnSelection)
        where TColumn : IDatabaseColumn<ColumnType>;
}

public interface IChainedSelector<Table> {
    ITableSelector<Table> And();
    IQuery End();
}

And here's as far as we got with the implementation...

public class TableSelector<Table> : ITableSelector<Table> where Table : IDatabaseTable {
    public IColumnSelector<Table, T> ValueOf<T>(T value) {
        return new ColumnSelector<Table, T>(value);
    }
}

public class ColumnSelector<Table, T> : IColumnSelector<Table, T> where Table : IDatabaseTable {
    private readonly T value;

    public ColumnSelector(T value) {
        this.value = value;
    }

    public IChainedSelector<Table> ForColumn<TColumn>(Func<Table, TColumn> columnSelection)
        where TColumn : IDatabaseColumn<T> {
        var table = Activator.CreateInstance<Table>();
        return new ChainedSelector<Table, T, TColumn>(
            table,
            value,
            columnSelection(table)
            );
    }
}

public class ChainedSelector<Table, Value, Column> : IChainedSelector<Table>
    where Table : IDatabaseTable
    where Column : IDatabaseColumn<Value> {
    private readonly Table table;
    private readonly Value value;
    private readonly Column column;

    public ChainedSelector(Table table, Value value, Column column) {
        this.table = table;
        this.value = value;
        this.column = column;
    }

    public ITableSelector<Table> And() {
        throw new NotImplementedException();
    }

    public IQuery End() {
        var builder = new InsertStatementBuilder(table.Name());
        builder.Add(column, value);
        return builder.EndQuery();
    }
    }

The most important piece is still missing, and that's implementing the "And()" method on ChainedSelector... and finishing off the End method. I'm drawing a blank.. Thoughts are appreciated!

 

 

#

XML Element Enumerable Take 2

Friday, May 30, 2008 8:07:53 AM (Mountain Standard Time, UTC-07:00)

A couple of days ago I posted something on an XmlEnumerable. An object that knows how to traverse an XML document in a linear form. After talking with Adam, he suggested that I simplify the implementation with a little XPath action.

public class XmlElementEnumerable : IEnumerable<IXmlElement> {
    private XmlElement rootElement;
    private IMapper<XmlElement, IXmlElement> mapper;

    public XmlElementEnumerable(XmlElement rootElement) {
        this.rootElement = rootElement;
        mapper = new XmlElementMapper();
    }

    public IEnumerator<IXmlElement> GetEnumerator() {
        foreach (var node in rootElement.SelectNodes("//*")) {
            yield return mapper.MapFrom(node.DownCastTo<XmlElement>());
        }
    }

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

Diving a little deeper, I think using XPath expressions are probably a lot more efficient for traversing a document.

#

Traversing Xml

Wednesday, May 28, 2008 5:44:31 PM (Mountain Standard Time, UTC-07:00)

If you ever need to traverse each xml element in an xml document , you may want to implement your own XmlEnumerable. I've had some issues with the .NET XML API recently. The built in .NET XmlElement implements the non generic IEnumerable which means you've got to foreach through a bunch of objects.

foreach (object o in rootElement) {
    
}

This kind of scares me a bit because of the Xml object hierarchy. The reason being, there are several sub classes of XmlNode, and trying to understand this object hierarchy is not interesting to me.

xml_node_derivatives

Rather than having to check if each item is an Xml element, we just created our own abstraction that we prefer to work with, and map from the framework XmlElement to our own IXmlElement.

public interface IXmlElement : IEquatable<IXmlElement>, IEnumerable<IXmlElement> {
    string Name();
    string ToXml();
}

 

 

Let's say you need to traverse and Xml that looks like this:

@"<root>
    <GrandParent>
        <Parent>
            <Child>
                <GrandChild>
                </GrandChild>
            </Child>
        </Parent>
    </GrandParent>
    <GrandParent>
        <Parent>
            <Child>
                <GrandChild>
                </GrandChild>
            </Child>
        </Parent>
    </GrandParent>
    <Cousin>
    </Cousin>
</root>"
);

If we were to traverse this document we would expect to find 10 elements

[Test]
public void should_traverse_through_each_element() {
    CreateSUT().Count().ShouldBeEqualTo(10);
}

[Test]
public void should_contain_one_root_element() {
    CreateSUT()
        .Where(x => x.Name().Equals("root"))
        .Count()
        .ShouldBeEqualTo(1);
}

[Test]
public void should_contain_two_grand_parents() {
    CreateSUT()
        .Where(x => x.Name().Equals("GrandParent"))
        .Count()
        .ShouldBeEqualTo(2);
}

We could walk this xml structure and query it, using an API that we prefer by building our own IEnumerable<IXmlElement> and extension methods for querying.

public class XmlElementEnumerable : IEnumerable<IXmlElement> {
    private XmlElement rootElement;
    private IMapper<XmlElement, IXmlElement> mapper;

    public XmlElementEnumerable(XmlElement rootElement) {
        this.rootElement = rootElement;
        mapper = new XmlElementMapper();
    }

    public IEnumerator<IXmlElement> GetEnumerator() {
        yield return mapper.MapFrom(rootElement);
        foreach (var element in RecursivelyWalkThrough(rootElement)) {
            yield return mapper.MapFrom(element);
        }
    }

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

    private IEnumerable<XmlElement> RecursivelyWalkThrough(XmlNode element) {
        if (element.HasChildNodes) {
            foreach (var childNode in element.ChildNodes) {
                if (childNode is XmlElement) {
                    yield return childNode.DownCastTo<XmlElement>();
                    foreach (var xmlElement in RecursivelyWalkThrough(childNode.DownCastTo<XmlElement>())) {
                        yield return xmlElement;
                    }
                }
            }
        }
    }
}

Now you can traverse your own xml data structures using a more strongly typed API that suits your needs. For example:

public class RawXmlElement : IXmlElement {
    public RawXmlElement(string rawXml) {
        _rawXml = rawXml;
    }

    public string ToXml() {
        return _rawXml;
    }

    public string Name() {
        return Parse.Xml(this).ForItsName();
    }

    public bool Equals(IXmlElement other) {
        return other != null && other.ToXml().Equals(_rawXml);
    }

    public override bool Equals(object obj) {
        return ReferenceEquals(this, obj) || Equals(obj as IXmlElement);
    }

    public override int GetHashCode() {
        return _rawXml != null ? _rawXml.GetHashCode() : 0;
    }

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

    public IEnumerator<IXmlElement> GetEnumerator() {
        return new XmlEnumerable(this).GetEnumerator();
    }

    public override string ToString() {
        return _rawXml;
    }

    private readonly string _rawXml;
}

Or...

public class SingleXmlElement<T> : IXmlElement {
    public SingleXmlElement(string elementName, T elementValue) {
        this.elementName = elementName;
        this.elementValue = elementValue;
    }

    public string ToXml() {
        return ToString();
    }

    public string Name() {
        return Parse.Xml(this).ForItsName();
    }

    public IEnumerator<IXmlElement> GetEnumerator() {
        return new XmlEnumerable(this).GetEnumerator();
    }

    public override string ToString() {
        return string.Format("<{0}>{1}</{0}>", elementName, elementValue);
    }

    public bool Equals(IXmlElement other) {
        return other != null && ToString().Equals(other.ToXml());
    }

    public override bool Equals(object obj) {
        return ReferenceEquals(this, obj) || Equals(obj as IXmlElement);
    }

    public override int GetHashCode() {
        return
            (elementName != null ? elementName.GetHashCode() : 0) +
            29*(elementValue != null ? elementValue.GetHashCode() : 0);
    }

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

    private readonly string elementName;
    private readonly T elementValue;
}

Hopefully, this helps someone else who's drowning in xml!

#

Slingin' Menus

Sunday, May 25, 2008 8:21:48 PM (Mountain Standard Time, UTC-07:00)

I received a question the other day on building menu's in a win forms application. I wasn't sure of a clean way of doing it, so I thought I would put together a sample app to see if I could come up with something. I'm not sure I'm completely happy with what I've got so far, but my goal was to be able to drop in new menu items, and menu groups without a lot of ceremony and configuration.

The guts of it depends on castle windsor to glue most of the pieces together using the mass component registration api. I found it really hard to test, but was please with how easy it just kind of worked!

public class WindsorContainerFactory : IWindsorContainerFactory {
    private static IWindsorContainer container;
    private IComponentExclusionSpecification criteriaToSatisfy;

    public WindsorContainerFactory() : this(new ComponentExclusionSpecification()) {}

    public WindsorContainerFactory(IComponentExclusionSpecification criteriaToSatisfy) {
        this.criteriaToSatisfy = criteriaToSatisfy;
    }

    public IWindsorContainer Create() {
        if (null == container) {
            container = new WindsorContainer();
            container.Register(
                AllTypes
                    .Pick()
                    .FromAssembly(GetType().Assembly)
                    .WithService
                    .FirstInterface()
                    .Unless(criteriaToSatisfy.IsSatisfiedBy)
                    .Configure(
                    delegate(ComponentRegistration registration) {
                        this.LogInformational("{1}-{0}", registration.Implementation, registration.ServiceType.Name);
                        if (registration.Implementation.GetInterfaces().Length == 0) {
                            registration.For(registration.Implementation);
                        }
                    })
                );
        }
        return container;
    }
}

The other neat piece that kind of made things easy to get up and running was the concept of a default repository. (I picked up this bit of knowledge from Oren at DevTeach.)

public class DefaultRepository<T> : IRepository<T> {
    private IDependencyRegistry registry;

    public DefaultRepository(IDependencyRegistry registry) {
        this.registry = registry;
    }

    public IEnumerable<T> All() {
        return registry.AllImplementationsOf<T>();
    }
}

This was the only implementation of a repository in the system, and it was used for a IRepository<IMenuItem> and IRepository<ISubMenu>. I just created a new implementation of an IMenuItem or ISubMenu and it picked it up via Windsor's mass component registration.

public class MainMenuPresenter : IMainMenuPresenter {
    private readonly IMainMenuView mainMenu;
    private readonly IRepository<ISubMenu> repository;
    private readonly ISubMenuItemComparer comparer;

    public MainMenuPresenter(IMainMenuView mainMenu,
                             IRepository<ISubMenu> repository,
                             ISubMenuItemComparer comparer) {
        this.mainMenu = mainMenu;
        this.repository = repository;
        this.comparer = comparer;
    }

    public void Initialize() {
        foreach (var subMenuToAddToMainMenu in repository.All().SortedUsing(comparer)) {
            mainMenu.Add(subMenuToAddToMainMenu);
        }
    }
}

I also spent a little time playing with Gallio. I had some issue with conflicts between the version of Castle.Microkernel that I was toying with and the one that comes with gallio. I wasn't able to resolve the issue, but after looking into the concept behind Gallio, I like the idea. Kind of neat stuff!

Here's what I came up... Thank you Mr. JP for the inspiration!

Source can be downloaded here!

I can't stress how many ideas in this project came from concepts learned from the Nothin' But .NET boot camp. If you're in the area, you should definitely go check out the Vancouver course coming up next month!

#

Some More Refactorings...

Thursday, May 22, 2008 8:22:51 PM (Mountain Standard Time, UTC-07:00)

A great book to read is...

Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

Read more about this title...

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."

"The first time you do something, you just do it. The second time you something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor."

Introduce Local Extension: A server class you are using needs several additional methods, but you can't modify the class.

Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original.

E.g From this...

    public interface IController{
        void Execute();
    }
    
    public class Controller : IController {
        protected void RenderView(string name, object data){
            //... note that this is a protected method
        }
        
        public void Execute(){
            //...
        }
    }

To this...

    public interface IViewRenderer{
        void Render<T>(string name, T data);
    }
    
    public class LocalExtensionController : Controller, IViewRenderer {
        public void Render<T>(string name, T data){
            RenderView(name, data);
        }
    }

Replace Conditional with Polymorphism: You have a conditional that chooses different behavior depending on the type of an object.

Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract.

E.g From this...

    public class Bird{
        public Bird(BirdType type){
            _type = type;
        }
        
        public double GetSpeed(){
            switch(_type){
                case BirdType.EUROPEAN:
                    return 5;
                
                case BirdType.AFRICAN:
                    return 10;
                    
                case BirdType.NORWEGIAN_BLUE:
                    return 20;
            }
            throw new ArgumentException();
        }
        
        private BirdType _type;        
    }
    
    public enum BirdType{
        EUROPEAN,
        AFRICAN,
        NORWEGIAN_BLUE
    }

To this...

    public interface IBird{
        double GetSpeed();
    }
    
    public class EuropeanBird : IBird {
        public double GetSpeed(){
            return 5;
        }
    }

    public class AfricanBird : IBird {
        public double GetSpeed() {
            return 10;
        }
    }

    public class NorwegianBlueBird : IBird {
        public double GetSpeed() {
            return 20;
        }
    }        

#

Tiny Units Of Work

Tuesday, May 20, 2008 12:21:08 PM (Mountain Standard Time, UTC-07:00)

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this book...

Defines Unit of Work as:

"Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." - PoEAA

I've been playing with some different ideas on how you can implement a unit of work in a win forms application.

Here was the idea of the usage:

public void SomeMethod() {
    using (var unitOfWork = UnitOfWork.StartFor<IPerson>())
    {
        var stacey = new Person("stacey");
        var veronica = new Person("veronica");
        var betty = new Person("betty");

        stacey.NewNumberIs("312-7467");

        unitOfWork.Commit();
    }
}

When the unit of work is asked to commit the new and modified instance would be committed to the person repository, in this case my imaginary black book.

public class BlackBook : IRepository<IPerson> {
    private IList<IPerson> associates;

    public BlackBook() : this(new List<IPerson>()) {
    }

    public BlackBook(IList<IPerson> associates) {
        this.associates = associates;
    }

    public void Add(IPerson newAssociate) {
        associates.Add(newAssociate);
    }

    public void Update(IPerson updatedAssociate) {
    }
}

Here's how it works... Person inherits from "DomainSuperType<T>". In the layer super type the no argument constructor registers itself with the current unit of work. I really don't like this because it makes all the domain objects aware of the surrounding infrastructure, and makes it much more difficult to test.

Next all components have to be decorated with the "Serializable" attribute, so that I could manage dirty object tracking. This also sucks...

[Serializable]
public class DomainSuperType<T> where T : class {
    public DomainSuperType() {
        UnitOfWork.StartFor<T>().Register(this as T);
    }
}
public interface IPerson
{
    void NewNumberIs(string newNumber);
}

[Serializable]
public class Person : DomainSuperType<IPerson>, IPerson {
    private string name;
    private string knownPhoneNumber;

    public Person(string name) {
        this.name = name;
    }

    public void NewNumberIs(string newNumber) {
        knownPhoneNumber = newNumber;
    }
}

The unit of work delegates to a registry of units of work to retrieve the unit of work applicable to type <T>....

public static class UnitOfWork {
    public static IUnitOfWork<T> StartFor<T>() {
        return Resolve.DependencyFor<IUnitOfWorkRegistry>().StartUnitOfWorkFor<T>();
    }
}

The unit of work registry creates a unit of work for type <T> if one hasn't been started yet. Otherwise returns the already started unit of work. This registry is similar to an identity map using type T as the identifier.

public class UnitOfWorkRegistry : IUnitOfWorkRegistry {
    private IDictionary<Type, object> unitsOfWork;
    private IUnitOfWorkFactory factory;

    public UnitOfWorkRegistry(IUnitOfWorkFactory factory) {
        this.factory = factory;
        unitsOfWork = new Dictionary<Type, object>();
    }

    public IUnitOfWork<T> StartUnitOfWorkFor<T>() {
        if (unitsOfWork.ContainsKey(typeof (T)))
        {
            return (IUnitOfWork<T>) unitsOfWork[typeof (T)];
        }
        var unitOfWork = factory.CreateFor<T>();
        unitsOfWork.Add(typeof (T), unitOfWork);
        return unitOfWork;
    }
}

The unit of work factory leverages the dependency resolver to retrieve an implementation of the repository applicable to type T.

public class UnitOfWorkFactory : IUnitOfWorkFactory {
    private IDependencyResolver resolver;

    public UnitOfWorkFactory(IDependencyResolver resolver) {
        this.resolver = resolver;
    }

    public IUnitOfWork<T> CreateFor<T>() {
        return new WorkSession<T>(resolver.GetMeAnImplementationOf<IRepository<T>>());
    }
}

Each time the unit of work factory is asked to create a new unit of work it creates a fresh instance of a work session.

public class WorkSession<T> : IUnitOfWork<T> {
    public WorkSession(IRepository<T> repository) : this(repository, new ObjectToRegisteredObjectMapper()) {
    }

    public WorkSession(IRepository<T> repository, IObjectToRegisteredObjectMapper mapper) {
        this.mapper = mapper;
        this.repository = repository;
        registeredInstances = new HashSet<IRegisteredInstanceOf<T>>();
    }

    public void Register(T newInstanceToRegister) {
        registeredInstances.Add(mapper.MapFrom(newInstanceToRegister));
    }

    public void Commit() {
        foreach (var registeredInstance in registeredInstances)
        {
            registeredInstance.CommitTo(repository);
        }
    }

    public void Dispose() {
        registeredInstances = new HashSet<IRegisteredInstanceOf<T>>();
    }

    private readonly IRepository<T> repository;
    private ICollection<IRegisteredInstanceOf<T>> registeredInstances;
    private IObjectToRegisteredObjectMapper mapper;
}

 

public class RegisteredInstance<T> : IRegisteredInstanceOf<T> {
    private readonly T originalInstance;
    private readonly T workingInstance;

    public RegisteredInstance(T newInstanceToRegister, ICloner cloner) {
        workingInstance = newInstanceToRegister;
        originalInstance = cloner.Clone(newInstanceToRegister);
    }

    public T Original() {
        return originalInstance;
    }

    public T WorkingCopy() {
        return workingInstance;
    }

    public bool HasBeenModified() {
        return !Original().Equals(WorkingCopy());
    }

    public void CommitTo(IRepository<T> repository) {
        if (HasBeenModified()) {
            repository.Update(WorkingCopy());
        }
        else {
            repository.Add(WorkingCopy());
        }
    }

    protected bool Equals(RegisteredInstance<T> registered) {
        return registered != null && Equals(originalInstance, registered.originalInstance);
    }

    public override bool Equals(object obj) {
        return ReferenceEquals(this, obj) || Equals(obj as RegisteredInstance<T>);
    }

    public override int GetHashCode() {
        return originalInstance != null ? originalInstance.GetHashCode() : 0;
    }
}

Each registered instance immediately clones the original instance to keep track of changes between the original and the current working copy. For this to work properly the cloner has to perform a deep copy otherwise the dirty tracking wont work properly. To do the deep copy, i'm using serialization, hence the "serializable" attribute decorating each entity.

public class Cloner : ICloner
{
    public T Clone< T >( T instanceToClone )
    {
        var serializer = new Serializer< T >( );
        return serializer.DeserializeFrom( serializer.Serialize( instanceToClone ) );
    }
}

So far this implementation is just a spike on how to implement a unit of work, it's really not a great implementation but I'm hoping to solicit some feedback on ways that have worked for others.

#

Sharpening My C

Saturday, March 15, 2008 1:35:43 PM (Mountain Standard Time, UTC-07:00)

I recently finished reading...

C# 3.0 in a Nutshell: A Desktop Quick Reference (In a Nutshell (O'Reilly))
by Joseph Albahari, Ben Albahari

Read more about this title...

My desire to read this book was to understand what new language features C# 3.0 brings to the table. This book started to explain the C# language right from the very beginning up until now. So some of it was a great refresher and some of it was quite boring. It not only covers the new language features but covers several areas of the framework class libraries and new lib's that came with the .NET 3.5 stack.

I was hoping to find my coverage on the new language features to see different usages for things like extension methods and lambda's to try to get a sense for what I like and don't like. So far I'm not really a fan of the new query comprehension syntax. It's to SQL-ish for me... I prefer working directly against methods. But I might have to give it some time... enough ranting here's some of the things I've learned.

Lambda Expressions

There's tonnes, and tonnes of discussion on this topic right now. I love how it's so much cleaner, and less verbose then anonymous delegates, but I see potential room for abuse. IMHO seeing lambda's tossed around all over your code base is no better then over using anonymous delegates. I love the new ideas that lambda's bring though...

"A lambda expression is an unnamed method written in place of a delegate instance. The compiler immediately converts the lambda expression to either:

  • A delegate instance.
  • An expression tree, of type Expression<T>, representing the code inside the lambda expression in a traversable object model. This allows the lambda expression to be interpreted later at runtime..." - C# 3.0 in a Nutshell

I love the idea of building up an expression tree of delegates that chain together to solve an equation. One of the ideas I'm working on is understanding how to leverage an expression tree of lambdas to solve trivial mathematical equations. Then possible traversing through the structure with a visitor to build out a display friendly version of the equation.

WPF

"The benefits of WPF are as follows:

  • It supports sophisticated graphics, such as arbitrary transformations, 3D rendering, and true transparency.
  • Its primary measurement unit is not pixel-based, so applications display correctly in any DPI
  • It has extensive dynamic layout support, which means you can localize any application without danger of elements overlapping.
  • Rendering uses DirectX and is fast, taking good advantage of graphics hardware acceleration.
  • User interfaces can be described declaratively in XAML files that can be maintained independently of the "code-behind" files - this helps to separate appearance from functionality." - C# 3.0 in a Nutshell

WCF

"WCF is the communication infrastructure new to Framework 3.0. WCF is flexible and configurable enough to make both of its predecessors - Remoting and (.ASMX) Web Services - mostly redundant." - C# 3.0 in a Nutshell

XML

"If you're dealing with data that's originated from or destined for an XML file, XmlConvert (the System.Xml namespace) provides the most suitable methods for formatting and parsing. The methods in XmlConvert handle the nuances of XML formatting without needing special format strings." - C# 3.0 in a Nutshell

Iterators

"The compiler, upon parsing the yield return statement, writes 'behind the scenes,' a hidden nested enumerator class, and then refactors GetEnumerator to instantiate and return that class. Iterators are powerful and simple" - C# 3.0 in a Nutshell

Hash Tables

"Its underlying hashtable works by converting each element' key into an integer hashcode - a pseudo unique value - and then applying an algorithm to convert the hashcode into a hash key. This hash key is used internally to determine which 'bucket' an entry belongs to. If the bucket contains more than one value, a linear search is performed on the bucket. A hashtable typically starts out maintaining a 1:1 ration of buckets to values, meaning that each bucket contains only one value. However, as more items are added to the hashtable, the load factor dynamically increases, in a manner designed to optimize insertion and retrieval performance as well as memory requirements." - C# 3.0 in a Nutshell

Serialization

"The data contract serializer is the newest and the most versatile of the three serializatoin engines and is used by WCF. The serializer is particularly strong in two scenarios:

  • When exchanging information through standards-compliant messaging protocols
  • When you need high-version tolerance plus the option of preserving object references."

C# 3.0 in a Nutshell

Threading

"A Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wide as well as application-wide" - C# 3.0 in a Nutshell

"A Semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it's full, no more people can enter and a queue build up outside. Then, for each person that leaves, one person enters from the head of the queue." - C# 3.0 in a Nutshell

"The Thread class provides GetData and SetData methods for storing nontransient isolated data in 'slots' whose values persist between method calls." - C# 3.0 in a Nutshell

#

More Readable Assertions

Saturday, March 15, 2008 12:58:43 PM (Mountain Standard Time, UTC-07:00)

I recently started to leverage extension methods in my unit tests as a way to create more readable and strongly typed unit tests. Here's an example:

        [Test]
        public void should_be_able_to_subtract_one_number_from_another() {
            var twenty = Number( 20 );
            var three = Number( 3 );
            var seventeen = Number( 17 );

            var calculator = CreateSUT( );
            var resultOfCalculation
                = calculator
                    .Number( twenty )
                    .Minus( )
                    .Number( three )
                    .ComputesTo( );

            resultOfCalculation.ShouldBeEqualTo( seventeen );
        }

This is a completely state based unit test that asserts that the result of the calculation is equal to 17. The actual assertion actually happens in an extension method. Defined below:

    public static class AssertionExtensions {
        public static void ShouldBeEqualTo< T >( this T itemToCheck, T valueToBeEqualTo ) {
            Assert.AreEqual( valueToBeEqualTo, itemToCheck );
        }
    }
 

MbUnits Assert.AreEqual() method has several overloads. The one I use the most is the overload defined as follows:

public void AreEqual( object expected, object actual ) {...}

The problem I have with this overload is that it's not strongly typed. So I could have written an Assertion that looked like:

Assert.AreEqual( 17, new Number(17) );

This won't give me a compile error but will indicate a broken test with the following message. 

Equal assertion failed: [[17]]!=[[Calculator.Domain.Number]]

This happens because the integer value type 17 is not equal to the Number reference type with an underlying value of 17. Also, this would have boxed the value type to a reference type to use the overload that accepts two objects. (which is also expensive)

By extending the assertion with a generic  extension method, I get a more readable test with the strong typing of generics.

Hopefully, this saves you from some embarrassing moments with your pair!

#

Specifications & Extension Methods

Thursday, March 06, 2008 5:56:27 AM (Mountain Standard Time, UTC-07:00)

Last week I went and checked out JP's latest presentation on Generics at the Calgary .NET User Group, and as usual it was awesome! He's definitely knee deep in C# 3.0, and was dropping lambda's and extension methods like it was old news... Here's some of the stuff I learned.

Extending the ISpecification interface via the use of Extension methods.

    public static class SpecificationExtensions {
        public static ISpecification< T > And< T >( this ISpecification< T > leftSide, ISpecification< T > rightSide ) {
            return new AndSpecification< T >( leftSide, rightSide );
        }

        public static ISpecification< T > And< T >( this ISpecification< T > left, Predicate< T > criteriaToSatisfy ) {
            return left.And( new Specification< T >( criteriaToSatisfy ) );
        }

        public static ISpecification< T > Or< T >( this ISpecification< T > leftSide, ISpecification< T > rightSide ) {
            return new OrSpecification< T >( leftSide, rightSide );
        }

        public static ISpecification< T > Or< T >( this ISpecification< T > left, Predicate< T > criteriaToSatisfy ) {
            return left.Or( new Specification< T >( criteriaToSatisfy ) );
        }

        private class AndSpecification< T > : ISpecification< T > {
            public AndSpecification( ISpecification< T > leftCriteria, ISpecification< T > rightCriteria ) {
                this.leftCriteria = leftCriteria;
                this.rightCriteria = rightCriteria;
            }

            public bool IsSatisfiedBy( T item ) {
                return leftCriteria.IsSatisfiedBy( item ) && rightCriteria.IsSatisfiedBy( item );
            }

            private ISpecification< T > leftCriteria;
            private ISpecification< T > rightCriteria;
        }

        private class OrSpecification< T > : ISpecification< T > {
            public OrSpecification( ISpecification< T > leftCriteria, ISpecification< T > rightCriteria ) {
                this.leftCriteria = leftCriteria;
                this.rightCriteria = rightCriteria;
            }

            public bool IsSatisfiedBy( T item ) {
                return leftCriteria.IsSatisfiedBy( item ) || rightCriteria.IsSatisfiedBy( item );
            }

            private ISpecification< T > leftCriteria;
            private ISpecification< T > rightCriteria;
        }
    }

By accepting a Predicate<T> delegate as the second argument you can now inline your lambdas and still take advantage of specifications. Client components can now take advantage of these extensions like this...

    public class SlipsRepository : ISlipsRepository {
        public SlipsRepository( ISlipDataMapper mapper ) {
            _mapper = mapper;
        }

        public IEnumerable< ISlip > AllAvailableSlips() {
            return _mapper.AllSlips( ).Where( Is.NotLeased( ) );
        }

        public IEnumerable< ISlip > AllAvailableSlipsFor( IDock dockToFindSlipsOn ) {
            return _mapper.AllSlips( ).Where( Is.NotLeased( ).And( Is.On( dockToFindSlipsOn ) ) );
        }

        private readonly ISlipDataMapper _mapper;

        private static class Is {
            public static ISpecification< ISlip > NotLeased() {
                return new Specification< ISlip >( slip => !slip.IsLeased( ) );
            }

            public static Predicate< ISlip > On( IDock dock ) {
                return slip => dock.Equals( slip.Dock( ) );
            }
        }
    }

 The base specification class becomes a quick and easy...

    public class Specification< T > : ISpecification< T > {
        public Specification( Predicate< T > criteriaToSatisfy ) {
            _criteriaToSatisfy = criteriaToSatisfy;
        }

        public bool IsSatisfiedBy( T item ) {
            return _criteriaToSatisfy( item );
        }

        private readonly Predicate< T > _criteriaToSatisfy;
    }

#

Replace Enum With Flyweights

Saturday, February 23, 2008 11:08:21 AM (Mountain Standard Time, UTC-07:00)

I've got a beef with enums. When I see them, I cringe... which is quite different from my days in C, where I couldn't live without enums and structs. That's another story...

"Flyweight: Use sharing to support large numbers of fine-grained objects efficiently" - Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)
by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides

Read more about this title...

Why do some of us quickly jump to enums? In procedural languages it makes sense. It's giving a type code a human readable meaning. So instead of having to stare at type code 1, everywhere you can use State.Acknowledgement, which is a lot easier to understand ... what does 1 mean again?

But in an OO language, I feel dirty when I see enums. The argument of using it for bitwise operations and the Flags attribute is weak. Create a composite!

    [Flags]
    public enum Digits {
        Zero = 0x00,
        One = 0x01,
        Two = 0x02,
        Three = 0x03,
        Four = 0x04,
        Five = 0x05,
        Six = 0x06,
        Seven = 0x07,
        Eight = 0x08,
        Nine = 0x09
    }
    [Test]
    public void Should_be_equal_to_2_digits() {
        Digits digits = Digits.Six | Digits.One;
        Assert.IsTrue( Digits.Six == (digits & Digits.Six) );
        Assert.IsTrue( Digits.One == (digits & Digits.One) );            
    }

Weak... do you really want to use a bitwise & to check if a certain digit is enabled. I don't. I'm going to use the following 2 tests to squash the enum into a first class component, with some smarts to it.

        [Test]
        public void should_be_able_to_add_a_single_digit() {
            INumberBuilder builder = CreateSUT( );
            builder.Add( Digits.One );
            Assert.AreEqual( new Number( 1 ), builder.Build( ) );
        }

        [Test]
        public void should_be_able_to_form_a_number_with_more_than_one_digit() {
            INumberBuilder builder = CreateSUT( );
            builder.Add( Digits.One );
            builder.Add( Digits.Nine );
            Assert.AreEqual( new Number( 19 ), builder.Build( ) );
        }

My current NumberBuilder implementation looks like this (it sucks but it works):

    public class NumberBuilder : INumberBuilder {
        public void Add( Digits digit ) {
            numberBeingBuilt += Convert.ToString( Convert.ToInt32( digit ) );
        }

        public INumber Build() {
            return new Number( Convert.ToInt32( numberBeingBuilt ) );
        }

        private string numberBeingBuilt;
    }

I'm going to start off by creating some Flyweights.

    public class Digits {
        public static readonly IDigit Eight = new Digit( 8 );
        public static readonly IDigit Five = new Digit( 5 );
        public static readonly IDigit Four = new Digit( 4 );
        public static readonly IDigit Nine = new Digit( 9 );
        public static readonly IDigit One = new Digit( 1 );
        public static readonly IDigit Seven = new Digit( 7 );
        public static readonly IDigit Six = new Digit( 6 );
        public static readonly IDigit Three = new Digit( 3 );
        public static readonly IDigit Two = new Digit( 2 );
        public static readonly IDigit Zero = new Digit( 0 );

        public class Digit : IDigit {
            public Digit( int digitToRepresent ) {
                _digitToRepresent = digitToRepresent;
            }

            public override string ToString() {
                return _digitToRepresent.ToString( );
            }

            private readonly int _digitToRepresent;
        }
    }

My compiler is telling me that the Add method on my builder currently accepts a parameter of type "Digits", so I'm going to change the signature to accept a parameter of type IDigit.

    public interface INumberBuilder {
        void Add( Digits digit );
        INumber Build();
    }

To...

    public interface INumberBuilder {
        void Add( IDigit digit );
        INumber Build();
    }

Let's update the NumberBuilder implementation to:

    public class NumberBuilder : INumberBuilder {
        public NumberBuilder() {
            _digitsOfNumberBeingBuilt = new List< IDigit >( );
        }

        public void Add( IDigit digit ) {
            _digitsOfNumberBeingBuilt.Add( digit );
        }

        public INumber Build() {
            return new Number( CreateIntegerFrom( _digitsOfNumberBeingBuilt ) );
        }

        private int CreateIntegerFrom( IEnumerable< IDigit > digitsOfNumberBeingBuilt ) {
            StringBuilder builder = new StringBuilder( );
            foreach ( IDigit digit in digitsOfNumberBeingBuilt ) {
                builder.Append( digit );
            }
            return Convert.ToInt32( builder.ToString( ) );
        }

        private IList< IDigit > _digitsOfNumberBeingBuilt;
    }

I run the tests and they pass, sweet. But I'm not happy with the current implementation, so I look for other potential refactorings. I decide to forward the digit to append right to the number, the number can take care of how to append the digit, rather then having the builder doing so. The builder now looks like:

    public class NumberBuilder : INumberBuilder {
        public NumberBuilder() {
            _numberBeingBuilt = new Number( 0 );
        }

        public void Append( IDigit digit ) {
            _numberBeingBuilt = _numberBeingBuilt.Append( digit );
        }

        public INumber Build() {
            return _numberBeingBuilt;
        }

        private INumber _numberBeingBuilt;
    }

And Number looks like:

    public class Number : INumber, IEquatable< Number > {
        public Number() : this( 0 ) {}

        public Number( int numberToRepresent ) {
            _numberToRepresent = numberToRepresent;
        }

        public INumber Append( IDigit digit ) {
            return new Number( ( _numberToRepresent*10 ) + digit.Value( ) );
        }

        public bool Equals( Number number ) {
            if ( number == null ) {
                return false;
            }
            return _numberToRepresent == number._numberToRepresent;
        }

        public override string ToString() {
            return _numberToRepresent.ToString( );
        }

        public override bool Equals( object obj ) {
            if ( ReferenceEquals( this, obj ) ) {
                return true;
            }
            return Equals( obj as Number );
        }

        public override int GetHashCode() {
            return _numberToRepresent;
        }

        private readonly int _numberToRepresent;
    }

To wrap this up, Number aggregates digits, the enum got dropped and was replaced by a class. There's still more refactorings that can occur, but the point is that a full blown component is much easier to extend then an enum...

For more info check out "Replace Type Code with Class" from...

Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

Read more about this title...

 Soure:

#

I'll do it later

Sunday, February 10, 2008 10:19:03 AM (Mountain Standard Time, UTC-07:00)

Let's have a quick chat about deferring execution. Take a look at the following test:

    [SetUp]
    public void SetUp() {
        _mockery = new MockRepository( );
        _mapper = _mockery.DynamicMock< IXmlToBookMapper >( );
        _xmlGateway = _mockery.DynamicMock< IXmlGateway >( );
    }

    public IBooksGateway CreateSUT() {
        return new BooksGateway( _mapper, _xmlGateway );
    }

    [Test]
    public void Should_leverage_xml_bank_to_retrieve_xml() {
        using ( _mockery.Record( ) ) {
            Expect.Call( _xmlGateway.AllElementsNamed( "Book" ) ).Return( new List< IXmlElement >( ) );
        }

        using ( _mockery.Playback( ) ) {
            CreateSUT( ).LoadAllBooksFromStorage( );
        }
    }

When I run this test I get the following output:

FailedTest

It says that the expectation set on the xml gateway was never satisfied. So the call to the method "AllElementsNamed()" with an input parameter with a value of "Book" was not made.

Let's take a look at the implementation that failed this test.

    public class BooksGateway : IBooksGateway {
        public BooksGateway( IXmlToBookMapper mapper, IXmlGateway xmlGateway ) {
            _mapper = mapper;
            _xmlGateway = xmlGateway;
        }

        public IEnumerable< IBook > LoadAllBooksFromStorage() {
            foreach ( IXmlElement element in _xmlGateway.AllElementsNamed( "Book" ) ) {
                yield return _mapper.MapFrom( element );
            }
        }

        private readonly IXmlToBookMapper _mapper;
        private readonly IXmlGateway _xmlGateway;
    }

Can you spot the error? Really?

There is no error, the reason this test fails is because of something that C# 2.0 offered for free that very few people actually talk about, and that's deferred execution. The iteration through the loop never occurs because the client of the BooksGateway component never actually begins iterating. In this case the client component is our unit test.

CreateSUT( ).LoadAllBooksFromStorage( );

The above line never actually starts to walk the underlying collection therefore causes the expectation violation to occur. Traversal through the collection is put off until the last possible moment necessary. What this also means is that each time the traversal through the collection re-starts it will actually rebuild the internal collection to walk through. This works great for immutable types but can cause a bit of a head ache with types that change through out its lifetime, since new instances are brought back out of persistence. In this case, each time we walk the underlying collection we're actually re-reading the books from an xml file.

If we re-write the test like this...

        [Test]
        public void Should_leverage_xml_bank_to_retrieve_xml() {
            using ( _mockery.Record( ) ) {
                Expect.Call( _xmlGateway.AllElementsNamed( "Book" ) ).Return( new List< IXmlElement >( ) );
            }

            using ( _mockery.Playback( ) ) {
                foreach ( IBook book in CreateSUT( ).LoadAllBooksFromStorage( ) ) {
                    Console.Out.WriteLine( book.Name( ) );
                }
            }
        }

The test now passes...

Charlie Calvert's got a nice post that explains how deferred execution is better utilized with the introduction of LINQ.

#

Keep the ruffians out

Saturday, February 02, 2008 10:52:02 AM (Mountain Standard Time, UTC-07:00)

It's so important to properly protect your internals of an object, especially collections. I'm going rant for a bit about why the following piece of code drives me a little nutty!

    public class HighSocietyCountryClub : ICountryClub {
        public HighSocietyCountryClub() {
            _membersOfTheHighlyExclusiveCountryClub = new List< IExclusiveMember >( );
        }

        public IList< IExclusiveMember > Members {
            get { return _membersOfTheHighlyExclusiveCountryClub; }
        }

        private IList< IExclusiveMember > _membersOfTheHighlyExclusiveCountryClub;
    }

Why is this so wrong... because it does not keep the ruffians out.

    public class CountryClubBackDoor {
        public CountryClubBackDoor() {
            _club = new HighSocietyCountryClub( );
        }

        public void SneakIn() {
            Ruffian ruffian = new Ruffian( );
            _club.Members.Add( ruffian );        // oops... who let the ruffian in?
        }

        private ICountryClub _club;
    }

When you expose a collection as a property on a component you expose the innards of the component. Clients of the component can inject state that was not meant to be there. Does that suck? YUP!

So how do we deal with this? You separate the behavior of add new exclusive members from checking the exclusive members roster. When you're viewing the roster, you're doing so in a read only manner. Clients who are checking out the roster should not have access to sneaking in new exclusive members.

Enter the IEnumerable interface. All collections types implement the IEnumerable interface, it's contract allows consumers to walk a collection but not sneak members in. Or does it? Let's take a look at a revised contract for the Country Club.

    public interface ICountryClub {
        //IList< IExclusiveMember > Members { get; }
        IEnumerable< IExclusiveMember > RosterOfMembers { get; }
    }

Looks alright for now. Let's peak at an implementation or the contract...

        public IEnumerable< IExclusiveMember > RosterOfMembers {
            get { return _membersOfTheHighlyExclusiveCountryClub; }
        }

IEnumerable doesn't have an add method so I guess clients shouldn't be able to sneak in now right? Let's see what those ruffians come up with...

        public void SneakIn() {
            Ruffian ruffian = new Ruffian( );
            //_club.Members.Add( ruffian ); // oops... who let the ruffian in?
            ( ( List< IExclusiveMember > )_club.RosterOfMembers ).Add( ruffian ); // they did it again!
        }

They did it again, those ruffians are a persistent bunch. They guessed that the roster of members were composed in a collection of type List, and they were right! They snuck in again!

We can keep those ruffians out by building an instance of a type that implements the IEnumerable interface but doesn't hand out our internal collection. The following code does just that:

        public IEnumerable< IExclusiveMember > RosterOfMembers {
            get {
                foreach ( IExclusiveMember exclusiveMember in _membersOfTheHighlyExclusiveCountryClub ) {
                    yield return exclusiveMember;
                }
            }
        }

The above code compiles down to a full blown Enumerable type. Kind of like the code below, you can go check out the IL produced from the above and see what it translates too...

    public class ExclusiveMembersEnumerable : IEnumerable< IExclusiveMember > {
        public ExclusiveMembersEnumerable( IEnumerable< IExclusiveMember > members ) {
            _members = members;
        }

        IEnumerator< IExclusiveMember > IEnumerable< IExclusiveMember >.GetEnumerator() {
            return _members.GetEnumerator( );
        }

        public IEnumerator GetEnumerator() {
            return ( ( IEnumerable< IExclusiveMember > )this ).GetEnumerator( );
        }

        private readonly IEnumerable< IExclusiveMember > _members;
    }

One additional thing that the yield return keyword offers is deferred execution. This concept is getting a lot more attention now in C# 3.0, but it was already available in C#2.0. More on that later...

If the purpose of exposing the IList interface on a type instead of the IEnumerable interface is to leverage the sorting methods then I suggest you factor out a separate interface specifically for traversing a collection and being able to query it. I spoke of a RichEnumerable interface that allowed you to do so, but the new language features in C# 3.0 and specifically the IQueryable interface looks like it might make this much easier to traverse a collection and sort and query it as needed.

New interfaces to check out:

  • IGrouping<TKey, TElement>
  • ILookup<TKey, TElement>
  • IOrderedEnumerable<TElement>
  • IOrderedQueryable<T>
  • IQueryable<T>
  • IQueryProvider

My personal preference is to drop the properties... In my mind when I see a call to a method, I think this is invoking and action or triggering some sort of behavior, and in this example it is. We're building up a type that we serve back to a client to allow them to traverse our internals without completely handing it out. Anyway's, I wont fight the battle with properties today... but maybe I can save that for a later rant.

Source: CHECK OUT THE CODE!

#

Controlling Pages

Friday, February 01, 2008 4:10:39 PM (Mountain Standard Time, UTC-07:00)

WebForms is an awkward marriage between a Page Controller and a Template View. In the Web Forms model the Template View (aspx page) inherits from the Page Controller (code behind).

Patterns of Enterprise Application Architecture defines the Page Controller as:

"An object that handles a request for a specific page or action on a web site." - PoEAA

In this example I've separated the Page Controller from the Template View, because... mostly because I was bored and thought this would be a great way to better understand the patterns. So let's get started...

I defined a layer super type for all page controllers defined as :

    public interface IPageController : IHttpHandler {
        void Execute();
    }

The IPageController could have very well been called and Page Command because in this implementation I'm not concerned about having separate behaviors for GET and POST method requests. If this example were to evolve I might choose to separate the "Execute()" method into "ProcessGetRequest()" and "ProcessPostRequest()".

The IPageController type inherits IHttpHandler in order to register this page controller with ASP.NET to receive all requests for a particular path. In this case this handler is registered in the web.config for all requests to the "DisplayAllCustomers.aspx" page.

    <httpHandlers>
        <add 
            verb="*" 
            path="DisplayAllCustomers.aspx" 
            validate="false" 
            type="PlayingWithPageControllers.Web.Controllers.DisplayAllCustomersController, PlayingWithPageControllers"/>
    </httpHandlers>

If I wanted to get a little more nitty, gritty I could have specified only GET Http method's are handled by this handler.

Moving on.... The PageController base type for all controllers looks like:

    public abstract class PageController : IPageController {
        public void ProcessRequest( HttpContext context ) {
            Execute( );
        }

        public bool IsReusable {
            get { return true; }
        }

        public abstract void Execute();
    }

And finally our "DisplayAllCustomersController" component looks like:

    public class DisplayAllCustomersController : PageController, IDisplayAllCustomersController {
        public DisplayAllCustomersController( IDisplayAllCustomersView view, ICustomerTasks tasks ) {
            _view = view;
            _tasks = tasks;
        }

        public override void Execute() {
            _view.AddToBag( _tasks.AllCustomers( ) );
            _view.Render( );
        }

        private readonly IDisplayAllCustomersView _view;
        private readonly ICustomerTasks _tasks;
    }

And voila all requests to "DisplayAllCustomers.aspx" are handled by the DisplayAllCustomersController which pulls information from the model and fires it off to the template view to be rendered.

The Template View Pattern is defined as:

"Renders information into HTML by embedding markers in an HTML page." - PoEAA

Our template view for "AllCustomers.aspx" looks like this:

    <table>
        <thead>
            <tr>
                <td>First Name:</td>
                <td>Last Name:</td>
            </tr>
        </thead>
        <tbody>            
            <% foreach ( DisplayCustomerDTO dto in ViewBagLocator.For( ViewBagKeys.DisplayCustomers ) ) {%>
            <tr>
                <td><%= dto.FirstName() %></td>
                <td><%= dto.LastName( ) %></td>
            </tr>
            <% } %>
        </tbody>
    </table>

This separates the Template view from having any knowledge of the Page Controller. The Page controller has the responsibility of pulling information from the model to pass along to the appropriate view.

All access to the current context and the ASP.NET pipeline has been isolated to the HttpGateway which abstracts the ASP.NET facilities available through a condensed client interface.

    public interface IHttpGateway {
        void RedirectTo( IView view );

        void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag );

        T FindItemFor< T >( IViewBagKey< T > key );
    }

Now that I think about it, another step that I could have taken would have to shield the page controllers from having any knowledge of "IHttpHandler", which would have further isolated the ASP.NET infrastructure from the rest of the web presentation layer.

Patterns of Enterprise Application Architecture defines a Gateway as:

"An object that encapsulates access to an external system or resource." - PoEAA

    public class HttpGateway : IHttpGateway {
        public HttpGateway( IHttpContext context ) {
            _context = context;
        }

        public void RedirectTo( IView view ) {
            _context.Server.Transfer( view.Path( ) );
        }

        public void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag ) {
            _context.Items.Add( key, itemToAddToBag );
        }

        public T FindItemFor< T >( IViewBagKey< T > key ) {
            return ( T )_context.Items[ key ];
        }

        private readonly IHttpContext _context;
    }

If you haven't already you should go buy and read, then re-read, then re-read "Patterns of Enterprise Application Architecture by Martin Fowler"

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this title...

Source: DOWNLOAD THE CODE

#

Jockin' Screens

Friday, December 28, 2007 2:05:17 PM (Mountain Standard Time, UTC-07:00)

So another thought that came to mind was the concept of how to switch views in a winforms application. Bare with me because these are only thought so far and I have yet to read about the actual "Application Controller" pattern in PoEAA.

I've been reading a book on WinForms lately by Chris Sells, the name evades me at the moment but I promise to give you the name in the future. And it tells about the ApplicationContext and how it works and how you can access it.

If you take a look at the overloads for the "Application.Run()" method you'll find one that accepts an ApplicationContext. When you choose the overload that accepts a Form it creates an application context and registers for the form closing event which is when it call Application.Exit().

If you can access the context then you can access the start up form, and if you need to switch user controls on the main form you can try to access the application context to do so. Here's my 30 second brain dump on potentially how this could work... (Warning... I have yet to fully implement this!)

    public class ApplicationController
    {
        private static System.Windows.Forms.ApplicationContext _context;
        private readonly IScreenRegistry registry;

        public ApplicationController( IScreenRegistry registry )
        {
            this.registry = registry;
        }

        public static void Begin( )
        {
            Application.EnableVisualStyles( );
            Application.SetCompatibleTextRenderingDefault( false );
            _context = new System.Windows.Forms.ApplicationContext( new Form1( ) );
            Application.Run( _context );
        }

        public void Render( IScreen screen )
        {
            _context.MainForm.Controls.Add( registry.FindFor( screen ) );
        }
    }

Main then becomes an empty shell that delegates to the application controller, when types in the system need to render a new view it can call upon the ApplicationController to take care of that by calling it's Render method and passing in the screen to display. The application controller can then leverage registry to find the user control that's registered for the screen.

Hey, if anyone knows a good book on WinForms patterns of even UI patterns I'd love to hear about it!

Source:

Updated: February. 17, 2008... As Mr. Chris mentioned in the comments below the name of the book was:

Windows Forms 2.0 Programming (2nd Edition) (Microsoft .NET Development Series)
by Chris Sells, Michael Weinhardt

Read more about this book...

#

RichEnumerables

Friday, December 28, 2007 1:24:51 PM (Mountain Standard Time, UTC-07:00)

So i was digging through some old posts of Adam's and found one where he's pointing to article on MSDN on the new language features in C# 3.0. It got me thinking about how you can bring some of those features down to C# 2.0 and I came up with the concept of a RichEnumerable. This type can be used for querying using specifications.

The interface implements the IEnumerable<T> interface but extends it with a "Where" method.

    public interface IRichEnumerable< T > : IEnumerable< T >
    {
        IEnumerable< T > Where( ISpecification< T > criteria );
    }

The implementation so far looks like this.

    internal class RichEnumerable< T > : IRichEnumerable< T >
    {
        private readonly IEnumerable< T > _items;

        public RichEnumerable( IEnumerable< T > items )
        {
            _items = items;
        }

        public IEnumerable< T > Where( ISpecification< T > criteria )
        {
            foreach( T item in _items )
            {
                if( criteria.IsSatisfiedBy( item ) )
                {
                    yield return item;
                }
            }
        }

        IEnumerator< T > IEnumerable< T >.GetEnumerator( )
        {
            return _items.GetEnumerator( );
        }

        public IEnumerator GetEnumerator( )
        {
            return ( ( IEnumerable< T > )this ).GetEnumerator( );
        }
    }

This could be extended further to return a RichEnumerable<T> from the where method instead of an IEnumerable<T> so you can filter further.

Just a quick lunch time idea... source is provided.

#

The Event Aggregator

Tuesday, December 18, 2007 2:26:11 PM (Mountain Standard Time, UTC-07:00)

I'd like to talk to you for a moment about my man The Event Aggregator. (Homeboy's been tossin' events for years!)

Martin Fowler defines the Event Aggregator as:

"Channel events from multiple objects into a single object to simplify registration for clients." - Martin Fowler

But he's so much more then that! This pattern comes in handy in state-ful environments, so.. hello WinForms/WPF. Sorry ASP.NET!

What this guy does is creates a single channel to find out what's going on and to raise events. Through the event aggregator you can subscribe to known events in the system as well as raise known events in the system.

Some examples for system wide events are Save, Loading, Shutdown. You can also create concepts for layer specific event aggregators that target certain layers of a system. For example UI only.

    public class ApplicationEvents {
        private static readonly IEventAggregator aggregator;
        public static readonly IEvent Save = new EventRaiser( "Save" );
        public static readonly IEvent Loading = new EventRaiser( "Loading" );

        static ApplicationEvents( ) {
            aggregator = new EventAggregator( );
            aggregator.Register( Save );
            aggregator.Register( Loading );
        }

        public static void Raise( IEvent eventToRaise ) {
            aggregator.RaiseEvent( eventToRaise );
        }

        public static void SubscribeTo( IEvent eventToSubscribeTo, EventHandler handler ) {
            aggregator.AddHandler( eventToSubscribeTo.Name, handler );
        }
    }

The ApplicationEvents becomes the central point for raising and subscribing to known application wide events. Type can be coupled to the aggregator but not to each other.

Let's start with the concept of a named event. An event is really nothing more then a delegate. In .NET there are 2 delegate signatures that are used for all events. The generic and non generic version of the EventHandler delegate. (Read More... )

A named event is an event with a name. He might look something like this guy?

    internal class EventRaiser : IEvent {
        public EventRaiser( string name ) {
            _name = name;
            _handlers = new List< EventHandler >( );
        }

        public string Name {
            get { return _name; }
        }

        public void Add( EventHandler handler ) {
            _handlers.Add( handler );
        }

        public void Raise( ) {
            Raise( null, null );
        }

        public void Raise( object sender, EventArgs data ) {
            foreach ( EventHandler handler in _handlers ) {
                if ( handler != null ) {
                    handler( sender, data );
                }
            }           
        }

        private readonly string _name;
        private readonly IList< EventHandler > _handlers;
    }

Underneath the hood it's the aggregator that's maintaining references to all the types that have subscribed to events.

    public class EventAggregator : IEventAggregator {
        public EventAggregator( ) {
            _events = new Dictionary< string, IEvent >( );
        }

        public void Register( string eventName ) {
            Register( new EventRaiser( eventName ) );
        }

        public void Register( IEvent eventToAdd ) {
            EnsureEventHasntBeenRegistered( eventToAdd );
            _events.Add( eventToAdd.Name, eventToAdd );
        }

        public void AddHandler( string eventName, EventHandler handler ) {
            RetrieveEvent( eventName ).Add( handler );
        }

        public void RaiseEvent( string withEventName ) {
            RaiseEvent< EventArgs >( withEventName, null, EventArgs.Empty );
        }

        public void RaiseEvent( IEvent eventToRaise ) {
            RaiseEvent< EventArgs >( eventToRaise.Name, null, EventArgs.Empty );
        }

        public void RaiseEvent< T >( string withEventName, object sender, T data ) where T : EventArgs {
            RetrieveEvent( withEventName ).Raise( sender, data );
        }

        private IEvent RetrieveEvent( string eventName ) {
            if ( _events.ContainsKey( eventName ) ) {
                return _events[ eventName ];
            }
            throw new ArgumentNullException( eventName, "The Event Has Not Been Registered." );
        }

        private void EnsureEventHasntBeenRegistered( IEvent eventToAdd ) {
            if ( _events.ContainsKey( eventToAdd.Name ) ) {
                throw new ArgumentException( "Event name has already been registered", eventToAdd.Name );
            }
        }

        private readonly IDictionary< string, IEvent > _events;
    }

The concept is similar to Juval Lowy's EventHelper class defined in...

Programming .NET Components, 2nd Edition
by Juval Lowy

Read more about this title...

#

What's Wrong With Inline ASPX

Tuesday, December 18, 2007 1:42:36 PM (Mountain Standard Time, UTC-07:00)

This month I've been going pretty hard core about learning ASP.NET and I was having a lot of difficulty with playing with the ASPX view engine. I'm already fairly familiar with HTML and CSS, but now I have to learn these new ASP.NET controls? Why can't I just stick to the HTML and CSS I know and enjoy working with?

Well it turns out I can... I don't need to learn about the complex data binding of a GridView or how an ASP:TextBox converts to a plain ol' input tag wrapped in span tags. I've been heavily studying the work from the project we worked on during the Nothin' But .NET boot camp and reading up on the MSDN documentation on inlining aspx.

I like it... C'mon doesn't this....

<h1>Available Slips</h1>          
<table>
    <thead>
        <tr>
            <td>Location Name</td>
            <td>Dock Name</td>
            <td>Slip Width</td>
            <td>Slip Length</td>
        </tr>
    </thead>            
<% foreach ( SlipDisplayDTO item in ViewLuggage.ClaimFor(ViewLuggageTickets.AvailableSlips) ) {%>
    <tr>
        <td><%= item.LocationName %></td>
        <td>
            <a href='<%= WebViews.DockView.Name( ) %>?<%= PayloadKeys.DockId %>=<%= item.DockId %>'>
                <%= item.DockName %>
            </a>
        </td>
        <td><%= item.Width %></td>
        <td><%= item.Length %></td>        
    </tr>
<% } %>                    
</table>

Seem a lot more readable then this...

<asp:Repeater ID="uxSlipsRepeater" runat="server">
<HeaderTemplate>
<table>
<thead>
    <tr>
        <td>Dock Name</td>
        <td>Slip Width</td>
        <td>Slip Length</td>
    </tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
    <tr>
        <td>
<a href='DockView.aspx?<%= PayLoadKeys.DockId %>=<%# ((SlipDisplayDTO)Container.DataItem).DockId %>'>
<%# Transform.From(Container.DataItem).AndConvertItToAn<SlipDisplayDTO>().DockName %>
</a>
        </td>
        <td><%# Transform.From(Container.DataItem).AndConvertItToAn<SlipDisplayDTO>().Width %></td>
        <td><%# Transform.From(Container.DataItem).AndConvertItToAn<SlipDisplayDTO>().Length %></td>
    </tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>    

The extra asp namespaces appended to all the controls just seem like noise. The explicit casting from Container.DataItem to the type actually contained seems like extra work. I suppose you could write all this out in an item data bound event handler. But it just looks like noise, noise noise... Then when you actually look at the HTML that's spit out it loaded with more noise...

For example:

<input 
    name="ctl00$ContentPlaceHolder2$uxUserNameTextBox" 
    type="text" 
    id="ctl00_ContentPlaceHolder2_uxUserNameTextBox" />

Versus:

<input name="uxUserNameTextBox" type="text" />

Well all of this can be avoided. But you're going to have to get just a little bit deeper, and here's how. Everything you need to know is in HttpContext. Yup!

Instead of dropping an ASP:TextBox on the page try an input element and parse out the value in the input element from the HttpContext.Current.Request.Params. This is a NameValueCollection that has all the Http Headers that were sent along the trip to the server AKA The Payload.

For my current school assignment I'm currently flushing out the concept of an HttpGateway, where all traffic comes in and all traffic goes out. Currently this is just wrapping and HttpContext but with an interface that works better for me as a client of it. I don't need to see everything available in the HttpContext (which is a lot!).

Next up, take advantage of the HttpContext.Items collection. This is a collection of objects which you can load up with extra information to pass on down the pipeline. Consider the concept of view luggage, where luggage is issued a ticket when you drop it off. You can then claim that luggage using the same luggage ticket.

What does this mean, you can have your presenters, controllers, commands (whatever) drop off luggage to be carried to the view. You can then have your views claim that luggage with the luggage ticket. (Take a look back at the first bit of HTML markup in this post.)

The HttpContext.Items collection is a dictionary for objects. Using strongly typed luggage tickets you can make that the key, and the actual luggage the value to store in the items collection. The HttpContext then becomes the airplane, carrier or transporter that hauls your luggage from your presenter, controller, command (whatever) to the view.

For the quick and dirty here's the code that describes what I'm talking about:

    public class ViewLuggageTransporter< Luggage > : IViewLuggageTransporter< Luggage > {
        public ViewLuggageTransporter( IViewLuggageTicket< Luggage > key ) : this( key, HttpContext.Current.Items ) {}

        private ViewLuggageTransporter( IViewLuggageTicket< Luggage > key, IDictionary items ) {
            _ticket = key;
            _items = items;
        }

        public Luggage Value() {
            foreach ( DictionaryEntry entry in _items ) {
                if ( entry.Key.Equals( _ticket ) ) {
                    return ( Luggage )entry.Value;
                }
            }
            return default( Luggage );
        }

        public void Add( Luggage value ) {
            _items.Add( _ticket, value );
        }

        private readonly IViewLuggageTicket< Luggage > _ticket;
        private readonly IDictionary _items;
    }

    public class ViewLuggage {
        public static IViewLuggageTransporter< T > TransporterFor< T >( IViewLuggageTicket< T > ticket ) {
            return new ViewLuggageTransporter< T >( ticket );
        }

        public static T ClaimFor< T >( IViewLuggageTicket< T > ticket ) {
            return new ViewLuggageTransporter< T >( ticket ).Value( );
        }
    }

To parse out the value submitted in a request you can create mappers to parse out the values for each control. In the code below each of the string literals prefixed with a "ux" represents the name of the html control that was on the page.

    public class UpdateRegistrationPresentationMapper : IUpdateRegistrationPresentationMapper {
        public UpdateCustomerRegistrationDTO MapFrom( IHttpRequest input ) {
            return new UpdateCustomerRegistrationDTO(
                input.ParsePayloadFor( PayloadKeys.CustomerId ),
                input.ParsePayloadFor( PayloadKeys.For( "uxUserNameTextBox" ) ),
                input.ParsePayloadFor( PayloadKeys.For( "uxPasswordTextBox" ) ),
                input.ParsePayloadFor( PayloadKeys.For( "uxFirstNameTextBox" ) ),
                input.ParsePayloadFor( PayloadKeys.For( "uxLastNameTextBox" ) ),
                input.ParsePayloadFor( PayloadKeys.For( "uxPhoneNumberTextBox" ) ),
                input.ParsePayloadFor( PayloadKeys.For( "uxCityTextBox" ) )
                );
        }
    }

For an even sweeter example check out the source code for the NothinButDotNetStore.

Next up, figuring out a cleaner way to implement authorization and authentication without having to rely on the FormsAuthentication class. So far my spiking of Forms Auth looks something like the code below... *Please do not use the code below. I was just trying to understand how forms auth works and this is not a great example of how you should use it.

        public void AuthenticateHttpRequest( ) {
            HttpCookie cookie = GetCookieFrom( HttpContext.Current );
            if ( null != cookie ) {
                BindPrincipalToThreadUsing( _mapper.MapFrom( FormsAuthentication.Decrypt( cookie.Value ) ) );
            }
        }

        private HttpCookie GetCookieFrom( HttpContext context ) {
            return context.Request.Cookies[ FormsAuthentication.FormsCookieName ];
        }

        private void BindPrincipalToThreadUsing( CustomerCookieCredentials credentials ) {
            IIdentity identity = new CustomerIdentity( credentials.Username, credentials.Username );
            HttpContext.Current.User = new GenericPrincipal( identity, new string[] {"customer"} );
        }

        private void AddAuthenticationTicket( ) {
            FormsAuthenticationTicket ticket =
                new FormsAuthenticationTicket( 1, "mo", DateTime.Now, DateTime.Now.AddMinutes( 20 ), false, "2" );
            string cookieValue = FormsAuthentication.Encrypt( ticket );
            HttpContext current = HttpContext.Current;
            current.Response.Cookies.Add( new HttpCookie( FormsAuthentication.FormsCookieName, cookieValue ) );

            IIdentity identity = new CustomerIdentity( "mo", "2" );
            current.User = new GenericPrincipal( identity, new string[] {"customer"} );
        }

#

The Identity Map

Tuesday, December 18, 2007 12:21:21 PM (Mountain Standard Time, UTC-07:00)

This week while I'm at home on holidays, I've been reading...

Patterns of Enterprise Application Architecture (The Addison-Wesley Signature Series)
by Martin Fowler

Read more about this title...

This book is amazing, I could probably read it over and over again. The patterns that it presents makes a lot of sense, the actual implementations and examples could probably re-vamped but I'm finding that it's a great starter to trying to understand the concepts.

So today I'm trying to grok this concept of the "IDENTITY MAP". The book defines it as:

"Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them."

I put together a quick implementation that I'm using for an assignment I'm writing for school. I'm creating repositories that have 2 dependencies. First dependency is a Data Mapper (not to be confused with a Mapper) and the second is an Identity Map.

As objects are requested from the repository, the repository is checking the identity map to see if an instance has been loaded, if it has it's immediately returned to the caller. If the object is not in the map the repository leverages the data mapper to load the object, then adds it to the map and returns it to the caller.

The Data Mapper is defined as:

"A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." - PoEAA

I created a Layer Supertype to register objects in the map. The Domain Layer Super type demands that domain objects had an ID. The ID is what's getting used to load and register objects into the map.

The Layer Supertype is defined as:

"A type that acts as a the supertype for all types in it's layer." - PoEAA

The Domain Layer Super Type.

    public interface IDomainObject {
        long ID();
    }

My actual implementation of the identity map looks like this...

    public class IdentityMap< T > : IIdentityMap< T > where T : IDomainObject {
        public IdentityMap() {
            _items = new List< T >( );
        }

        public void Add( T domainObject ) {
            EnsureObjectHasNotAlreadyBeenAdded( domainObject );
            _items.Add( domainObject );
        }

        public T FindObjectWithIdOf( long idOfObjectToFind ) {
            foreach ( T item in _items ) {
                if ( item.ID( ).Equals( idOfObjectToFind ) ) {
                    return item;
                }
            }
            return default( T );
        }

        private void EnsureObjectHasNotAlreadyBeenAdded( T domainObject ) {
            if ( ContainsObjectWithIdOf( domainObject.ID( ) ) ) {
                throw new ObjectAlreadyAddedToIdentityMapException( domainObject );
            }
        }

        private readonly IList< T > _items;
    }

One of the benefits I like about the Identity Map is that it acts as an in memory cache for objects loaded from the database. This reduces the number of trips to and from the persistence store.

Source Code

#

Disposable Actions

Saturday, November 17, 2007 9:53:12 AM (Mountain Standard Time, UTC-07:00)

What do you get when you marry the IDisposable interface to the Action<T> delegate? Disposable Actions... with a bit of syntactic sugar.

As you may or may not know, you can use the using block on types that implement the IDisposable interface. When the block is exiting it will call dispose on the type.

For example the following block of code uses the "using" block.

        public void DemoWithUsingBlock()
        {
            using (MemoryStream stream = new MemoryStream()) {
                // do something with the stream
            }
        }

But when compiled, the above block of code actually expands out to something like...

        public void DemoOfUsingBlockExpanded()
        {
            MemoryStream stream = null;
            try {
                stream = new MemoryStream();
                // do something with the stream
            }
            finally {
                if (stream != null) stream.Dispose();
            }
        }

Ok, so now let's take a look at the signature for the Action<T> delegate.

public delegate void Action<T>(T obj);

The signature returns void and takes in an object of type T. Quite simple actually. I'm sure you can think of quite a few methods that match that signature, but just in case you can't here are a couple of examples.

        public void DemoAction()
        {
            Do<string>(Console.Out.WriteLine);
            Do<Type>(MyMethodThatMatchesTheActionDelegateSignature);
        }

        public void Do<T>(Action<T> action)
        {
        }

        private void MyMethodThatMatchesTheActionDelegateSignature(Type type)
        {
        }

Ok, hopefully that makes sense! Now on to the good stuff. Suppose we created a type that implemented the IDisposable interface, and took in our closing action. This action would run when a process is completed. In this scenario the "Dispose" method is not being used to clean up resources, but rather to signal the end of a running process.

For instance suppose we wanted to write a message to the console upon completion of a long running process.

            using (new DisposableConsoleLogger("Finished running...")) {
                // do something
            }

The above code uses the "using" block to wrap a sequence of events to call an action when the sequence of events is completed. When the "do something" block of code is completed the "Finished running..." message will be spit out to the console.

The underlying implementation looks like this...

    public class DisposableAction<T> : IDisposableAction {
        public DisposableAction(Action<T> _action, T _itemToActOn) {
            this._action = _action;
            this._itemToActOn = _itemToActOn;
        }

        public void Dispose() {
            _action(_itemToActOn);
        }

        private Action<T> _action;
        private T _itemToActOn;
    }

    public class DisposableConsoleLogger : DisposableAction<string> {
        public DisposableConsoleLogger(string completionMessage) : base(Console.Out.WriteLine, completionMessage){}
        public DisposableConsoleLogger() : base(Console.Out.WriteLine, "completed action"){}
    }

Perhaps the following block of code might make a little more sense to you now...

        using (mockery.Record()) {
            // ReplayAll()
        }
        using (mockery.Playback()) {
            // VerifyAll()
        }

Source Code (1.94 KB)

#

The Visitor Pattern

Friday, November 16, 2007 11:00:13 PM (Mountain Standard Time, UTC-07:00)

One of the many cool things we learned last week was on how to traverse a collection using a visitor.

"...the visitor design pattern is a way of separating an algorithm from an object structure. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures." - wikipedia

Let's pretend that I've got an exam, and this exam has a bunch of questions and I want to find out how many questions have been completed.

I could throw a method on my IExam type that returns the number of completed questions. Kind of like...

    public class BadExam : IExam {
        public BadExam( ) : this( new List< IQuestion >( ) ) {}

        public BadExam( IList< IQuestion > questions ) {
            _questions = questions;
        }

        public int GetCompletedQuestions( ) {
            int completedQuestions = 0;
            foreach ( IQuestion question in _questions ) {
                completedQuestions += question.IsComplete( ) ? 1 : 0;
            }
            return completedQuestions;
        }

        private IList< IQuestion > _questions;
    }

 

But what happens when I want to find out other statistics about the questions in my exam. I could add additional methods to the IExam type for each type of information that I want to query on, but this would totally violate the Open/Closed Principle.

Let's try to solve the same problem above using a visitor...

    public class Exam : IExam {
        public Exam( ) : this( new List< IQuestion >( ) ) {}

        public Exam( IList< IQuestion > questions ) {
            _questions = questions;
        }

        public void TraverseUsing( IVisitor< IQuestion > visitor ) {
            foreach ( IQuestion question in _questions ) {
                visitor.Visit( question );
            }
        }

        private IList< IQuestion > _questions;
    }

What this allows me to do is create new implementations of IVisitor's that traverse the collection of questions but collect information that it needs.

For example we could have a "CompletedQuestionsVisitor" that keeps track of the number of completed questions.

    public class CompletedQuestionsVisitor : ICompletedQuestionsVisitor {
        private int _completedQuestions;

        public void Visit( IQuestion question ) {
            _completedQuestions += ( question.IsComplete( ) ? 1 : 0 );
        }

        public int TotalCompletedQuestions( ) {
            return _completedQuestions;
        }
    }

Now I can traverse the internal collection of questions and pick out the information that I need.

What if I wanted to build a tree of specifications and wanted to traverse a collection of items and keep track of only those items that match my composite specification. Introducing the "Specification Visitor".

    public class SpecificationVisitor< T > : ISpecificationVisitor< T > {
        private readonly ISpecification< T > _specification;
        private int _totalMatching;

        public SpecificationVisitor( ISpecification< T > specification ) {
            _specification = specification;
        }

        public void Visit( T item ) {
            _totalMatching += _specification.IsSatisfiedBy( item ) ? 1 : 0;
        }

        public int TotalMatching( ) {
            return _totalMatching;
        }
    }

Yes it's a little overboard and slightly contrived, but perhaps someone can find a good home for him.

Source Code (2.28MB)

#

Spiking Active Reports

Friday, November 02, 2007 10:03:21 AM (Mountain Standard Time, UTC-07:00)

After the troubles we faced working with Crystal Reports in the last sprint my manager gave me the permission to go and spike Active Reports .NET to see what I could find... so far... so good!

Right off the bat the report designer is a lot like the Win Forms designer. You can drag and drop Active Reports.NET controls like the "Label", "TextBox", "CheckBox", and "RichTextBox" controls. This generates a "*.designer.cs" file, just like a win form.

active_reports_toolbox

I like this because it's intuitive, I already have knowledge working with WinForms so I don't have go learn how a completely new designer behaves. Also I have access to the code behind. (I can see what's going on!)

Reports seem to be super easy to build. Each report inherits from "ActiveReport3" and can be access almost like any ol' "plain old clr object" (POCO). The quick and easy from running a report might look something like...

            SimpleReport report = new SimpleReport( );
            report.DataSource = CreateDtosList( );
            report.Run( false );
            this.uxReportViewerControl.Document = report.Document;

The "SimpleReport" type inherits from "ActiveReport3" and represents the report that we want to view. The DataSource property can be bound to a type that implements the IEnumerable interface. The call to "Run" binds the data to the report and creates an in memory representation of the report which can then be bound a report viewer control which is what takes place in the following line. That's the quick and dirty...

TableOfContentsControl

The above images shows the report viewer control a table of contents panel. This panel will show any "bookmarks" that are tagged in the report. To set a bookmark in different sections of a report you can create a handler for the "Format" event of the detail section of the report. Each report can have a report header/footer, group header/footer and a detail section. (You can embed multiple sub reports into a detail section)

    public partial class SimpleReport : ActiveReport3 {
        public SimpleReport( ) {
            InitializeComponent( );

            this.detail.Format += delegate { detail.AddBookmark( uxQuestionText.Value.ToString( ) ); };
        }

The above code sample creates a handler for the "Format" event and adds a bookmark to the detail section with the name of the question.

My feeling after spiking Active Reports is that I like it. I'm sure I haven't covered everything that it has to offer, but I have confidence that I could use it the way i need it to work. The way any good tool should work. I really enjoy being able to access the object model and the ability to bind custom collections to the view. I like how the development seems to familiar to a winforms model, and I feel that given some creativity you can use Active Reports .NET the way that you want to use it, not the way it wants you to use it.

After tinkering with the quick and dirty, I started to try to evolve to something a little more extensible. My pair and I thought of perhaps modelling the report as a type that contains a listing of sections. E.g. a report has a header section, and a footer section and a table of contents section. We started moving towards a model where a section builder would build a section and bind the necessary information to that section. The section builder would then add the section the report.

Here's kind of what we came up with...

    public class ResultsSectionBuilder : ISectionBuilder {
        public ResultsSectionBuilder( IResultSectionTask task ) {
            _task = task;
        }

        public void BuildFrom( IMainReport report ) {
            BuildFrom( report, new ResultsSection( ) );
        }

        public void BuildFrom( IMainReport report, IResultsSection section ) {
            report.AddSection( section.BindTo( _task.GetResults( ) ) );
        }

        private readonly IResultSectionTask _task;
    }

The idea is that when the report is run, the report will ask it's section builder to build their sections and add it to it. Maybe this might flush it out a bit more...

    public class MainReport : IMainReport {
        public MainReport( ) : this( new List< ISectionBuilder >( ) ) {}

        public MainReport( IList< ISectionBuilder > builders ) {
            _builders = builders;
            _sections = new List< IReportSection >( );
        }

        public void AddSection( IReportSection section ) {
            _sections.Add( section );
        }

        public IMainReport Run( ) {
            foreach( ISectionBuilder builder in _builders ) {
                builder.BuildFrom( this );
            }
            return this;
        }

        private readonly IList< ISectionBuilder > _builders;
    }

Now that I'm typing this out, I'm thinking that this is a form of double dispatch, which could move to a visitor pattern. I have to admit I'm a little shy of the visitor because it seems awkward. But after reading Jeremy Millers post last night, I'm questioning whether I need to better understand how to use it or recognize good uses of it.

We never completely flushed out this work, but hopefully it sparks some ideas... Source code (5.4 MB)

I hope this helps you to think about how to build more extensible reports. I still have a lot to learn in this category, but I know you can build reports that don't rely on data sets. Hopefully, time will tell me which is more practical and worth investing time into.

One last thought, I really like how you can just download the active reports assemblies and start building learning without a license. The licensing model seems to be great, when you work with the trial version you get a little caption on the report that indicates that a trial version is being used. If you like the reports and working with it, you can go out and buy yourself a developer license and deploy as you like. It really does seem like Active Reports was built as a tool to aid the developer as opposed to trying to squeeze out pennies out of end users.

Reference material:

#

Decorating Services

Saturday, October 27, 2007 9:41:19 PM (Mountain Standard Time, UTC-07:00)

So tonight I decided to spend some time playing with services, principals, identities, and loggers. On Thursday at work a client wanted to be able to log several different events in a system. I remember a while back reading an article on MSDN by Oren on Ioc, and I thought I would try to roll something out just to get a feel for who it could work. I still have a lot to learn when it comes to IoC so I put that aside for now.

It all starts at the "AuthenticationService" in a method called "CheckCredentials". It looks something like...

        public bool CheckCredentials( string userName, string password ) {
            IUser user = _repository.FindBy( userName );
            if ( IsMatch( user.Password, password ) ) {
                ApplyPrincipalToThreadFor( user );
                return true;
            }
            return false;
        }
 

This method checks the repository for the user with the matching username and checks to see if the password given matches what's stored for the user in the repository. If it does, a principal is created and applied to the current thread. Passwords really shouldn't be held in memory for long, and would probably better be transferred or computed as a hash, so that the actual password exposure is limited. (There's also a "SecureString" type which I haven't spent much time looking at, but sounds promising!)

Now if I wanted to log all login attempts I can extend this service with a AuthenticationLoggerService decorator. That looks like... 

    public class AuthenticationLoggerService : IAuthenticationService {
        public AuthenticationLoggerService( IAuthenticationService service, ILogger logger ) {
            _service = service;
            _logger = logger;
        }
 
        public bool CheckCredentials( string userName, string password ) {
            _logger.Write( "User Login Attempt: " + userName );
            return _service.CheckCredentials( userName, password );
        }
 
        private readonly IAuthenticationService _service;
        private readonly ILogger _logger;
    }

All this type does is log information and delegate to the actual type.

"The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide flexible alternative to subclassing for extending functionality." - Head First Design Patterns

Read more in...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

PlayingWithServices.zip (2.28 MB)

#

Complexity Simplified

Saturday, October 27, 2007 12:47:17 AM (Mountain Standard Time, UTC-07:00)

I'm currently reading...

Domain-Driven Design: Tackling Complexity in the Heart of Software
by Eric Evans

Read more about this title...

It's really as good as they say it is! And it's got me thinking... I really enjoy reading a book that makes me think, I sometimes prefer reading tech books that only give you concepts to think about. It's up to you to understand those concepts then find a way to implement them when you see their use is necessary. There's a lot of great concepts that came from this book, and after seeing them out in the wild in episodes of DNRTV and source code buried in svn repositories it's all starting to make sense...

  • Entities: An object defined primarily by its identity is called an Entity.
  • Value Objects: An object that describes some characteristic or attribute but carries no concept of identity.
  • Aggregates: A cluster of associated objects that are treated as a unit for the purpose of data changes.
  • Repositories: A mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
  • Services: An operation offered as an interface that stands alone in the model, with no encapsulated state.
  • Specifications: A predicate that determines if an object does or does not satisfy some criteria.

*Note: the definitions above are right out of the glossary.

The toughest part to grasp and seems to be the underlying theme of this book is "The Ubiquitous Language". The tough part is not grasping the "concept" but rather the implementation. The concept makes a lot of sense, but how you can practically apply it is a separate story. One that I think takes experience through trial and error. Time will tell...

Go buy this book, I know I will... until then thank you Mr. Adam! (just in case I can't I put it on my wish list for Santa, he always pulls through!)

After reading through some examples on specifications and reading through JP's example, this sparked some ideas in my mind. So I hacked together some code and came up with this. Let's say I've got a bank of questions, and that each question is part of a category, and I want to be able to search through the bank of questions...

[Test]
public void Should_Return_3_Questions_That_Are_Not_Math( ) {
    IEnumerable< IQuestion > matches =
        CreateSut( ).FindAllWhere( Question.IsIn( Any.Category ).But( Not.In( Category.Math ) ) );
    Assert.AreEqual( 3, GetCountFor( matches ) );
}

Notice the use of "But", I wonder if this will catch on...

Basically I started looking into creating specification for boolean operations, with a slightly different take from what the book offered and inspired by JP and Ayende. I'm not sure it's the most elegant interface, but I really wanted to be able to make the client code as readable as possible.

What I ended up with was types like "Is", "Not", "And" & "Or". I'm not sure I'm completely happy with the end product, but I see potential for extending this further, and the best part is how readable the code seems to be. I think that excites me more then anything else... I think I'm just starting to understand this concept of the "fluent" interface. Not truly implementing it well, seems to be difficult, but fun!

Here's what my Question type turned in too...

    public class Question : IQuestion {
        public Question( ICategory category ) {
            _category = category;
        }

        public ICategory Category {
            get { return _category; }
        }

        public static ISpecification< IQuestion > IsIn( ICategory category ) {
            return Is.In( category );
        }

        public static ISpecification< IQuestion > IsNotIn( ICategory category ) {
            return Not.In( category );
        }

        private readonly ICategory _category;
    }

The Is type looks like...

    public class Is {
        public static ISpecification< IQuestion > In( ICategory category ) {
            return new Specification< IQuestion >(
                delegate( IQuestion question ) { return category.Equals( question.Category ); }
                );
        }
    }

And the "Not" type looks like...

    public class Not {
        public static ISpecification< IQuestion > In( ICategory category ) {
            return new Specification< IQuestion >(
                delegate( IQuestion question ) { return !category.Equals( question.Category ); }
                );
        }
    }

To me it still seems that the "Not" and "Is" types shouldn't be responsible for returning the specification, and that responsibility should belong to the Question, but I'm just not sure... and it's getting rather late so I should head to bed.

Source is attached!

PlayingWithSpecifications.zip (2.17 MB)

#

Mocking Out Crystal Reports

Wednesday, October 24, 2007 2:57:39 PM (Mountain Standard Time, UTC-07:00)

So I'm still suffering from working with Crystal Reports. Here's some funniness I'm having trouble understanding.. maybe YOU can help!

I'm trying to calculate a page count for a section in a crystal report. Here's what my test looks like:

 [Test] public void Should_Be_Able_To_Calculate_Page_Count( ) { MockRepository mockery = new MockRepository( ); ReportDocument stubReport = mockery.Stub< ReportDocument >( ); FormatEngine stubEngine = mockery.Stub< FormatEngine >( ); using( mockery.Record( ) ) { Expect.Call( stubReport.FormatEngine ).Return( stubEngine ); Expect.Call( stubEngine.GetLastPageNumber( null ) ).IgnoreArguments( ).Return( 1 ); } using( mockery.Playback( ) ) { int count = new ExecutiveSummarySection( stubReport ).CalculatePageCount( ); Assert.AreEqual( 1, count ); } } }

I'm trying to retrieve the last page number for a section in a crystal report so that i can generate a table of contents. It seems that this trivial task isn't as easy as I believe it should be, so this is my work around. The code to pass this test looks like this:

 internal class ExecutiveSummarySection { public ExecutiveSummarySection( ReportDocument report ) { _report = report; } public int CalculatePageCount( ) { return _report.FormatEngine.GetLastPageNumber( new ReportPageRequestContext( ) ); } private readonly ReportDocument _report; }

 

But when I run the test I get this error...

Tests run: 398, Failures: 1, Skipped: 0, Ignored: 0
Failures:
1) ExecutiveSummaryTest.Should_Be_Able_To_Calculate_Page_Count :
Can't find a constructor with matching arguments
   at Rhino.Mocks.MockRepository.MockClass(CreateMockState mockStateFactory, Type type, Type[] extras, Object[] argumentsForConstructor)
   at Rhino.Mocks.MockRepository.CreateMockObject(Type type, CreateMockState factory, Type[] extras, Object[] argumentsForConstructor)
   at Rhino.Mocks.MockRepository.Stub(Type type, Object[] argumentsForConstructor)
   at Rhino.Mocks.MockRepository.Stub[T](Object[] argumentsForConstructor)
   at ExecutiveSummaryTest.Should_Be_Able_To_Calculate_Page_Count() in c:\development\MediaLogic\...\ExecutiveSummaryTest.cs:line 13

I don't get it... so i popped open reflector to see what I might be able to find. It turns out that the "FormatEngine" type is located in an assembly called "CrystalDecisions.CrystalReports.Engine" which is installed in the GAC. (I haven't quite found out how to pull this out of the GAC so that we can xcopy deploy this assembly with the rest, and i don't believe you can. Correct me if i'm wrong, please!)

Also, the constructor on "FormatEngine" is defined as 'internal'. I noticed that the "FormatEngine" type is implementing the interface "IReportSource". So I tried stubbing that out instead in place of the "FormatEngine" property on the "ReportDocument". On got this message:

Tests run: 398, Failures: 1, Skipped: 0, Ignored: 0
Failures:
1) ExecutiveSummaryTest.Should_Be_Able_To_Calculate_Page_Count :
Type 'IReportSourceProxyb9462264e9bb45c1a40d67229a43aa9c' doesn't match the return type 'CrystalDecisions.CrystalReports.Engine.FormatEngine' for method 'ReportDocument.get_FormatEngine();'
   at Rhino.Mocks.Expectations.AbstractExpectation.AssertTypesMatches(Object value)
   at Rhino.Mocks.Expectations.AbstractExpectation.set_ReturnValue(Object value)
   at Rhino.Mocks.Impl.MethodOptions.Return(Object objToReturn)
   at ExecutiveSummaryTest.Should_Be_Able_To_Calculate_Page_Count() in c:\development\MediaLogic\...\ExecutiveSummaryTest.cs:line 16

That makes sense... So how do i get around this?

#

Crystal Unclear Nightmares

Saturday, September 29, 2007 7:01:14 AM (Mountain Standard Time, UTC-07:00)

Yesterday I had the privelage of creating my first report using Crystal Reports. I had never used it prior to then, and I thought "how hard could this be", after all I was just generating a pdf. How hard should that be?

Well it turns out, that it was much harder then I expected. Crystal is one huge beast, with one of the craziest object models I've seen so far. Who the heck wrote this stuff?

It would be nice if I could just include the crystal libraries in our project and just xcopy the libraries without having to install anything, but that's not the case. I can XCopy the following assembly's:

  • CrystalDecisions.CrystalReports.Engine
  • CrystalDecisions.ReportSource
  • CrystalDecisions.Shared
  • CrystalDecisions.Windows.Forms

But the following assembly's are stored up in the GAC, when you install Crystal to. (Perhaps I need to look into pulling assembly's out of the GAC and just including them with the project, but something tells me that this might be a dead end.)

  • CrystalDecisions.Enterprise.Framework
  • CrystalDecisions.Enterprise.InfoStore

Oh fine... next up is poking at the object model. Whenever you create a new "Crystal Report" it generates an ".rpt" file and a code behind for that ".rpt" file. The code behind contains a definition for a class that represents that report. This class inherits from a type called "ReportClass", which inherits from a type called "ReportDocument".

public class MyReport : ReportClass { ... }
	
 

The following photo kind of sums up the nightmare I had yesterday in learning Crystal Reports.

CrystalReportsWhiteBoard

  • Report Document has a property of type DataDefinition.
  • DataDefinition has a property called ParameterFields of type ParameterFieldDefinitions.
  • ParameterFieldDefinitions has a few indexers to access its collection of "ParameterFieldDefinition".
  • ParameterFieldDefinition has a method called "ApplyCurrentValues(IParameterValues)" and an overload of the same method that takes in "ParameterValues".

Why is this overload necessary? Well because ParameterValues does not implement IParameterValues. (Huh?)  

So let's dig into this a little bit deeper.... ParameterValues inherits from Arraylist. 

public class ParameterValues : ArrayList{}

ParameterValues

 IParameterValues implements IList.

public class IParameterValues : IList{}

IParameterValues

And ArrayList implement IList....

ArrayList

But... ParameterValues does not implement IParameterValues... so I CANT treat a ParameterValues type as an IParameterValues type, hence the overloaded method above. One takes in a ParameterValues type and the other a IParameterValues type. So how do I bridge this?

I create a type that implements IParameterValues and inherits from ParameterValues and I now have a single type that satisfies both, which in my opinion should have been done in the first place... but wait there's more!

    internal class Parameters : ParameterValues, IParameterValues {
        public ParameterRangeValue AddRangeValue( object lowerBound,
                                                  object upperBound,
                                                  RangeBoundType lowerBoundType,
                                                  RangeBoundType upperBoundType ) {
            throw new NotImplementedException( );
        }
    }

 The IParameterValues interface has one additional method that is not defined in ParameterValues. (ooooh man!)

All of this has left my head spinning... Must things be so complicated?

Did I mention lack of strong typing, yes I know generics didn't show up until .NET 2.0 but event still there were ways to create more strongly typed objects in the 1.1. days, that's no excuse to use type "object" everywhere.

And please, please, consider using composition over inheritance, it simplifies things sooo very much. When I started inspecting Crystal in reflector, I first focused on the interfaces to get an overall sense for how the beast works, but if the types I expect to be implementing the interfaces aren't, then what's the point of having them? If this is your idea of open for extension, I think it's rather silly. But who am i to judge, i'm but a simple jr. developer.

Moving on... I was experiencing some funny business when I was binding my report to a crystal report viewer. (I don't know if i mentioned this yet, but this is for a desktop application.) And the stack trace ended up leading me to a method called "Load" defined in the "ReportClass". This is an override of a virtual Load method defined in the "ReportDocument" class.

This following line of code made me throw up a little bit in my mouth...

ReportClass_Load

The load method is checking to see if the "HttpContext.Current" value is equal to null. (Remember this is running in a winforms application.) This means that crystal is loading the System.Web assembly up into my app domain so that it can check the HttpContext.Current value. This is not what I would expect, or want.

Well I have probably ranted enough for one morning... I can't believe how long I have just spent crafting up this post, but I really don't like Crystal Reports. At the end of the day, all i want to do is generate a pdf with text and images on it.

"Can It Be All So Simple" - Wu-Tang Clan

#

IBindableTextBox<T>

Tuesday, September 25, 2007 7:40:42 PM (Mountain Standard Time, UTC-07:00)

About a week ago I described how you can use a command to format a phone number in a textbox. I'd like to offer you a new way of formatting the same phone number, in the text box. This time around we'll be binding the IPhoneNumber type directly to the text box. When changes are made to the text in the text box a new phone number type will be constructed and bound to the text box. Without further ado I would like to present to you the BindableTextBox<T>...

    public class BindableTextBox< T > : IBindableTextBox< T > {
        public BindableTextBox( TextBox control, CreateType< T > method ) {
            _control = control;
            _method = method;

            _control.Leave += delegate { BindTo( _method.Invoke( _control ) ); };
        }

        public T Value {
            get { return _value; }
        }

        public void BindTo( T item ) {
            _value = item;
            _control.Text = _value.ToString( );
        }

        private readonly TextBox _control;
        private readonly CreateType< T > _method;
        private T _value;
    }

This is a generic type that will bind the text box control text property to the value returned by the type 'T's "ToString()" override. The "CreateType<T>" parameter is a delegate that is used to construct a new instance of type <T> on the controls "leave" event. The CreateType delegate is declared as follows:

public delegate T CreateType< T >( Control usingControl );

When it's time to flush data from the view back to the domain, you can inspect the BindableTextBox's "Value" property which will hand you the current value contained in the type. In this example it would hand you the current "IPhoneNumber". This may work well for simple types, but maybe not so much on more complex types. One thing you could do is change the input parameter of the CreateType delegate to take in a "IBindableTextBox" instead of a control, thus giving you access to the current "Value" that is bound to the text box, in case you need to copy over additional information to the new type.

Either way to use this type it's about as simple as this:

    public partial class PhoneNumberView : Form {
        public PhoneNumberView( ) {
            InitializeComponent( );
            _phoneNumber = new BindableTextBox< IPhoneNumber >( uxPhoneNumberTextBox, CreateTypeFactory.PhoneNumber );
        }

        private IBindableTextBox< IPhoneNumber > _phoneNumber;
    }

As usual the full source is provided...

PhoneNumberView2.cs.txt (1.7 KB)

#

SALES TAXES

Monday, September 24, 2007 7:07:23 PM (Mountain Standard Time, UTC-07:00)

I recently came across a problem, and I thought I would try to flex some of my developer muscle to try to solve it. The problem reads as follows:

Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.

When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid.  The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.

Write an application that prints out the receipt details for these shopping
baskets...
INPUT:_

Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85

Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50

Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25

OUTPUT

Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83

Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15

Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
==========

To solve this problem I used a composite to calculate taxes. The "TaxComposite" type allows you to bundle several different taxes all in one type. So when calculating taxes, the calculation with iterate through all the taxes and add the calculated tax and return the total value.

    public class TaxComposite : ITax {
        public TaxComposite( params ITax[] taxes ) : this( new List< ITax >( taxes ) ) {}

        public TaxComposite( IEnumerable< ITax > taxes ) {
            _taxes = new List< ITax >( taxes );
            _amount = CalculateAmount( );
            _type = CalculateType( );
        }

        public double Amount {
            get { return _amount; }
        }

        public TaxTypes Type {
            get { return _type; }
        }

        public IMoney CalculateTaxFor( IMoney price ) {
            return CalculateTaxFor( price, RoundingDelegateFactory.RoundToNearestTenCents );
        }

        public IMoney CalculateTaxFor( IMoney price, RoundingStrategy round ) {
            IMoney total = new Money( );
            Summary( delegate( ITax tax ) { total = total.Add( tax.CalculateTaxFor( price, round ) ); } );
            return total;
        }

        private double CalculateAmount( ) {
            double amount = 0d;
            Summary( delegate( ITax tax ) { amount += tax.Amount; } );
            return amount;
        }

        private TaxTypes CalculateType( ) {
            TaxTypes type = TaxTypes.None;
            Summary( delegate( ITax tax ) { type = type | tax.Type; } );
            return type;
        }

        private void Summary( Action< ITax > toDo ) {
            foreach ( ITax tax in _taxes ) {
                toDo( tax );
            }
        }

        private readonly IList< ITax > _taxes;
        private readonly double _amount;
        private readonly TaxTypes _type;
    }

"The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." - Head First Design Patterns

I used a TaxFactory type to construct the TaxComposite type which gathers all the taxes that match a specified predicate and injects it into the TaxComposite constructor. It looks like...

    public static class TaxFactory {
        public static ITax Create( TaxTypes forTaxes ) {
            return new TaxComposite(
                Taxes.FindBy( delegate( ITax tax ) { return ( tax.Type & forTaxes ) == tax.Type; } ) );
        }

The tax type is an enum that uses the flags attribute so that I can enable different bits for different taxes.

    [Flags]
    public enum TaxTypes {
        None = 0x00,
        Sales = 0x01,
        Import = 0x02
    }

Taxes is a static type that contains different types of taxes. The FindBy method allows for different strategies to be passed into to gather different types of taxes based on different critera. The above example returns all the taxes that are enabled in the "forTaxes" argument. FindBy is defined like...

        public static IEnumerable< ITax > FindBy( Predicate< ITax > condition ) {
            foreach ( ITax tax in taxes ) {
                if ( condition( tax ) ) {
                    yield return tax;
                }
            }
        }

I'm not sure if this is the most flexible design, but if i need to make changes to tax rates I can do that in one spot. The only catch is that it requires a re-compile to take a effect. In a full blown implementation I may want to consider using a "service" to retrieve the tax rates. Also, in this implementation in order to add new taxes I have to added it too 2 different locations. The first is the TaxTypes enum and the second is the Taxes static holder class. This leaves a bit of a smell...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

#

Using a Command to Format a Phone Number

Sunday, September 16, 2007 4:15:15 PM (Mountain Standard Time, UTC-07:00)

I've got an issue where I need to format a phone number as soon as a user clicks away from the phone number text box. So a phone number like (403) 555 - 7777 gets formatted to 4035557777 as soon as focus is removed from the text box. The view looks something like this....

phoneNumberView

When the phone number (403) 555 - 7777 get's entered, it should get formatted to 4035557777.

Before: After:
phoneNumberViewBefore phoneNumberViewAfter

To do this I created a "FormatPhoneNumberCommand" type who's only purpose is to update the phone number when it is executed. It looks like this:

    internal class FormatPhoneNumberCommand : IFormatPhoneNumberCommand {
        public FormatPhoneNumberCommand( Control control ) {
            _control = control;
        }

        public void Exexute( ) {
            _control.Text = new PhoneNumber( _control.Text ).Number;
        }

        private readonly Control _control;
    }

The "PhoneNumber" type is updating the format of the phone number upon construction, it looks like this:

    public class PhoneNumber : IPhoneNumber {
        public PhoneNumber( string number ) {
            const string expression = @"[\(\)\-\ ]";
            _number = ( null != number ) ? Regex.Replace( number, expression, String.Empty ) : string.Empty;
        }

        public string Number {
            get { return _number; }
        }

        public bool IsValid( ) {
            string tenDigitNumberExpression = @"^(\d{10})*$";
            return !string.IsNullOrEmpty( _number ) && Regex.IsMatch( _number, tenDigitNumberExpression );
        }

        public override string ToString( ) {
            return _number;
        }

        private readonly string _number;
    }

I want the command object to be executed on the text box controls "Leave" event. To capture this event I create a type that's only purpose to maintain a reference to the command object execute method. I don't want to declare a local field to hang on to a reference to the command object, so i delegate that task to the DelegateAggregator type. Which is used like this:

            _aggregator = new DelegateAggregator( );

            uxPhoneNumberTextBox.Leave +=
                _aggregator.CreateHandler( new FormatPhoneNumberCommand( uxPhoneNumberTextBox ).Execute );

I can now re-use the same delegate aggregator to hold onto references to other command methods, without having to declare a local field for individual command object. The DelegateAggregator type is defined like so...

    internal class DelegateAggregator : IDelegateAggregator {
        public DelegateAggregator( ) : this( new List< Delegate >( ) ) {}

        private DelegateAggregator( IList< Delegate > delegates ) {
            _delegates = delegates;
        }

        public EventHandler CreateHandler( MethodInvoker command ) {
            _delegates.Add( command );
            //return delegate( object sender, EventArgs e ) { command( ); }; // same as line below
            return delegate { command( ); }; // c# compiler implicitly adds the sender and e params.
        }

        private readonly IList< Delegate > _delegates;
    }

The CreateHandler method takes in a "MethodInvoker" delegate as it's input parameter. The signature for this delegate takes in no input parameters and returns void. The purpose of the DelegateAggregator is to maintain references to delegates, which in this scenario is implicitly maintaining a reference to the command object without having to explicitly declare a local field to refer to the command object.

PhoneNumberView.cs.txt (2.18 KB)

#

Those Darn Checkboxes

Thursday, September 13, 2007 8:26:33 PM (Mountain Standard Time, UTC-07:00)

Tonight I spent sometime playing with checkboxes! (Yes I know, I should get out more...) Here's what I learned. Let's say you've got a form with a group of checkboxes. That might look something like this:

CheckBoxGroup Yes I know this is one of the most impressive forms you've ever seen. But let's say that you've got a group of checkboxes and you need to capture which checkboxes are selected. You could wire up an event handler for the "Save" button's click event, then write up a bunch of if-else statements to see which checkboxes are checked and yada yada...

 

Your code might look something like...

            if ( checkBox1.Checked ) {}
            if ( checkBox2.Checked ) {}
            if ( checkBox3.Checked ) {}

 

I didn't like this so I wanted to come up with a different way, something that's not so smelly. Here's what I came up with. The ICheckBoxGroup<T> where T is a full blown type that represents something in the real world.

    internal interface ICheckBoxGroup< T > {
        void Add( CheckBox checkbox, T item );
        IEnumerable< T > GetAllEnabled( );
        IEnumerable< T > GetAllThatSatisfies( Predicate< CheckBox > condition );
    }

This allows me to bind a full blown domain object to each checkbox. In this example I'm binding a Sport to each checkbox.

            ICheckBoxGroup< ISport > group = new CheckBoxGroup< ISport >( );
            group.Add( checkBox1, Sport.Hockey );
            group.Add( checkBox2, Sport.BasketBall );
            group.Add( checkBox3, Sport.FootBall );
            group.Add( checkBox4, Sport.Golf );
            group.Add( checkBox5, Sport.Tennis );

When the "Save" button is clicked I'm asking for all the Sports that have been selected like this...

    StringBuilder builder = new StringBuilder( );
    foreach ( ISport employee in group.GetAllEnabled( ) ) {
        builder.AppendFormat( "{0}{1}", employee, Environment.NewLine );
    }
    MessageBox.Show( builder.ToString( ) );

The "GetAllEnabled" method is returning an IEnumerable<ISport>. This means there's no conversion from if checkbox1.checked == true then Hockey was selected. You're just handed back the type that the checkbox represents, no translation required. The implementation of CheckBoxGroup<T> looks like this:

    public class CheckBoxGroup< T > : ICheckBoxGroup< T > {
        public CheckBoxGroup( ) {
            _checkboxes = new List< CheckBox >( );
        }

        public void Add( CheckBox checkbox, T item ) {
            checkbox.Tag = item;
            checkbox.Text = item.ToString( );
            _checkboxes.Add( checkbox );
        }

        public IEnumerable< T > GetAllEnabled( ) {
            return GetAllThatSatisfies( delegate( CheckBox box ) { return box.Checked; } );
        }

        public IEnumerable< T > GetAllThatSatisfies( Predicate< CheckBox > condition ) {
            foreach ( CheckBox checkBox in _checkboxes ) {
                if ( condition( checkBox ) ) {
                    yield return ( T )checkBox.Tag;
                }
            }
        }

        private readonly IList< CheckBox > _checkboxes;
    }

Just remember to override ToString on your types otherwise the default implementation will just write the fully qualified name of your type as the text next to your checkbox. I know this example could be greatly improved, but after a bus ride home pondering about this, this was what I could come up. Feel free to toss me your example.

PlayingWithCheckboxes.txt (2.4 KB)

#

Playing With The Predicate Delegate

Tuesday, September 11, 2007 7:55:32 PM (Mountain Standard Time, UTC-07:00)

While digging through the .NET Framework I came across another sweet little delegate called "The Predicate Delegate." Say it with me now, "Predicate Delegate". It's got a nice ring to it, don't you think? It's signature looks like this...

public delegate bool Predicate<T>(T obj);

So let's play with another contrived example. Let's pretend I've got a question bank full of questions. And each question belongs to a particular category, and I need to be able to retrieve a set of questions by category.

    public interface IQuestion {
        ICategory Category { get; }
        string Text { get; }
    }

    public interface ICategory {
        string Name { get; }
    }

    public interface IQuestionBank {
        IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate );
    }

Take a look at the IQuestionBank.FindBy method. Notice that it takes in a Predicate delegate as it's input parameter, and returns a set of IQuestion's. Let's take a look at how the FindBy method could be implemented.

    public class QuestionBank : IQuestionBank {
        public QuestionBank( ) {
            _questions = new List< IQuestion >( );
            _questions.Add( new Question( Category.English, "Do you like English?" ) );
            _questions.Add( new Question( Category.Math, "What is 2 + 2?" ) );
            _questions.Add( new Question( Category.English, "Can you spell?" ) );
            _questions.Add( new Question( Category.Math, "What is 3 + 3?" ) );
        }        

        public IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate ) {
            foreach ( IQuestion question in _questions ) {
                if ( predicate( question ) ) {
                    yield return question;
                }
            }
        }
        private readonly IList<IQuestion> _questions;
    }

The FindBy method is iterating through the internal list of questions and only returning the questions that match the predicate's criteria defined by the client of the code. This means that the client can define an anonymous method to do the filtering, you could use a strategy to interchange filtering algorithms at runtime to produce dynamic querying.

Here's a couple of different ways you could perform the querying. One uses the pre-defined delegate for filtering all the English questions, and the other uses an anonymous delegate to define the filter criteria.

    public class PredicateDelegateFactory {
        public static Predicate< IQuestion > EnglishFilter =
            delegate( IQuestion question ) { return question.Category.Equals( Category.English ); };

        public static Predicate< IQuestion > MathFilter =
            delegate( IQuestion question ) { return question.Category.Equals( Category.Math ); };
    }

    public class Bootstrap {
        public static void Main( ) {
            IQuestionBank questionBank = new QuestionBank( );

            Console.Out.WriteLine( "Searching for all English questions..." );
            foreach ( IQuestion question in questionBank.FindBy( PredicateDelegateFactory.EnglishFilter ) ) {
                Console.Out.WriteLine( question );
            }

            Console.Out.WriteLine( );
            Console.Out.WriteLine( "Searching for all Math questions..." );
            foreach ( IQuestion question in
                questionBank.FindBy( delegate( IQuestion item ) { return item.Category.Equals( Category.Math ); } ) ) {
                Console.Out.WriteLine( question );
            }

            Console.In.ReadLine( );
        }
    }

This yields an output of....

PredicateDelegateOutput

Why is this useful?

This allows you to specify the criteria for querying data from the question repository without having to modify the IQuestionBank implementation. This closes the repository for modification but leaves it open for extension.

The full source for this example for your viewing pleasure!

    //public delegate bool Predicate< T >( T obj );

    public interface IQuestion {
        ICategory Category { get; }
        string Text { get; }
    }

    public interface ICategory {
        string Name { get; }
    }

    public interface IQuestionBank {
        IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate );
    }

    public class Question : IQuestion {
        public Question( ICategory category, string text ) {
            _category = category;
            _text = text;
        }

        public ICategory Category {
            get { return _category; }
        }

        public string Text {
            get { return _text; }
        }

        public override string ToString( ) {
            return Text;
        }

        private readonly ICategory _category;
        private readonly string _text;
    }

    public class Category : ICategory, IEquatable< Category > {
        private Category( string name ) {
            _name = name;
        }

        public string Name {
            get { return _name; }
        }

        public static readonly ICategory Math = new Category( "Math" );
        public static readonly ICategory English = new Category( "English" );

        public bool Equals( Category category ) {
            if ( category == null ) {
                return false;
            }
            return Equals( _name, category._name );
        }

        public override bool Equals( object obj ) {
            if ( ReferenceEquals( this, obj ) ) {
                return true;
            }
            return Equals( obj as Category );
        }

        public override int GetHashCode( ) {
            return _name.GetHashCode( );
        }

        private readonly string _name;
    }

    public class QuestionBank : IQuestionBank {
        public QuestionBank( ) {
            _questions = new List< IQuestion >( );
            _questions.Add( new Question( Category.English, "Do you like English?" ) );
            _questions.Add( new Question( Category.Math, "What is 2 + 2?" ) );
            _questions.Add( new Question( Category.English, "Can you spell?" ) );
            _questions.Add( new Question( Category.Math, "What is 3 + 3?" ) );
        }

        public IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate ) {
            foreach ( IQuestion question in _questions ) {
                if ( predicate( question ) ) {
                    yield return question;
                }
            }
        }

        private readonly IList< IQuestion > _questions;
    }

    public class PredicateDelegateFactory {
        public static Predicate< IQuestion > EnglishFilter =
            delegate( IQuestion question ) { return question.Category.Equals( Category.English ); };

        public static Predicate< IQuestion > MathFilter =
            delegate( IQuestion question ) { return question.Category.Equals( Category.Math ); };
    }

    public class Bootstrap {
        public static void Main( ) {
            IQuestionBank questionBank = new QuestionBank( );

            Console.Out.WriteLine( "Searching for all English questions..." );
            foreach ( IQuestion question in questionBank.FindBy( PredicateDelegateFactory.EnglishFilter ) ) {
                Console.Out.WriteLine( question );
            }

            Console.Out.WriteLine( );
            Console.Out.WriteLine( "Searching for all Math questions..." );
            foreach ( IQuestion question in
                questionBank.FindBy( delegate( IQuestion item ) { return item.Category.Equals( Category.Math ); } ) ) {
                Console.Out.WriteLine( question );
            }

            Console.In.ReadLine( );
        }
    }
PlayingWithPredicates.txt (3.2 KB)

#

Keeping It Real With Delegates

Tuesday, September 11, 2007 11:46:21 AM (Mountain Standard Time, UTC-07:00)

If you take a look at the following line, you will probably recognize it as the signature for an event handler.

public void Handler( object sender, EventArgs e ) {

The reason why event handlers are defined with this signature is because it matches the signature of the EventHandler delegate which looks like this:

public delegate void EventHandler(object sender, EventArgs e);

So when you're registering an event handler to an event. You're adding a delegate to the internal list of delegates. (Think of a type safe array of function pointers.) So when the event is raised, each method in the list of delegates is raised, in the same order as they were registered in.

The following line:

container.MyEvent += new PlayingWithEventHandlers( Console.Out.WriteLine ).Handler;

Expands out to something like this...

            PlayingWithEventHandlers handlers = new PlayingWithEventHandlers( Console.Out.WriteLine );
            MulticastDelegate multicastDelegate = new MulticastDelegate( handlers, "Handler" );

You'll find that the MulticastDelegate constructor is protected so this code wont actually compile. Also, the event delegate is combining the newly added delegate that is registering for the event.

The following example uses 3 different delegates defined in the .NET Framework.

    //public delegate void EventHandler(object sender, EventArgs e);
    //public delegate void TimerCallback(object state);
    //public delegate void Action<T>(T obj);

    public class PlayingWithEventHandlers {
        private readonly Action< string > _action;

        public PlayingWithEventHandlers( Action< string > action ) {
            _action = action;
        }

        public void Handler( object sender, EventArgs e ) {
            _action( ( string )sender );
        }
    }

    public class MyEventContainer {
        private Timer _timer;

        public MyEventContainer( ) {
            _timer = new Timer( delegate( object state ) { MyEvent.Invoke( state, EventArgs.Empty ); }, "Tick", 0, 5000 );
        }

        public event EventHandler MyEvent;
    }

    public class Bootstrap {
        public static void Main( ) {
            MyEventContainer container = new MyEventContainer( );
            container.MyEvent += new PlayingWithEventHandlers( Console.Out.WriteLine ).Handler;
            Console.In.ReadLine( );
        }
    }

One of the benefits of using delegates that you can inline an anonymous delegate. The above line where the an instance of the Timer class is constructed could be re-written like...

_timer = new Timer( delegate { MyEvent.Invoke( "Tick", EventArgs.Empty ); }, null, 0, 5000 );

The TimerCallBack's input parameter "state" is still passed to the delegate but the C# compiler allows for this shorthand which ignores the input parameter. The same code could also be re-written as...

        public MyEventContainer( ) {
            _timer = new Timer( TimerClickHandler, "Tick", 0, 5000 );
        }

        public void TimerClickHandler( object state ) {
            MyEvent.Invoke( state, EventArgs.Empty );
        }

This version creates a new method called "TimerClickHandler" that matches the "TimerCallback" delegate signature. Delegates can be quite fun... almost as fun as tables of function pointers in C.

For more information check out...

CLR via C#, Second Edition (Pro Developer)
by Jeffrey Richter

Read more about this title...

EventHandler.txt (1.22 KB)

#

TOutput Converter<TInput, TOutput>(TInput input)

Monday, September 10, 2007 11:49:33 AM (Mountain Standard Time, UTC-07:00)

Yesterday I spent some time poking around the .NET Framework libraries using Reflector and I came across the Converter delegate. It's signature looks like this...

public delegate TOutput Converter<TInput, TOutput>( TInput input );
 

I thought I might put together a contrived example on using this delegate. So here goes...

Let's pretend that I have an Employee Class that looks like this:

    public class Employee {
        public Employee( string firstName, string lastName, ILocation location ) {
            _firstName = firstName;
            _lastName = lastName;
            _location = location;
        }

        public string FirstName {
            get { return _firstName; }
        }

        public string LastName {
            get { return _lastName; }
        }

        public ILocation Location {
            get { return _location; }
        }

        private readonly string _firstName;
        private readonly string _lastName;
        private readonly ILocation _location;
    }

The ILocation interface looks like this.

    public interface ILocation
    {
        string Address { get; }
        string City { get; }
        string Province { get; }
    }

Now let's say i want to be able to convert my Employee object to an Employee data transfer object that looks like this...

    public class EmployeeDto {
        public EmployeeDto( string firstName, string lastName, string address, string city, string province ) {
            _firstName = firstName;
            _lastName = lastName;
            _address = address;
            _city = city;
            _province = province;
        }

        public string FirstName {
            get { return _firstName; }
        }

        public string LastName {
            get { return _lastName; }
        }

        public string Address {
            get { return _address; }
        }

        public string City {
            get { return _city; }
        }

        public string Province {
            get { return _province; }
        }

        private readonly string _firstName;
        private readonly string _lastName;
        private readonly string _address;
        private readonly string _city;
        private readonly string _province;
    }

I could create a full blown EmployeeConverter type to do the conversion or I could leverage the Converter delegate. To do this I could create a DomainToDtoConverter type which can be re-used for other domain to dto type conversions.

    public class DomainToDtoConverter< TIn, TOut > {
        public DomainToDtoConverter( TIn toConvert ) {
            _toConvert = toConvert;
        }

        public TOut Convert( Converter< TIn, TOut > method ) {
            return method( _toConvert );
        }

        private readonly TIn _toConvert;
    }

Notice that the Convert method takes in a Converter delegate? Using this type alone the client of this type would have to define a method that matches the converter delegate signature to do the conversion. This also means that you could use pass in an anonymous delegate, but that may not be the wisest choice because it's possible that this conversion may need to occur in multiple places in our application. So let's encapsulate that in a factory.

    public class ConverterDelegateFactory
    {
        public static Converter< Employee, EmployeeDto > EmployeeConverterMethod =
            delegate( Employee employee ) {
                return
                    new EmployeeDto( employee.FirstName, employee.LastName, employee.Location.Address, employee.Location.City,
                                     employee.Location.Province );
            };
    }

Clients of the DomainToDtoConverter can now pass in the factory delegate method like so...

            Employee employee = new Employee( "mo", "khan", new Location( "620 8th ave sw", "Calgary", "Alberta" ) );
            EmployeeDto dto =
                new DomainToDtoConverter< Employee, EmployeeDto >( employee ).Convert(
                    ConverterDelegateFactory.EmployeeConverterMethod );

The DomainToDtoConverter type can now be re-used for converting different types. Yes I know this is probably not the greatest example but hopefully it helps.

Converter.zip (11.65 KB)

#

Converting From MSN Live Spaces to DasBlog

Sunday, August 26, 2007 3:48:11 PM (Mountain Standard Time, UTC-07:00)

So recently I managed to pull my posts from an old Live spaces account to merge them into my current DasBlog. It wasn't an easy process and I lost things like comments from my posts. MSN Live Spaces exposes an MetaWeblogAPI to pull down your posts. There are limitations though... like you can only pull that last 20 posts using the "getRecentPosts()" method. All calls are carried over Xml Rpc.

MSDN documentation can be found here...

In order to pull data from your account you have to enable email publishing and specify a email publishing password this will be used for the RPC calls. I had a lot of problems pulling the correct data from the API. I wanted to get all of my entries, but I couldn't use the "getRecentPosts()" method because it only returned the last 20 posts. So I had to use the "getPost()" method in a loop and try to get each individual post one at a time.

However, to get the post you have to use the post Id, so i started a loop from 0 to 300 to start grabbing Id's. I found that each one of my posts had a similar prefix to the ID. They all started with "E2CAA5FD0245D158!" then had a number appended to it. Except the number didn't increment by one, and I couldn't find that pattern. So I started a loop from 0 to 2000 and appended the current counter index to the unique id.

Another issue I had was that the post date was not correct, every single post returned some strange date time that did not match the post data at all. To get around this I sent a web request for the actual html page and parsed out the date. This definitely was a hack for a solution...

The guts of the console app looks like this:

            MsnSpacesMetaWeblog mw = new MsnSpacesMetaWeblog( );
            SpaceSettings settings = new SpaceSettings( );

            mw.Credentials = new NetworkCredential( settings.Username, settings.Password );

            DasBlogWriter dasBlogWriter = new DasBlogWriter( settings.DefaultCategory );
            SpaceHtmlParser parser = new SpaceHtmlParser( settings.BlogUrl );
            for ( int i = 0; i < settings.UpperLimit; i++ ) {
                string entryId = settings.EntryIdPrefix + i;
                try {
                    Post post = mw.getPost( entryId, settings.Username, settings.Password );
                    post.dateCreated = parser.GetEntryDate( entryId );
                    
                    dasBlogWriter.Write( new SpacesEntry( post ) );
                    Console.WriteLine( "Success: Entry Id " + entryId );
                }
                catch {
                    Console.WriteLine( "Failed to retrieve post with ID: " + entryId );
                }
            }
            Console.ReadLine( );

I told you it wasn't pretty... Please feel free to the source and modify it as you need too... You will have to change the settings in the app.config file to match your settings.

Good Luck!

SpacesToDasBlog.zip (700.77 KB)

#

The State Pattern

Sunday, August 26, 2007 2:35:59 PM (Mountain Standard Time, UTC-07:00)

"The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

 

Let's say I've got a point of sale terminal used for processing financial transactions. Let's say that at any given time the terminal can be in 1 of 6 states. Those states are:

  • Idle State: During this state an idle message is displayed on the screen of the POS terminal.
  • Card Swiped State: The terminal enters this state when a card is swiped.
  • Amount Entered State: The terminal enters this state when the transaction amount is entered.
  • PIN Entered State: The terminal enters this state when the customer enters their PIN.
  • Processing Transaction State: The terminal enters this state when it connects to a financial processor to process the transaction.
  • Transaction Approved State: The terminal enters this state when the transaction has been process and has been approved.
  • Transaction Rejected State: The terminal enters this state when the transaction was processed but was rejected.

Let's pretend the following is the client code that will use the point of sale terminal to process transactions.

            IPosTerminal terminal = new PosTerminal( );
            terminal.SwipeCard( "6278080000008205" );
            terminal.EnterAmount( 99.99 );
            terminal.EnterPin( "8012" );
            terminal.ProcessTransaction( );
            terminal.PrintReceipt( );

When the PosTerminal is first constructed it is immediate put into an Idle State which displays an idle message to screen. The PosTerminal has a property of type IState that all the concrete state types implement.

As actions are performed against the PosTerminal, they are delegated to the current state.

        public void SwipeCard( string cardNumber ) {
            _currentState.SwipeCard( cardNumber );
        }

        public void EnterAmount( double amount ) {
            _currentState.EnterAmount( amount );
        }

        public void EnterPin( string pin ) {
            _currentState.EnterPin( pin );
        }

        public void AuthorizeTransaction( ) {
            _currentState.ProcessTransaction( );
        }

        public void PrintReceipt( ) {
            _currentState.PrintReceipt( );
        }

        public void ProcessTransaction( ) {
            _currentState.ProcessTransaction( );
        }
In this implementation I've made it the concrete state types responsibility to transition to the next state. For example the IdleState might look like:
        public void SwipeCard( string cardNumber ) {
            _terminal.Transaction = new PosTransaction( );
            _terminal.Transaction.Date = DateTime.Now;
            _terminal.Transaction.CardNumber = cardNumber;
            _terminal.CurrentState = new CardSwipedState( _terminal );
        }

        public void EnterAmount( double amount ) {
            Console.Out.WriteLine( "Please swipe a card first." );
        }

...

With the state pattern you can re-order states and alter the implementation of a state with out having to change the subject of the state.

DesignPatterns.State.zip (7.13 KB)

#

The Adapter Pattern

Sunday, August 26, 2007 1:39:14 PM (Mountain Standard Time, UTC-07:00)

"The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." - Head First Design Patterns

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

If you're trying to build a presentation layer that is platform agnostic, you might turn to adapters for simple UI controls. For example in ASP.NET there is a drop down list control, and in Win Forms there is the Combo Box control.

A quick an easy adapter to the two controls might look like:

    public interface IDropDownListAdapter {
        void BindTo( IEnumerable< IDropDownListItem > pairs );
        IDropDownListItem SelectedItem { get; }
    }

Each drop down list item might look like:

    public interface IDropDownListItem {
        string Text { get; }
        string Value { get; }
    }

A concrete implementation for a Win Forms application might look like:

    public class DesktopDropDownList : IDropDownListAdapter {
        public DesktopDropDownList( ComboBox dropDown ) {
            _dropDown = dropDown;
            _pairs = new Dictionary< string, IDropDownListItem >( );
        }

        public void BindTo( IEnumerable< IDropDownListItem > pairs ) {
            if ( pairs != null ) {
                _pairs = new Dictionary< string, IDropDownListItem >( );

                foreach ( IDropDownListItem pair in pairs ) {
                    _dropDown.Items.Add( pair.Text );
                    _pairs.Add( pair.Text, pair );
                }
                _dropDown.SelectedIndex = 0;
            }
        }

        public IDropDownListItem SelectedItem {
            get { return !string.IsNullOrEmpty( _dropDown.Text ) ? _pairs[ _dropDown.Text ] : null; }
        }

        private ComboBox _dropDown;
        private IDictionary< string, IDropDownListItem > _pairs;
    }

A concrete implementation for a ASP.NET application might look like:

    public class WebDropDownList : IDropDownListAdapter {
        public WebDropDownList( DropDownList dropDown ) {
            _dropDown = dropDown;
        }

        public void BindTo( IEnumerable< IDropDownListItem > pairs ) {
            if ( pairs != null ) {
                foreach ( IDropDownListItem pair in pairs ) {
                    _dropDown.Items.Add( new ListItem( pair.Text, pair.Value ) );
                }
            }
        }

        public IDropDownListItem SelectedItem {
            get { return new DropDownListItem( _dropDown.SelectedItem.Text, _dropDown.SelectedItem.Value ); }
        }

        private DropDownList _dropDown;
    }

And voila... we can write a presentation layer that binds data to an IDropDownListAdapter, without having to be specific to WinForms, ASP.NET, WPF, Silverlight etc.

        public Presenter( IView view ) {
            _view = view;
        }

        public void Initialize( ) {
            IList< IDropDownListItem > items = new List< IDropDownListItem >( );
            items.Add( new DropDownListItem( "Yes", "1" ) );
            items.Add( new DropDownListItem( "No", "2" ) );
            _view.AreYouHappy.BindTo( items );
        }
DesignPatterns.Adapter.zip (4.56 KB)

#

ADO.NET 2.0

Sunday, August 26, 2007 1:10:12 PM (Mountain Standard Time, UTC-07:00)

Here it is my final assignment for CMPP298 - Database Programming ADO.NET. Assignment is as follows:

"Create a Windows Forms application to support data maintenance (CRUD functionality) of Invoices per Vendor in the Payables database.
Make use of the Connection, Transaction, Command, and DataReader objects of the ADO.NET SQLClient Provider,
not DataSets, DataTables, DataAdapters or the Configuration Wizard.

The user has to select a Vendor and then view, add, edit or delete Invoice records for the selected vendor.
Changes have to be saved before the user can select another vendor.

Feel free to make use of a combination of UI controls such as Grids, TextBoxes, ComboBoxes, etc. "

The focus of the assignment was on ADO.NET 2.0. So my implementation of validation, UI, and domain is rather weak. I wanted to focus my attention on learning the core of ADO.NET 2.0 by learning more about...

  • IDbConnection: The interface the the abstract DbConnection type implements that all connection sub classes inherit from for each ado.net provider. (OleDb, Odbc, Oracle, SQL Server, MySQL)
  • IDbCommand: The interface that the abstract DbCommand type implements that all command objects inherit from.
  • DataTable: An in memory type used to store data in a tabular format.
  • IDataReader: A forward only, read-only type that allows you to iterate through  a result set.
  • IDataParameter: This type represents a parameter for a IDbCommand object.
  • DbProviderFactories:  Provides a factory method to return a DbProviderFactory abstract factory with methods such as CreateConnection.

IDbConnectionIDbConnection

The IDbConnection interface demands a set of very simple methods and properties. I found "CreateCommand()" and "Open()" to be the most useful. Working against the interface as opposed to the concrete implementation simplified learning for myself. I was able to focus on the most important traits and behaviors that all Connection types share.

The "CreateCommand()" method returns a "IDbCommand" type that has it's connection property set to the the IDbConnection type that created it. Further reducing the amount of code needed to be written.

In my assignment I created and ConnectionFactory that has a single factory method that returns IDbConnection types. This separates where the connection string settings are retrieved from, from where the connection object is actually used.

            using ( IDbConnection connection = _connectionFactory.Create( ) ) {
                IDbCommand command = connection.CreateCommand( );
                command.CommandText = sqlQuery;
                connection.Open( );
                IDataReader reader = command.ExecuteReader( );
                DataTable table = new DataTable( );
                table.Load( reader );
                return table;
            }

You might have also noticed that IDbConnection also implements the IDisposable interface which allows me to use the type in a "using" block, which implicitly calls the Dispose method on the type. The Dispose method will then close the connection and clean up any other unmanaged resources.

 IDbCommandIDbCommand

Types that implement the IDbCommand interface are used to execute "commands" against a database. This uses the Command pattern with 3 types of execute methods.

  • ExecuteReader: will execute a SQL command against the data source and return and IDataReader type that allows you to read through a result set.
  • ExecuteNonQuery: will execute a SQL command against the data source and returns the number of rows affected by the command.
  • ExecuteScalar: will execute a SQL command against the data source and returns the value in the first column of the first row.

The CommandText property is either the name of the stored procedure or the raw SQL to execute against the data source.

                IDbCommand command = connection.CreateCommand( );
                connection.Open( );
                command.CommandText = query;
                command.ExecuteNonQuery( );

DataTable

A DataTable is an in memory container for tabular data. It has a method named "Load()" that takes in an IDataReader type and will load the data table with the entire result set from the IDataReader. The overloaded Load method looks like this in Lutz Reflector:

 DataTableLoad

A client usage of the Load method looks like this:

                IDataReader reader = command.ExecuteReader( );
                DataTable table = new DataTable( );
                table.Load( reader );

 IDataReader

Types that implement the IDataReader interface allow for forward-only reading through 1 or more result sets.

IDataReader

The IDataReader type also inherits from IDataRecord which exposes a set of get methods like "GetDecimal()", "GetBoolean()", "GetOrdinal()", "GetString()" to read out the value from each column as you iterate through the result set. This can definitely lead to some sloppy code such as...

        private void SloppyReader( IDataReader reader ) {
            string customerFirstName = !reader.IsDBNull( 1 ) ? reader.GetString( 1 ) : "Unknown";
            string customerLastName = !reader.IsDBNull( 2 ) ? reader.GetString( 2 ) : "Unknown";            
        }

IDataParameter

The IDataParameter is a parameter that is used by command objects. For example in the following SQL syntax @FirstName and @LastName are parameters.

INSERT INTO Customer (FirstName, LastName) VALUES (@FirstName, @LastName);

The following C# will insert the values "Mo" and "Khan" as the @FirstName, and @LastName parameters.

            IDbCommand command = connection.CreateCommand( );
            command.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES (@FirstName, @LastName);";

            IDataParameter commandParameter = command.CreateParameter( );
            commandParameter.ParameterName = "@FirstName";
            commandParameter.Value = "Mo";
            command.Parameters.Add( commandParameter );

            commandParameter = command.CreateParameter( );
            commandParameter.ParameterName = "@LastName";
            commandParameter.Value = "Khan";
            command.Parameters.Add( commandParameter );

DbProviderFactoriesDbProviderFactories

This type has a factory method called "GetFactory()" which returns an abstract factory for creating connections, commands, adapters and parameters.

To construct a DbProviderFactory you need to specify the ADO.NET provider to use. For example for the SQL Server Provider, you would use the invariant provider name of "System.Data.SqlClient".

This works great with the ConnectionStringSettings section of the *.config file. Using the ConnectionStringSettings type you can extract the connection string as well as the provider name and construct a DbProviderFactory without a re-compile.

With a quick change to the *.config I can switch from a SQL Server provider to an Oracle provider or MySQL provider, or an OleDb provider or and Odbc provider.

    <connectionStrings>
        <add name="PayablesConnection" 
             connectionString="data source=(local);Integrated Security=SSPI;Initial Catalog=Payables;" 
             providerName="System.Data.SqlClient" />
   </connectionStrings>
DbProviderFactory

 The DbProviderFactory allows you to create database agnostic ADO.NET types through factory methods. 

        public DatabaseConnectionFactory( ConnectionStringSettings connectionStringSettings ) {
            _settings = connectionStringSettings;
        }

        public IDbConnection Create( ) {
            IDbConnection connection = DbProviderFactories.GetFactory( _settings.ProviderName ).CreateConnection( );
            connection.ConnectionString = _settings.ConnectionString;
            return connection;
        }

ADO.NET seems intimidating at first, but when you break it down piece by piece it's not such a scary beast. Now none of the examples provided use stored procedures, but using similar techniques discussed you could transition to stored procedures with ease and confidence.

Now as for DataSets, DataAdapters, CodeGen and Wizards... that's a whole other story!

Sait.Cmpp298.Assignment3.zip (2.35 MB)

#

System.Windows.Forms.Control.CompanyName?

Tuesday, August 21, 2007 8:47:29 PM (Mountain Standard Time, UTC-07:00)

This messed me up a bit... I have a view that has a property called "CompanyName"

    public interface ICaptureCompanyDetailsView {
        string CompanyName { get; }

...

When my presenter was actually getting the company it was not getting stored as what I intended, because I had not implemented the "CompanyName" property on my actual view.

How did this compile?... It turns out that System.Windows.Forms.Control has a property called "CompanyName". Hmm...

companyName

 

The temporary solution... C# Shadow Field! (Notice the 'new' keyword)

        public new string CompanyName {
            get { return uxCompanyNameTextBox.Text; }
        }

#

ADO.NET On the Brain

Tuesday, August 21, 2007 11:33:39 AM (Mountain Standard Time, UTC-07:00)

Good Morning! Well I'm feeling a little sluggish this morning. It's always tough going straight to sleep on school nights. You just feel a little cheated when you get home, because I want to squeeze a little bit of time out of the evening for myself. Not to mention my brain was just buzzing in bed, and it took a little longer to wind down then usual.

In the last couple of days I have been reading through Jeremy Miller's articles on how to build your own CAB. It's definitely worth a read, I've learned a lot so far.

On Sunday, I just about wrapped up an assignment for class. It's focus is on ADO.NET and data access... I'm hoping I'll be able to publish my work after the due date but in the mean time here's a sample...

To select data I build a SelectQueryBuilder object that can be used like this...

        public IEnumerable< IDropDownListItem > GetAllVendorNames( ) {
            SelectQueryBuilder builder = new SelectQueryBuilder( Tables.Vendors.TableName );
            builder.AddColumn( Tables.Vendors.VendorID );
            builder.AddColumn( Tables.Vendors.Name );
            return CreateItemsFrom( _gateway.GetTableFrom( builder ) );
        }

To update a row in the database you would use my home brewed UpdateQueryBuilder.

        public void UpdateInvoice( UpdateInvoiceDto dto ) {
            UpdateQueryBuilder builder = new UpdateQueryBuilder( Tables.Invoices.InvoiceID, dto.InvoiceId );
            builder.Add( Tables.Invoices.CreditTotal, dto.CreditTotal );
            builder.Add( Tables.Invoices.DueDate, dto.DueDate );
            builder.Add( Tables.Invoices.InvoiceDate, dto.InvoiceDate );
            builder.Add( Tables.Invoices.InvoiceNumber, dto.InvoiceNumber );
            builder.Add( Tables.Invoices.InvoiceTotal, dto.InvoiceTotal );
            builder.Add( Tables.Invoices.PaymentDate, dto.PaymentDate );
            builder.Add( Tables.Invoices.PaymentTotal, dto.PaymentTotal );
            builder.Add( Tables.Invoices.TermsID, dto.TermsId );

            _gateway.UpdateRowUsing( builder );
        }

One of the coolest things I Found in ADO.NET 2.0 was DbProviderFactories. There's so much good stuff that was introduced in 2.0 that I know I wasn't taking advantage of.

#

Do You Have Style?

Sunday, July 08, 2007 7:28:20 PM (Mountain Standard Time, UTC-07:00)

For anyone who currently writes C#, or is looking to start I highly recommend you pick up a copy of... 

The Elements of C# Style
by Kenneth Baldwin, Andrew Gray, Trevor Misfeldt

Read more about this title...

This book offers great suggestions for programming style in the C# language. It covers things like:

  • Formatting
  • Naming Conventions
  • Documentation
  • General Principles

The book contains a series of rules to abide by, most of the rules are quite flexible. The main premise of the book is to maintain consistency but offers variations that a C# developer can follow.

Here are a few example's taken from the book:

43. Use Came Case for Variable and Method Parameter Names

Use lowercase for the first word and capitalize each subsequent word that appears in a variable name to provide a visual cue for separating the individual words within each name.

public class Customer {
 	public string firstName_;
	public string lastName_;
	public string ToString(){
		return lastName_ + ", " + firstName_;
	}
} 

49. Use an Organization Name for the Root Namespace, and Narrow by Project, Product or Group

namespace Company.Group.Project{
	// ...
}

This book is an extremely quick read, but well worth the price. It comes in handy as an excellent reference manual!

#

The Observer Pattern

Friday, July 06, 2007 8:14:45 AM (Mountain Standard Time, UTC-07:00)

"The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically." - Head First Design Patterns

What this means is that if you have objects that are interested in changes in another object, you allow the "observers" to register or subscribe to the subject. In the example provided, my wife and mother in law want to be notified whenever i look at cute girls. Each time i look at a cute girl they should be notified and then they can take whatever action they want.

Typically, you would push or pull the data from the subject (that's me), to the observers (that's my wife and her mom). Mo (that's me) contains an internal list of relatives that want to know what he's up to. Anytime one of his relatives wants to check in on him, the add themselves to Mo's interal list. If they're no longer interested, they can remove themselves for the internal list.

        public Mo( IList< IObserver > concernedRelatives ) {
            _concernedRelatives = concernedRelatives;
            LookAtCuteGirl += delegate { OnLookedAtCuteGirl( ); };
        }

        public event EventHandler LookAtCuteGirl;

        public void Add( IObserver observer ) {
            _concernedRelatives.Add( observer );
        }

        public void Remove( IObserver observer ) {
            _concernedRelatives.Remove( observer );
        }

        private IList< IObserver > _concernedRelatives;

        private void OnLookedAtCuteGirl( ) {
            foreach ( IObserver relative in _concernedRelatives ) {
                relative.Update( );
            }
        }

Let's say my wife is concerned and wants to check up on me, here's how she would do it.

        public MosWife( ISubject husband ) {
            _husband = husband;
            _husband.Add( this );
        }

        public void Update( ) {
            Console.Out.WriteLine( "Why is my husband looking at cute girls?" );
        }

        private ISubject _husband;

She's decided to always add her self to my internal list to see what I'm doing. If I should happen to check out a cute girl, she will be immediately notified. Lucky for me, my wife is pretty laid back, and asks herself "Why is my husband looking at cute girls?"...

Hopefully, this helps to demonstrate the observer pattern. I realize that it is rather contrived example, and the source could could be refactored. But hopefully it's clear.

For a better explanation, you should read...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

P.S. My wife does not check up on me, she's awesome!

DesignPatterns.Observer.zip (4.01 KB)

#

The Strategy Pattern

Monday, July 02, 2007 3:32:53 PM (Mountain Standard Time, UTC-07:00)

"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it." - Head First Design Patterns

This means that at runtime you can switch the algorithm being used by a particular object. In the example attached, there are a set of characters. Each characters has a weapon that they yield! At runtime, you can switch the type of weapon that a particular character is using.

For instance if the character king was constructed to use a default weapon, at runtime you could switch out the weapon that the king uses when he is fighting. This adheres to the open/closed principle, where the king object is open for extension but closed for modification.

In the future if we wanted to add new weapons, we can add them without having to change the implementation of the king object. This allows us to switch the type of weapon the king object is using at runtime!

            King king = new King( );
            king.Fight( );

            king.Weapon = new Axe( );
            king.Fight( );

            king.Weapon = new BowAndArrow( );
            king.Fight( );

 For more information check out...

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title...

DesignPatterns.Strategy.zip (5.29 KB)

#

Moneris API

Thursday, June 21, 2007 8:38:05 AM (Mountain Standard Time, UTC-07:00)

Overview


The purpose of this document is to describe how to use the Moneris API in a .NET application written in C# to process credit card transactions. Further information on the Moneris API can be found at:

The Moneris .NET API is a wrapper to the HTTPS post to their site. Instead of having to embed hidden input fields on and HTML page, the API allows users to post directly to the page via C#. The way the data is transported to Moneris is the same as a direct post from the client using hidden input fields.

E.g. Direct Post

With a direct post the data is transmitted directly from the client browser to Moneris.

<input id="storeID" type="hidden" name="ps_store_id" value=""/>
<input id="hppKey" type="hidden" name="hpp_key" value=""/>
<input id="chargeTotal" type="hidden" name="charge_total" />

E.g. .NET API

With the .NET API the client data is transmitted to our application, then we send the data to Moneris and a response back to the client. The client has no knowledge the payment was processed through Moneris.

    HttpsPostRequest request =
        new HttpsPostRequest(
            host,
            storeId,
            apiToken,
            new Purchase(
                orderId,
                customerId,
                amount,
                pan,
                expiryDate,
                crypt)
        );
    Receipt receipt = request.GetReceipt();

Requirements


Because the data is transmitted to us before being processed by Moneris we need an SSL certificate. When a customer is processing a payment, the data is sent to us through an encrypted channel which is then transported to Moneris for authorization through another encrypted channel.

Transaction Types


There are several different types of credit card transactions that we can process using the Moneris API. This document will focus on the Purchase transaction.

  • Purchase: Verifies funds are available on customers card and removes them.
  • Pre Authorization: Verifies that funds are available on the customer card then locks those funds.
  • Capture: Retrieves the captured funds that are locked on a customers card. (This implies that a Pre Auth for the capture amount has already been committed.)
  • Void: Will void a purchase or capture transaction on the day of the transaction.
  • Refund: Will return funds from a Purchase or Capture transaction. ( Can be any amount of the transaction.)
  • Batch Close: Closes all transactions so that all Purchase, Capture and Refund transactions will be credited or debited on the following business day.

API Types


To process a purchase transaction, I will focus on 3 key types from the API.

  • HttpsPostRequest: Used to send a request to Moneris and retrieve a response
  • Purchase: Type of transaction to process
  • Receipt: The response from Moneris.

HttpsPostRequest:

This type is used to transport transaction information to Moneris through an SSL connection. Once the response stream is returned it is sent to the Receipt constructor where a reference to that stream is contained as a private data member. (This seems inefficient to store the stream rather than to immediately parse out the data from the stream then close it.)

The following call will connect to Moneris, process the transaction, and retrieve a receipt object which contains the details of the response from Moneris.

new HttpsPostRequest( order.Host, order.StoreId, order.Token, transaction ).GetReceipt( );

Purchase:

The purchase type is specialization of the base type Transaction. It contains the information necessary for Moneris to process the transaction.

It can be constructed like this:

new Purchase( order.OrderId, order.Amount.ToString( "F" ), order.CardNumber, order.ExpirationDate, Indicator.SslEnabledMerchant );

Receipt:

This type contains the response from Moneris after a transaction has been processed. It can be retrieved by calling the “GetReceipt()” method on the HttpsPostRequest object.

new HttpsPostRequest( order.Host, order.StoreId, order.Token, transaction ).GetReceipt( );

These 3 objects allow a user to process a transaction through the Moneris store. It is up to the user of the API to enforce validation, and transparency between the client and Moneris.

I was able to quickly process sample transactions through the Moneris test store.

The .NET API wrapper is very easy to use but there is some behavior that isn’t intuitive. For example, when you construct an instance of the HttpsPostRequest object, this immediately fires of a request to Moneris in the constructor. This is shown from a capture of the code viewed through Reflector.

    public HttpsPostRequest(string host, string store, string apiTok, Transaction t)
    {
        this.receiptObj = new Receipt();
        this.retry = false;
        this.storeId = store;
        this.apiToken = apiTok;
        this.transaction = t;
        this.url = "https://" + host + ":443/gateway2/servlet/MpgRequest";
        this.SendRequest();
    }

Also, the type named “IDebitPurchase” suggests that it is an interface, however it is declared as a class.

Conclusion


Overall, the Moneris API is easy to use and allows the user to quickly process transactions, and seems to be a good solution for connecting to the Moneris store and processing transactions. The documentation provided with the API offers lots and lots of code samples, which is extremely helpful in learning and quickly understanding the API. There is also lots of other useful information such as the types of things that need to show up on a receipt.

Additional Notes/Observations


- The API is very easy to use and it abstracts a lot of the tedious work for us.

The document attached with the API describes the response fields and tells the length of them but does not offer the actual values to be returned.

For example the card type is not specified. Through testing I found that the following return values are sent back for each card type, based on the card numbers supplied in the document.          

            Test Card Numbers:
            Visa:                         4242424242424242
            MasterCard:                5454545454545454
            American Express:        373599005095005
            Diners Club:                36462462742008          

            Visa "V"
            Master Card "M"
            American Express "AX"
            Diners "M"          

I don't know why the same value is getting returned for MasterCard and Diners, but the difference between the 2 transactions is that master cards have a 16 digit card number and Diners have a 14 digit card number.

#

Regular Expressions

Monday, June 11, 2007 7:07:08 PM (Mountain Standard Time, UTC-07:00)

Regular expressions can be used to find patterns in Strings, useful for validation to ensure that data is in a particular format. Compilers use regular expressions to validate the syntax of programs.

Character Class'

  • \d: Matches any digit
  • \D: Matches any non-digit
  • \w: Matches any word
  • \W: Matches any non-word
  • \s: Matches any whitespace
  • \S: Matches any non-whitespace

Quantifiers

  • * Matches zero or more occurrences of the preceding pattern.
  • + Matches one or more occurrences of the preceding pattern.
  • ? Matches zero or one occurrences of the preceding pattern.
  • {n} Matches exactly n occurrences of the preceding pattern.
  • {n,} Matches at least n occurrences of the preceding pattern.
  • {n,m} Matches between n and m (inclusive) occurrences of the preceding pattern.

Examples:

  • . Matches any single character except a newline character
  • .* Matches any number of unspecified characters except newlines.
  • * When the applied this will match zero or more occurrences.
  • + causes the pattern to match one or more occurrences.
    • E.g. "A*" and "A+" will match "A", but "A*" will match an empty string as well.
  • \d matches any numeric digit
  • [] to specify sets of characters other than those that belong to a predefined character class.
    • E.g. "[aeiou]" matches any vowel.
  • - can be used to specify ranges of characters
    • E.g. "[0-35-9]" -> 0 to 3, or 5 to 9. Not 4!
  • ^ specifies that a pattern should match anything but.
    • E.g. "[^4]" matches any non-digit and digits that is not 4.

 

Visual C# 2005 How to Program (2nd Edition) (How to Program)
by Harvey & Paul) Deitel & Associates

Read more about this title...

#

Converting From Blogger to DasBlog

Sunday, June 10, 2007 11:29:06 AM (Mountain Standard Time, UTC-07:00)

In the last few months I started using DasBlog as my blogging engine, and I've really grown to like it. It's so easy to use and make changes, and the best part is that all of my posts are stored in easy to transfer xml files.

I've been blogging for a few years now and I've used 2 different engines to host my blog. First I started at MSN Spaces, now known as Live Spaces. Then I switched to Blogger. I have over 300 posts on my blogger blog and I wanted to find a way to port those entries into my dasBlog. I did some reading and found a couple of helpful articles that helped me to put together a console application that I used to port 301 blogger entries to my dasBlog.

I started by Googling: "blogger to dasblog" and came across the following articles:

The first thing that I did was create a backup of my Blogger posts by replacing my current template with the following:

<bloggerEntries>
    <Blogger>
        <bi_entry>
            <bi_url><![CDATA[<$BlogItemURL$>]]></bi_url>
            <bi_title><![CDATA[<$BlogItemTitle$>]]></bi_title>
            <bi_body><![CDATA[<$BlogItemBody$>]]></bi_body>
            <bi_author><![CDATA[<$BlogItemAuthor$>]]></bi_author>
            <bi_date><![CDATA[<$BlogItemDateTime$>]]></bi_date>
            <BlogItemCommentsEnabled>
                <BlogItemComments>
                    <bi_comments>
                        <bi_commentauthor><![CDATA[<$BlogCommentAuthor$>]]></bi_commentauthor>
                        <bi_commentdate><![CDATA[<$BlogCommentDateTime$>]]></bi_commentdate>
                        <bi_commentbody><![CDATA[<$BlogCommentBody$>]]></bi_commentbody>
                    </bi_comments>
                </BlogItemComments>
            </BlogItemCommentsEnabled>
        </bi_entry>
    </Blogger>
</bloggerEntries>

Next I changed my blog settings to show 999 posts on the main page.

 

Then I browsed to my blog http://mokhan.blogspot.com and saved the page as an ".xml" file.

The file looked something like this...

<bloggerEntries>
<bi_entry>
    <bi_url><![CDATA[]]></bi_url>
    <bi_title><![CDATA[The Suburban Ghetto Cowboy]]></bi_title>
    <bi_body><![CDATA[Good Morning! Well yesterday was ...]]></bi_body>
    <bi_author><![CDATA[!~Mista mO~!]]></bi_author>
    <bi_date><![CDATA[6/08/2007 08:24:00 AM]]></bi_date>
    <bi_comments>
        <bi_commentAuthor><![CDATA[FallenAngel]]></bi_commentAuthor>
        <bi_commentDate><![CDATA[Saturday, June 09, 2007 8:07:00 PM]]></bi_commentDate>
        <bi_commentBody><![CDATA[I'll tell you where ...]]></bi_commentBody>
    </bi_comments>
</bi_entry>

After I undid the changes I made to my blog, I forgot to mention that I made a backup of my blog template before changing it. So I changed my template back to the way it was then I changed the number of posts to display on the main page.

Then I created a C# console application using the "newtelligence.DasBlog.Runtime.dll" assembly as a reference to my application, and I parsed out the blogger entries and created dasBlog ones. In the end the guts of my console application looks like:

        private static void Main( ) {
            IList< IBloggerEntry > bloggerEntries =
                BloggerReader.Read( new Uri( 
Path.Combine( Environment.CurrentDirectory, "mokhan.blogspot.com.xml" ) ) );

            foreach ( IBloggerEntry bloggerEntry in bloggerEntries ) {
                new DasBlogWriter( ).Write( bloggerEntry );
            }
            System.Console.WriteLine( bloggerEntries );
            System.Console.WriteLine( bloggerEntries.Count + " Entries have been created!" );
            System.Console.ReadLine( );
        }

I could have updated it to take in the file path the xml file as a parameter to the console app, but this was kind of a throw away project for me. Next I'm on to parse out my Live Spaces posts to merge into my dasBlog.

I've attached the source for my C# bloggerToDasBlog app. It's free to use and modify as you wish, feel free to give me credit if ya wish to do so!

BloggerToDasBlog.zip (320.32 KB)

#

Online Payment Insecurities

Friday, June 08, 2007 11:43:06 AM (Mountain Standard Time, UTC-07:00)

So I was doing a little research on integrating the ability to make online payment through a financial processor and came across Moneris. I came across this document. It is the eSelect plus merchant integration guide. It contains information on how to access a test site, with a store id, username and password.

When you log in, you can see a number of different vendors, and you can see information on them. Ok... wtf??? So I can see a list of vendors who use Moneris eSelect. That's kind of weird, it only shows the tests site for them, but it wouldn't take much to figure out how to get to the production site. (Maybe, maybe not!)

The above mentioned PDF, also describes how a vendor's web application is to communicate with Moneris. They require a number of hidden input fields sent in a HTTP post to their secure server.

<form method="POST" action="https://esqa.moneris.com/HPPDP/index.php">
    <input type="HIDDEN" name="ps_store_id" VALUE="AF4Fs1024" />
    <input type="HIDDEN" name="hpp_key" VALUE="Hsjh4GSr4g" />
    <input type="HIDDEN" name="charge_total" VALUE="1.00" />
    <!-- MORE OPTIONAL VARIABLES CAN BE DEFINED HERE -->
    <input type="SUBMIT" name="SUBMIT" value="Click to proceed to Secure Page" /> 
</form>

Moneris will process the information based on your store id, amount, and card information you submit to Moneris. Then Moneris will submit an HTTP post back to your page, with the results of the transaction. These parameters are defined in the document mentioned above.

  1. Amount - (charge_total)
  2. Transaction Type - (trans_name)
  3. Date and Time - (date_stamp & time_stamp)
  4. Authorisation Code - (bank_approval_code)
  5. Response Code - (response_code)
  6. ISO Code - (iso_code)
  7. Response Message - (message)
  8. Reference Number - (bank_transaction_id)

Interesting... this seemed kind of insecure to me. If someone were to find one of these pages on the net that accepts the response from Moneris and parses out these values, they could potentially craft a malicious URL to simulate the data the would be returned to Moneris. What's even scarier, is that since they could log in to the test site, and they could see a list of other vendors that someone could go look for exploits on. It's like a honey pot for exploits??

A malicious URL might look like...

"http://domain.com/page.php?charge_total=100,000.00

&trans_name=N/A

&date_stamp=6/8/2007

&time_stamp=12:32:38.6726165

&message=fakepurchase!

&bank_approval_code=N/A

&response_code=N/A

&iso_code=N/A

&bank_transaction_id=N/A"

Also, if someone were to write a page that posted directly to Moneris that buried the hidden input fields within the scope of a form element, a user could view the source and pull out all the hidden input arguments and try to add to the hand crafted URL...

Now say someone were to write an app...

public static void Main( ) {
    WebRequest request = WebRequest.Create( ConstructUrl( http://domain.com/page.php ) );
    WebResponse response = request.GetResponse( );
    Console.WriteLine( ( ( HttpWebResponse )response ).StatusDescription );
    Stream dataStream = response.GetResponseStream( );
    StreamReader reader = new StreamReader( dataStream );
    string responseFromServer = reader.ReadToEnd( );
    Console.WriteLine( responseFromServer );
    reader.Close( );
    response.Close( );

    using( StreamWriter writer = File.CreateText( Path.Combine( 
Environment.CurrentDirectory, "MyFakeReceipt.html" ) ) ) {
        writer.Write( responseFromServer );
    }
}

private static String ConstructUrl( String pagePath ) {
    StringBuilder builder = new StringBuilder( );
    builder.Append( pagePath );
    builder.Append( "?" + MonerisParameters.Amount + "=100,000.00" );
    builder.Append( "&" + MonerisParameters.TransactionType + "=N/A" );
    builder.Append( "&" + MonerisParameters.Date + "=" + DateTime.Now.Date.ToShortDateString( ) );
    builder.Append( "&" + MonerisParameters.Time + "=" + DateTime.Now.TimeOfDay );
    builder.Append( "&" + MonerisParameters.ResponseMessage + "=Congratulations on your fake purchase!" );
    builder.Append( "&" + MonerisParameters.AuthorizationCode + "=N/A" );
    builder.Append( "&" + MonerisParameters.ResponseCode + "=N/A" );
    builder.Append( "&" + MonerisParameters.IsoCode + "=N/A" );
    builder.Append( "&" + MonerisParameters.ReferenceNumber + "=N/A" );

    return builder.ToString( );
}

public class MonerisParameters {
    public const String Amount = "charge_total";
    public const String TransactionType = "trans_name";
    public const String Date = "date_stamp";
    public const String Time = "time_stamp";
    public const String AuthorizationCode = "bank_approval_code";
    public const String ResponseCode = "response_code";
    public const String IsoCode = "iso_code";
    public const String ResponseMessage = "message";
    public const String ReferenceNumber = "bank_transaction_id";
}
It's a scary world... and this is why I trust debit cards, credit cards and most especially gift cards less and less. Don't even get me started with Gift Cards!

#

Prioritizing Your Threads

Monday, June 04, 2007 7:21:06 PM (Mountain Standard Time, UTC-07:00)

Here is my latest assignment for my CMPP297 class at SAIT.

"Write a program to demonstrate that, as a high-priority thread executes, it will delay the execution of all lower-priority threads."

It took me a while to figure out a way to do this. At first I was thinking I would try to create a circular buffer with a consumer and producer object that was reading/writing to a shared data buffer. I was going to give one a higher priority then the other using the Priority property of the thread class.

This seemed like a lot of work, and I was wondering if I would be able to capture the actual requirements by doing this. I later thought back to the example we got in class about me and a friend running. I thought that if I could count the number of laps we each ran this would tell me who ran "faster".

My final solution I decided to just increment a counter in 2 different threads, giving each thread a different priority hoping that the higher priority thread would run "faster". Turns out it did, even on my P4 with hyper threading.

My Solution: (It's not elegant, but hopefully it conveys the message!)

    public class ThreadCounter {
        #region Constructors

        public ThreadCounter( ) {
            _continue = true;
        }

        #endregion

        #region Public Properties

        public Boolean Continue {
            set { _continue = value; }
        }

        #endregion

        #region Public Methods

        public void Count( ) {
            Int32 i__ = 0;

            while ( _continue ) {
                i__++;
            }
            Console.WriteLine( "{0} has a count = {1}", Thread.CurrentThread.Name, i__ );
        }

        #endregion

        #region Private Fields

        private bool _continue;

        #endregion
    }
 
    internal class Program {
        private static void Main( ) {
            const Int32 TimeoutMilliSeconds = 5000;
            ThreadCounter priorityTest = new ThreadCounter( );
            ThreadStart startDelegate = new ThreadStart( priorityTest.Count );

            Thread threadOne = new Thread( startDelegate );
            threadOne.Name = "Highest Priority Thread";
            Thread threadTwo = new Thread( startDelegate );
            threadTwo.Name = "Lowest Priority Thread";

            threadOne.Priority = System.Threading.ThreadPriority.Highest;
            threadTwo.Priority = System.Threading.ThreadPriority.Lowest;
            threadOne.Start( );
            threadTwo.Start( );

            Console.WriteLine( "Putting thread to sleep for 5 seconds... Please wait!" );
            Thread.Sleep( TimeoutMilliSeconds );
            priorityTest.Continue = false;
            Console.ReadLine( );
        }
    }

 

The results look something like this... the counts will be different based on the speed of you CPU, whether you have a single core, duo core or hyper threading!

#

Ternary Operator

Monday, June 04, 2007 11:58:20 AM (Mountain Standard Time, UTC-07:00)

I have come to become a big fan of the ternary operator... It's quite useful for replacing simple if-else statements.
Ternary operator template:
( true/false expression to evaluate ) ? (true evaluation) : (false evaluation) ;


E.g.

            Boolean IsMoCool = false;
            String s = ( IsMoCool ) ? "Mo is cool" : "Mo is not cool";
            Console.WriteLine( s );

Can you predict the result? This should print "Mo is not cool" to the console window. This happens for 2 reasons, the first is the "IsMoCool" value is initialized as false. So when the statement ( IsMoCool ) evaluated it yields a false value and executes the false condition. The 2nd reason this works is because mO is not cool!
Here is maybe a better usage of the ternary operator...
Let's say I have the following code...

    public class TernaryDemo {
        private object _myObject;

        public object MyObject {
            get {
                if( null == _myObject ) {
                    _myObject = new object( );
                }
                return _myObject;
            }
        }
    }

This could be re-written as....

    public class TernaryDemo {
        private object _myObject;

        public object MyObject {
            // if _myObject hasn't been constructed yet then create an instance,        
            // otherwise return the constructed instance.        
            get { return ( null == _myObject ) ? _myObject = new object( ) : _myObject; }
        }
    }

Recently I was reading an article from an MSDN blog... (I'm sorry I didn't save the link... I will have to look it up later.) And I came across the ?? operator added in C# 2.0. Whoa!
Here's how (I think) it works...

        private string _s;

        public void MyMethod( ) {
            string s = ( null == _s ) ? "Some Clever Text Here" : _s;
        }

The above code can be re-written using ?? like this...

        private string _s;

        public void MyMethod( ) {
            string s = _s ?? "Some Clever Text Here";
        }

The ?? operator implicitly does the same operation as the ternary operator but looks much cleaner.

#

Deadlock

Wednesday, May 30, 2007 7:20:18 PM (Mountain Standard Time, UTC-07:00)

A deadlock occurs when two or more threads are trying to access the same data but are blocking each other from getting at the resources necessary to continue.

 

    internal class Program {
        private static void Main( ) {
            Deadlocker deadlock = new Deadlocker( );

            Thread first = new Thread( new ThreadStart( deadlock.First ) );
            Thread second = new Thread( new ThreadStart( deadlock.Second ) );
            first.Start( );
            second.Start( );

            first.Join( );
            second.Join( );
        }
    }

    /// <summary>
    /// 1. First thread starts and locks resourceA
    /// 2. Second thread starts and locks resourceB
    /// 3. First thread blocks waiting for resourceB to be freed.
    /// 4. Second thread blocks waiting for resourceA to be freed.
    /// 5. The application stops in it's tracks.
    /// </summary>
    internal class Deadlocker {
        #region Public Methods

        public void First( ) {
            lock ( _resourceA ) {
                lock ( ( _resourceB ) ) {
                    Console.WriteLine( "First" );
                }
            }
        }

        public void Second( ) {
            lock ( _resourceB ) {
                lock ( ( _resourceA ) ) {
                    Console.WriteLine( "Second" );
                }
            }
        }

        #endregion

        #region Private Fields

        private object _resourceA = new object( );
        private object _resourceB = new object( );

        #endregion
    }

Remember that lock implicitly translates too...

 

    lock ( _resourceB ) {
        
    }
    
    // translates too
    Monitor.Enter( _resourceB);
    try {
        
    }
    finally {
        Monitor.Exit( _resourceB );
    }

Instead of using Monitor.Enter(), you can use Monitor.TryEnter();

 

    if ( !Monitor.TryEnter( _resourceB, TimeSpan.FromSeconds( 5 ) ) ) {
        throw new TimeoutException( );
    }
    try {
        
    }
    finally {
        Monitor.Exit( _resourceB );
    }

For more info check out...

 

MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation
by Tony Northrup, Shawn Wildermuth, Bill Ryan

Read more about this title...

Assignment11.zip (9.12 KB)

#

Asterisk Patterns

Saturday, May 26, 2007 11:32:16 AM (Mountain Standard Time, UTC-07:00)

So in class this week were given the following problem to solve:

"Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form Console.Write( "*" ); which causes the asterisks to print side by side. A statement of the form Console.WriteLine(); can be used to move to the next line. A statement of the form Console.Write( " " ); can be used to display a space for the last two patterns. There should be no other output statements in the application. [Hint: the last two patterns require that each line begin with an appropriate number of blank spaces.]"

 

Here is my solution:

 

    #region Public Methods

    public static void Main( ) {
        OutputAC( delegate( Int32 xAxis, Int32 i ) { return ( xAxis < i + 1 ); } );

        OutputBD( delegate( Int32 xAxis, Int32 i ) { return ( xAxis < i ); } );

        OutputAC( delegate( Int32 xAxis, Int32 i ) { return ( xAxis >= i ); } );

        OutputBD( delegate( Int32 xAxis, Int32 i ) { return ( i <= xAxis + 1 ); } );
        Console.ReadLine( );
    }

    #endregion

    #region Private Fields

    private delegate Boolean CheckCondition( Int32 xAxis, Int32 charactersPerRow );

    #endregion

    #region Private Methods

    private static void OutputAC( CheckCondition condition ) {
        Int32 charactersPerRow = 0;
        // loop through the y axis from row 0 to 10
        for ( int yAxis = 0; yAxis < 10; yAxis++ ) {
            // loop through x axis from column 0 to 10 for each row.
            for ( int xAxis = 0; xAxis < 10; xAxis++ ) {
                // write the character for the current position
                Console.Write( condition( xAxis, charactersPerRow ) ? "*" : " " );
            }
            ++charactersPerRow;
            Console.WriteLine( );
        }
    }

    private static void OutputBD( CheckCondition condition ) {
        Int32 charactersPerRow = 10;
        for ( int yAxis = 0; yAxis < 10; yAxis++ ) {
            for ( int xAxis = 0; xAxis < 10; xAxis++ ) {
                Console.Write( condition( xAxis, charactersPerRow ) ? "*" : " " );
            }
            --charactersPerRow;
            Console.WriteLine( );
        }
    }

    #endregion

Assignment1.zip (5.62 KB)

#

Rebuild Your Database With nAnt

Tuesday, May 22, 2007 12:10:07 PM (Mountain Standard Time, UTC-07:00)

Re-building your database using nAnt!

 Source Code:

Have you ever peeked into the SQL Server tools folder. I found a couple of interesting tools in there.

Both of these useful executables allow you to connect to a SQL Server. So using either of these executables and the power of nAnt, I can re-build a database from scratch.

 

<?xml version="1.0"?>
<project name="University" default="all">
    <!-- environment-specific properties -->
    <property name="sqlcmd.exe" value="C:\program files\microsoft sql server\90\Tools\Binn\sqlcmd.exe" />
    <property name="sqlcmd.ConnectionString" value="-E" /><!-- Windows Authentication -->            
    <property name="initial.catalog" value="University"/>
    <property name="initial.server" value="(local)" />
    <property name="database.path" value="C:\nant\databases" />    

    <target name="convert.template">
        <echo message="Convert the SQL file template to one with the actual database name." />
        <copy file="${target}.template" tofile="${target}" overwrite="true">
            <filterchain>
                <replacetokens>
                    <token key="INITIAL_CATALOG" value="${initial.catalog}" />
                    <token key="DBPATH" value="${database.path}"/>
                </replacetokens>
            </filterchain>
        </copy>
    </target>
    
    <target name="exec.sql.template">
        <call target="convert.template" />
        <echo message="Connecting to database server..." />
        <echo message="${sqlcmd.exe} ${sqlcmd.ConnectionString} -b -i ${target}" />
        <exec program="${sqlcmd.exe}" commandline="${sqlcmd.ConnectionString} -S ${initial.server} -b -i ${target}" />
    </target>    
    
    <target name="builddb">
        <copy todir="${database.path}">
            <fileset basedir="sql\original">
                <include name="*"/>
            </fileset>
        </copy>
        <property name="target" value="sql\attach.sql"/>
        <call target="exec.sql.template"/>
    </target>                   

</project>

In order to create the database you will have to update the properties in the build file to settings specific to your machine, then open a command window to the directory containing the build file and type "build builddb" then press enter.

Resources:

#

Interface Based Programming

Monday, May 21, 2007 8:24:19 PM (Mountain Standard Time, UTC-07:00)

"By using the interface, I allow myself the advantage of making it easier to change implementations later on if I need to. Another implementation may provide performance improvements, some database interaction features, or other benefits. By programming to the interface rather than to the implementation, I avoid having to change all the code should I need a different implementation... You should always try to program to an interface like this; always use the most general type you can." - Martin Fowler -

UML Distilled: A Brief Guide to the Standard Object Modeling Language, Third Edition
by Martin Fowler

Read more about this title...

Let's take a look at the following code as an example:

  1 		[Test]
  2 		public void GetStudents_ShouldReturnAllStudents( ) {
  3 			List< Student > students = _store.GetStudents( );
  4 			Assert.IsNotNull( students );
  5 			foreach ( Student student in students ) {
  6 				Console.WriteLine( student.FirstName + student.LastName );
  7 			}
  8 		}

 

The code above is tightly bound to a specialized type of collection, List<T>. If we crack open Lutz Reflector and take a look at the List<T> type we can see that it implements IList<T> and ICollection<T>.

 

 

 

If we wanted to code to an abstraction, in this case we have two options, IList<T>, ICollection<T>. (For the above test it would probably be best to use IEnumerable<T>, but let's assume we need to add items to the collection in client code.)

If we take a look at IList<T>...

As you can see IList<T> implements ICollection<T>. ICollection<T> does not implement IList<T>, it would be safe to say that ICollection<T> is the most generalized form of List<T> or IList<T>, which gives us the greatest flexibility to change the underlying implementation of "GetStudents()" in the future.

The final code looks more like this:

  1 		[Test]
  2 		public void GetStudents_ShouldReturnAllStudents( ) {
  3 			ICollection< Student > students = _store.GetStudents( );
  4 			Assert.IsNotNull( students );
  5 			foreach( Student student in students ) {
  6 				Console.WriteLine( student.FirstName + student.LastName );
  7 			}
  8 		}
 

As a side note, for this particular contrived example since ICollection<T> also implements IEnumerable<T> the above can be re-written as follows (without any changes to the implementation of GetStudents())

  1 		[Test]
  2 		public void GetStudents_ShouldReturnAllStudents( ) {
  3 			IEnumerable< Student > students = _store.GetStudents( );
  4 			Assert.IsNotNull( students );
  5 			foreach( Student student in students ) {
  6 				Console.WriteLine( student.FirstName + student.LastName );
  7 			}
  8 		}
 

Additional Resources:


- C# Interface Based Development

- The Interface Construct in C#

 

#

Returning the Default on Generic Types

Friday, May 18, 2007 2:37:24 AM (Mountain Standard Time, UTC-07:00)

So during my quest to understand NHibernate I came across a new keyword in C#. (well kind of new, it's actually an old keyword but used in a different manner specifically for generic types.)

Here's my problem... When you define a generic type it does not assume it to be either of a reference type or value type. And I do not want to force my type to be a reference type, I want it to be generic. But in a scenario where I have to return an blank or "null" value, that assumption says that the type has to be a reference type...

Here's what I'm talking about:



The return null statement is making the assumption that T is a reference type. (I don't want to make this assumption!) In this case I would like to return the default value for reference types and value types without having to create 2 generic types. One for each!

So I can use the default( T ) statement which will return a null for reference types, and a 0 for value types! Problem solved.

        public T SearchFor( Int32 id ) {
            using( ISessionTransaction dbStore = _manager.StartTransaction( ) ) {
                try {
                    return ( T )dbStore.Session.Load( typeof( T ), id );
                }
                catch( ObjectNotFoundException ) {
                    return default( T );
                }
                catch( ADOException ) {
                    if( dbStore != null && null != dbStore.Transaction ) {
                        dbStore.Transaction.Rollback( );
                    }
                    throw;
                }
            }
        }


See MSDN for more information... http://msdn2.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

#

The Dispose Pattern

Thursday, May 17, 2007 7:48:42 PM (Mountain Standard Time, UTC-07:00)

Implementing the IDisposable interface can be a good idea, if done correctly! It allows you to clean up a lot of try... finally code and replace it with the fancy "using" blocks, because the "using" block implicitly invokes the dispose method and only works on types that implement IDisposable....

Lets say I define a type... (with a very poor name!)

 

  1 	public class Disposable : IDisposable
  2 	{
  3 		public void Dispose( )
  4 		{
  5 			throw new NotImplementedException( );
  6 		}
  7 	}

I could use the type like this....

  1 		public void Using( )
  2 		{
  3 			using ( Disposable myType = new Disposable( ) ) {
  4 				Console.WriteLine( myType );
  5 			}
  6 		}

Which is actually doing something like this...

 

  1 		public void TryFinally( )
  2 		{
  3 			IDisposable myType = null;
  4 			try {
  5 				myType = new Disposable( );
  6 				Console.WriteLine( myType );
  7 			}
  8 			finally {
  9 				if ( myType != null ) {
 10 					myType.Dispose( );
 11 				}
 12 			}
 13 		}

 

The proper implementation of the Dispose pattern looks like this block of code...

 

  1 	public class Disposable : IDisposable {
  2 		public Disposable( IDbConnection connection ) {
  3 			_connection = connection;
  4 		}
  5 
  6 		public void Dispose( ) {
  7 			Dispose( true );
  8 			GC.SuppressFinalize( this );
  9 		}
 10 
 11 		protected virtual void Dispose( Boolean disposing ) {
 12 			if ( disposing ) {
 13 				if ( _connection != null ) {
 14 					_connection.Close( );
 15 				}
 16 			}
 17 		}
 18 
 19 		private IDbConnection _connection;
 20 	}

 

So why do we need a protected virtual method named Dispose that takes in a boolean paramater, when the IDisposable interface only demands a method with a signature of public void Dispose()?

The boolean paramter tells if the method was invoked from the finalizer (aka destructor, which can be called at some unknown point in time by the garbage collector, which may be well after the resource has already been cleaned up by it's finalizer) or from client code explicitly calling the IDisposable.Dispose method. If the method is called from the finalizer, then disposing is false and it's not safe to touch any resources or other objects. (You don't want to raise exceptions in your finalizer!)

This makes sure that any resources used by your type does not get touched within the finalizer, since you can't tell if that resource has already been finalized by it's finalizer!

Since it's expected that your dispose will be cleaning up any resources used by your time, there is no sense in allowing your type to be finalized AGAIN! By calling GC.SuppressFinalize, you're telling the garbage collector not to finalize this type, because it has already been cleaned up. This should only be called if no exceptions are raised from your cleanup! (Which is why SuppressFinalize, should be called after the call to Dispose( true ) and not before!

For more information check out...

 

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series)
by Krzysztof Cwalina, Brad Abrams

Read more about this title...

http://msdn2.microsoft.com/en-us/library/system.gc.suppressfinalize(VS.71).aspx

http://msdn2.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx

http://msdn2.microsoft.com/en-us/library/12afb1ea-3a17-4a3f-a1f0-fcdb853e2359(vs.80).aspx

#

Magical Collection of .NET

Thursday, May 17, 2007 10:58:35 AM (Mountain Standard Time, UTC-07:00)

For I came across a couple of pages that discuss the use of collections in C#. I found them to be very helpful and I thought I would share...

Collections vs. Generic Collections

How to use Collections

 

This gist of it is this... use the most abstract type! Instead of accepting a parameter of type List<T>, which is a specific type of collection, consider using ICollection<T> or IList<T>!

IList<T> implements ICollection<T> so ICollection<T> is a more generic type of IList<T>. This allows for greater flexibility if you need to make changes under the hood!

 

   1:  [TypeDependency("System.SZArrayHelper")]
   2:  public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
   3:  {
   4:      // Methods
   5:      int IndexOf(T item);
   6:      void Insert(int index, T item);
   7:      void RemoveAt(int index);
   8:   
   9:      // Properties
  10:      T this[int index] { get; set; }
  11:  }
 

ICollection<T> implements IEnumerable<T>, so if you're just iterating through a collection, consider passing it as IEnumerable<T> instead of a specific type of collection.

 

   1:  [TypeDependency("System.SZArrayHelper")]
   2:  public interface ICollection<T> : IEnumerable<T>, IEnumerable
   3:  {
   4:      // Methods
   5:      void Add(T item);
   6:      void Clear();
   7:      bool Contains(T item);
   8:      void CopyTo(T[] array, int arrayIndex);
   9:      bool Remove(T item);
  10:   
  11:      // Properties
  12:      int Count { get; }
  13:      bool IsReadOnly { get; }
  14:  }
 

For instance the following code could be re-written...

   1:     public void Iterate( ICollection< T > records ) {

   2:          foreach( T record in records ) {
   3:              // do something that has no effect to records.
   4:          }
   5:      }
 
This can be re-written too...
 
   1:      public void Iterate( IEnumerable< T > records ) {
   2:          foreach( T record in records ) {
   3:              // do something that has no effect to records.
   4:          }
   5:      }
 

#

Unsafe C#

Monday, May 14, 2007 11:46:24 AM (Mountain Standard Time, UTC-07:00)

Can you spot the overflow...?

   1:  using System;
   2:   
   3:  namespace UnsafeCode
   4:  {
   5:      public class Program
   6:      {
   7:          public static unsafe void Main( )
   8:          {
   9:              Int32[] array = new int[4];
  10:              for( int i = 0; i < 4; i++ ) {
  11:                  array[ i ] = i * i;
  12:              }
  13:              Console.WriteLine( "Display 6 items (oops!)" );
  14:   
  15:              fixed( Int32* ptr = array ) {
  16:                  for( int j = 0; j < 6; j++ ) {
  17:                      Console.WriteLine( *( ptr + j ) );
  18:                  }
  19:              }
  20:              Console.WriteLine( "Display all items" );
  21:              foreach( int k in array ) {
  22:                  Console.WriteLine( k );
  23:              }
  24:          }
  25:      }
  26:  }

Pretty cool hey... you can use pointer in C#. You have to do a couple things though, in order to get it to work.

1. You have declare the block of code as unsafe

unsafe ... {
}

2. You have to tell the C# compiler to allow unsafe code. You can do this with the /unsafe switch or check the checkbox in the project settings.

3. You will also have to pin the objects you are pointing to, so that the garbage collector does not reclaim that memory. Use the fixed keyword. The following will pin the array so that it does not get reclaimed by the garbage collector.

    fixed( Int32* ptr = array ) {

    }
 

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series)
by Krzysztof Cwalina, Brad Abrams

Read more about this title...

#

Don't swallow Exceptions!

Thursday, May 10, 2007 7:28:23 PM (Mountain Standard Time, UTC-07:00)

I know there are a lot of programmers who do not want their application to crash out in the field and they are willing to do almost anything to stop that from happening - like swallow exceptions and let the program continue to run. But this is absolutely the wrong thing to do; it is much better for a program to crash than to continue running with unpredictable behavior and potential security vulnerabilities. - Jeffrey Richter (Framework Design Guidelines)

Bad code:

  1     try
  2     {
  3         currentPageInContext = context.Session["CurrentPage"].ToString().ToLower();
  4     }
  5     catch { }

I don't think most developers are aware of how expensive it is to raise exceptions, and if you develop so that exceptions are part of your programming logic like the above code, I think it's time you made a change!

In the above example the developer is swallowing a potentional ArgumentNullReference to continue executing code... silly... this code could have been written like so...

  1 	currentPageInContext = context.Session[ "CurrentPage" ] as String;
  2 	if( null != currentPageInContext ) {
  3 		currentPageInContext.ToLower( CultureInfo.InvariantCulture );
  4 	}

So what's happening here? The code is attempting to pull a value out of Session with a key of "CurrentPage". It's using the "as" keyword to cast to a type of String. Why use the "as" keyword? The reason for using the "as" keyword is because if the type cannot be cast to the type string it will return a value of "null" instead of raising an InvalidCastException. So the next step is to check that the returned value is in fact not null, if so then drop it to lower case. (Also, it's a good habit to make use of the overload that allows you to specify the CultureInfo or IFormatProvider. If you don't belive me, FxCop it!)

 Globalization Rules

 

 

 

 

 

Another thought... instead of using...

  1 DateTime.Parse( inputDate );

Use..

  1 DateTime.TryParse( inputDate, out selectedDate );

Also, if you decide to catch an Exception and raise a more specific exception in it's place make sure you toss in the old exception as the innerException parameter on your new Exception. Otherwise, you will lose the Stack Trace and other useful data for understanding what in the heck went wrong...

Here's an example of what not to do:

  1 	try {
  2 		...
  3 	}
  4 	catch (Exception e) {
  5 		throw new Exception(e.ToString());
  6 	}

The above example is bad for a couple of reasons. The first, well... catching an Exception then throwing another exception of the exact same type is expensive and a waste. If you're not going to do anything with the exception then don't catch it... If you really need to do it... do it like this...

This is better than above, but it's still not optimal:

  1 	try {
  2 		...
  3 	}
  4 	catch (Exception e) {
  5 		throw;
  6 	}

The following example is contrived, and probably still does not make sense... but if you have to re throw an exception from a catch block you might as well do it like this...

  1 	try {
  2 		...
  3 	}
  4 	catch (Exception e) {
  5 		throw new ArgumentOutOfRangeException( "Dude... this message sucks!", e);
  6 	}

This concludes another rant...

#

Question: What happens when you call a virtual member from an objects constructor?

Wednesday, May 09, 2007 8:46:36 PM (Mountain Standard Time, UTC-07:00)

Please consider the following code snippet... (sourced from "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries". A definitely good read!)

 

  1 public abstract class Base {
2 public Base(){
3 Method();
4 }
5 public abstract void Method();
6 }
7
8 public class Derived : Base {
9 private Int32 _value;
10
11 public Derived() : base()
12 {
13 _value = 1;
14 }
15
16 public override void Method(){
17 if( 1 == _value ){
18 Console.WriteLine( "All is good in the hood!" );
19 }
20 else{
21 Console.WriteLine( "What is wrong?" );
22 }
23 }
24 }

Can you predict the outcome...?

Hint: When you call a virtual member the most derived override to will be called, even if the constructor of the most derived type has not been fully run yet. Remember... although it's not explicitly stated in the above sample, when "Derived" is constructed it's base types constructor is run first!

Perhaps this will make things a little clearer...

 

  1 public abstract class Base
2 {
3 public Base()
4 {
5 Method();
6 }
7 public abstract void Method();
8 }
9
10 public class Derived : Base
11 {
12 private Int32 _value;
13
14 public Derived() : base() // explicit call to base class constructor 15 {
16 _value = 1;
17 }
18
19 public override void Method()
20 {
21 if ( 1 == _value )
22 {
23 Console.WriteLine("All is good in the hood!");
24 }
25 else 26 {
27 Console.WriteLine("What is wrong?");
28 }
29 }
30 }

If this still isn't clear... maybe now is a good time to put Snippet Compiler to the test. If you don't already use it, go download it from here...

Then download this source file and run the code...

Default.cs (.88 KB)

#

Windows Live Writer

Tuesday, May 08, 2007 9:11:46 PM (Mountain Standard Time, UTC-07:00)

So I just installed the Windows Live Writer beta for posting to my blog and thought I would give it a try with a brand spankin' new blog entry!...

Here's a little something you probably didn't know.... In C# you can set access modifiers to your setters and getters for your properties. Like so...

  1 public class MyClass {	
  2 	private String _myProperty;
  3 	
  4 	public String MyProperty {
  5 		get{ return _myProperty; }
  6 		private set{ _myProperty = value; }
  7 	}
  8 }
Hopefully, you've learned a little somethin', somethin'!
 

#

String Intern Table

Tuesday, May 08, 2007 11:58:42 AM (Mountain Standard Time, UTC-07:00)

The String intern table... I just read a pretty good article on this that is definitely worth checking out... the link is http://www.sliver.com/dotnet/emails/default.aspx?id=6

#

Resharper Test Template

Tuesday, May 08, 2007 10:52:34 AM (Mountain Standard Time, UTC-07:00)

My Resharper Test template....

/*
* Created by: $AUTHOR$
* Created: $DATE$
*/

using NUnit.Framework;
using Rhino.Mocks;

namespace $NAMESPACE$
{
    [TestFixture]
    public class $CLASS$
    {
        private MockRepository _mock;

        [SetUp]
        public void SetUp( )
        {
            _mock = new MockRepository( );
        }

        [TearDown]
        public void TearDown( )
        {
            _mock.VerifyAll( );
        }
        
        [Test]
        public void _Should()
        {
            
        }
    }$END$
}


#

Document Search With Google Search Software Development Kit

Tuesday, May 08, 2007 3:36:41 AM (Mountain Standard Time, UTC-07:00)

Ok... so when working with Google Desktop using the query model that my previous post described you don't get access to all sorts of other document properties that, supposedly, available when you work directly against the Google Desktop Search SDK. (Those damn .idl files!)

The setup... so first of all you're going to need to install Google Desktop on your machine so that it can take care of indexing files... (You probably could take the necessary Google assembly's and register just the ones you want, and create your own windows service to do add files to the Google index... i don't know that's probably beyond my skill set at the moment!)

Once you've got Google Desktop Search installed, you're going to need to add to COM references to your project... These guys are:
- Google Desktop Search API 1.1 Type Library
- Google Desktop Search Query API 1.0

Ok so in order to use the Google Query API your app has to first register with it, the Query API will then return a cookie that you need to hang on to. You'll use this cookie to make any search requests to the Google Query API.

In order to register you need to provide a description of your application and a globally unique identifier (guid) for your application. Here's a very rudimentary example... (I highly suggest that you don't actually use this code, but hopefully it helps with learning)

        public static int Register( )
        {            
            Object[] description = new Object[] {
                 "Title",
                 " tests",
                 "Description",
                 "Simple tests",
                 "Icon",
                 "My Icon@1"
             };

            const String applicationGuid = "{5323E036-345C-4323-548D-32AA55603215}";
            GoogleDesktopRegistrar registrar = new GoogleDesktopRegistrar( );

            registrar.StartComponentRegistration( applicationGuid, description );
            object regObjObj = registrar.GetRegistrationInterface( "GoogleDesktop.QueryRegistration" );

            IGoogleDesktopRegisterQueryPlugin query = regObjObj as IGoogleDesktopRegisterQueryPlugin;
            if( query == null ) {
                return 0;
            }
            else {
                Int32 cookie;
                cookie = query.RegisterPlugin( applicationGuid, true );
                registrar.FinishComponentRegistration( );
                return cookie;
            }
        }

So what's going on?... Well, in the above code there is a hard-coded guid ("{5323E036-345C-4323-548D-32AA55603215}";) and an object array of strings. The object array is the description of your application. When you call FinishComponentRegistration() the following dialogue will pop up.

This is Google's way of prompting the end-user of whether or not they want your application installed on their PC. If Ok is pressed you can use the cookie received in the call the line above it. If cancel is pressed a COMException is raised and that cookie is useless!

What does a cookie look like?
Well... for me the cookie was the value "1030818419". For the testing I copied the value and stuck it in a constant... but as the SDK suggests, you will probably want to encrypt this and store it somewhere where you can read it out and decrypt it, because you're going to need it for each search request.

private const Int32 GoogleCookie = 1030818419;

Dude.. I got a cookie! Mmmm.....

Now let's actually start searching... Instantiate a GoogleDesktopQueryAPI object and invoke the Query method... or QueryEx (for the ability to read and write to the index. In this example we just registered for a read-only cookie for searching!)

The Query method will return an object that contains a collection of search results. Unfortunately, there's no enumerator or indexer so foreach doesn't work here... *sigh*.

        public static void Search( String forText )
        {
            Int32 cookie = GoogleCookie;
         GoogleDesktopQueryAPI queryAPI = new GoogleDesktopQueryAPI( );
         IGoogleDesktopQueryResultSet results = queryAPI.Query( cookie, forText, "file", null );
            
         IGoogleDesktopQueryResultItem2 item;
         while( ( item = ( IGoogleDesktopQueryResultItem2 )results.Next( ) ) != null ) {
         Console.WriteLine( item.GetProperty( "uri" ) );
         }            
        }

Looks kind of ugly hey? In order to get properties on each search result you have to call the "GetProperty()" method on each result item. AND you have to pass it a string value as the property name.... Gross!

A possible way to get around this would be to create a private class or structure or string constants... This isn't that more elegant, and in fact this could be broken out and organized into logical groups of properties.

        private class GoogleResultItemProperty
        {
            public const String ActualWork = "actual_work";
           
public const String AlbumTitle = "album_title";
           
public const String Artist = "artist";
           
public const String Assistant = "assistant";
           
public const String Attendees = "attendees";
           
public const String Author = "author";
           
public const String Categories = "categories";
           
public const String Company = "company";
           
public const String FolderName = "folder_name";
           
public const String Format = "format";
           
public const String IMAddress = "im_address";
           
public const String Keywords = "keywords";
           
public const String Language = "language";
           
public const String LastModifiedTime = "last_modified_time";
           
public const String Length = "length";
           
public const String Location = "location";
        }

However, I keep getting COMException's when i try to access properties that I'm sure should be there... for instance I know that I've set the author property on...

But when I try to access the author property on that document a COMException is raised. Why is this happening? The whole purpose of using the Google Search SDK is so that I can retrieve that property without having to directly access that file!

In conclusion, I still have much to learn about COM and the Google Desktop Search API. I'm found the documentation on the API rather hard to read an understand. (It can be found here...) Hopefully, this helps a little!

#

Document Search

Monday, May 07, 2007 10:37:46 AM (Mountain Standard Time, UTC-07:00)

Documentation Search


How to build your own documents search!

  1. Lucene.NET
  2. Seekafile Server
  3. Google Desktop Search

 The purpose of this document is to describe how to build a document search using different API’s available. All code snippets are taken from sample projects and written in C#. Some samples code was removed for clarity!

Lucene.NET: (http://www.dotlucene.net/)


Lucene.NET is an open source project that allows the consumer of the library the ability to parse index files and format the results. (Useful for searching for documents!)

Some notable features are:

  1. Ranked search results
  2. Query highlighting
  3. .NET assembly. (No reference to COM)
  4. API available for building your own index files.

For the time being… let’s assume we have an index created that we can use to search from. (We will cover creating an index when we get to Seekafile Server!)

The guts of Lucene.NET come from a few Mr. Do-it-all objects named:

  • IndexSearcher: takes in a query and searches the index files for results. It returns a “Hits” object.
  • Query
  • QueryParser
  • QueryHighlightExtractor
  • Hits: object contains an “ArrayList” of documents. (Kind of poorly crafter, I would have preferred a strongly type generic list… of say document objects?)

 

The basic usage of Lucene is as follows…

 

There is also a QueryHighlightExtractor object that wraps your search tag with “<b></b>” markup for display on the web.

 

Seekafile Server


 - Source: http://www.dotlucene.net/seekafile-server-open-source-indexing-server
To build an index to search from I used the Seekafile server open source project. It is currently in version 1.5 beta 3 release.

Seekafile server is a windows service that searches through specified directories and create a search index. To configure the “index” directory and “documents” directory you can either use the Seekafile Server manager.

 

Or… you can configure the settings in the config.xml file located in the Seekafile server installation directory.

 

You can include additional IFilters to search different document types like “.rtf”, “.pdf”, “.vsd” etc.

This was pretty easy to install and setup, but during my test development I found that I had to stop the Seekafile server service, wipe out the contents of the index and lock directories and restart the service. I have not determined what was causing this problem.

Google Desktop Search


The Google Desktop Search is an application that you can download from Google, it indexes files on your PC and/or network and allows you to search for them through your browser. It has built in support to search for file types such as…


The Component Object Model Way!

 
The Google Desktop Search SDK (Software Development Kit) is available for use, with documentation available at http://desktop.google.com/dev/index.html

 
The SDK ships with 3 “.idl” files:

  1. GoogleDesktopActionAPI.idl
  2. GoogleDesktopAPI.idl
  3. GoogleDesktopDisplayAPI.idl

 
The first requirement when using the SDK is to register your application with the Google Desktop Search application loaded on the machine. I was unable to get this to actually work when testing… I kept receiving a COMException.

 
I’m not a big fan of COM, probably because my experience is limited, and I have access to the power of .NET!

The .NET Way! (Without the use of Interoperation)

The way I found was a much easier way to interact with Google Desktop Search was through a web request. Google Desktop receives all requests through http://127.0.0.1:4664/

 

By sending a request to this URL, with a specially crafted query string I am able to retrieve search results back in the form of XML.

The URL and port number can be retrieved from the Windows Registry.

If Google Desktop Search is installed on the machine it stores this Uri in the registry.

 

Once we have the Uri to connect to Google Desktop we can start sending search requests. Google Desktop takes care of managing the search index and creates a layer of abstraction for us by allowing us to make direct queries to it and retrieving results.

 
The query string parameters:

  • &format=xml” This tells Google Desktop to return the results in an Xml format.
  • &num=10” This tells Google Desktop to return 10 results.
  • &in= C:\Documents and Settings\mkhan\My Documents” This tells Google Desktop to return only results from “My Documents” directory.
  • &q=Microsoft” This tells Google Desktop to search for the word “Microsoft”.

There are a number of other parameters that we can send, in fact just about every option in the Advanced search has an equivelent query string parameter.

 

For the time being we can use the above parameters to send a request to Google Desktop. We will do this using the WebClient object.


Google Desktop will reply with a stream of Xml that looks like….


We can now parse out these results and format them in whatever context we like. This is usable in a Web application as well as a Desktop Application. However, it may be a little trickier with a Desktop Application. We would have to expose a web service or a method of exposing the search results from Google desktop to external clients.

For example if all the documents were stored on a central server and Google Desktop was installed on that server, we would have to create a Web service that takes in search requests, passes that request to Google Desktop and returns the xml results. The Desktop application could then search for those documents from wherever it has access to that web service.

If the web service were exposed to the internet, this potentially means that a user could search for documents stored on the business server from home.

 

#

Sleep Sitting

Thursday, May 03, 2007 10:45:18 AM (Mountain Standard Time, UTC-07:00)

Well Dasblog sure is interesting... it was pretty easy to set up and get running, but it's a little confusing when trying to add users. Oh well hopefully i can get the rest of ya'll to start blogging!

So I've learned quite a few interesting skills while riding the bus. My favorite is the art of sleep sitting. Yes it is a very difficult skill to master, I have much to learn still but I'm on my way!

One thing you do not want to do while sleep sitting is slouch. If you slouch you are more likely to lay your head on the shoulder of the person next to you. I don't mind to much when someone nods off on my shoulder but I prefer not to do the same to others.

Try to exercise good posture as you are getting into your sleepy zone!

Zzzz....

On another note i read an interesting article last night on TDD anti-patterns... It's a good read and it taught me that as a newbie I am making a lot of classic TDD mistakes... Check out the article if you have a chance... http://blog.james-carr.org/?p=44

Here's an example of a unit test i am currently working on for the Google Desktop Search.

        [Test]
        public void BuildQuery_ShouldReturnQueryInXmlFormat()
        {
         String directory = Environment.SystemDirectory;

         GoogleDesktopQueryBuilder builder = new GoogleDesktopQueryBuilder( );
         builder.Add( Filter.Directory, directory );
         String query = GoogleDesktopQueryBuilder.Build( );

         StringAssert.Contains( "http://127.0.0.1:4664/search&s=", query );
         StringAssert.Contains( XmlFormat, query );
         StringAssert.Contains( Directory, query );

         directory.Replace( ":", "%3A").Replace( "/", "%5C").Replace( " ", "+")
        }

From the little research I have done with the Google Desktop Search API I have become a fan. There's a couple of ways to develop against GDS, one is to download the SDK and import the IDL file and start plugging away. You have to do some silly things like create a GUID for your "plug-in" then ask for a cookie to use for all search requests. I found this approach a little more difficult and not as friendly to .NET. Most of the samples are in C/C++!

The alternative approach was to run the Google Desktop search in a browser, y'know the way it was meant to be used and I quickly recognized a pattern. All searches are stateless!

What do i mean by this, well... all searches are done through query string parameters...

        //http://127.0.0.1:4664/search&s=SFJNMLuPcNAwknyAszkB-ZEL-c0?ie=UTF-8
        //&adv=1
        //&type=cat_files
        //&ot=
        //&file=doc%7Cdocx
        //&ext=
        //&in=C%3A%5CDocuments+and+Settings%5Cmkhan%5CMy+Documents
        //&under=on
        //&to=
        //&from=
        //&domain=
        //&has=GoogleDesktop+
        //&no=
        //&within=86400
        //&day=

So I decided to make use of my friend the "WebClient" class and make a request to http://127.0.0.1:4664 to see what would happen... Well if you use the "&format=xml" parameter the response is an xml stream with results that look like this...

 

This means a couple of things... I have access to all the different search filters and advanced searches available to Google Desktop Search... this includes search for file types, search within directories, search for x # of files in directory...

If you have any questions please let me know!

#

AJAX Call Processor with ASP.NET

Friday, June 30, 2006 9:17:35 PM (Mountain Standard Time, UTC-07:00)

AJAX, shorthand for Asynchronous JavaScript and XML, is a Web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability." - wikipedia

There are 3 main components in my AJAX implementation. The client side JavaScript and HTML, and the server side AJAX call processor. For this articles I am going to discuss how I implemented the blog page on this site using AJAX.

Client Side

If you check the source code behind my blog page you may notice 2 script files were included. These are "ajax_obj.js" and "getEntry.js". The "ajax_obj.js" file creates an instance of the "XMLHttpRequest" object for non Microsoft browsers and an "ActiveXObject" for Microsoft web browsers. This object is pretty cool, it's the basis for almost all AJAX technology. Learn it, understand it and AJAX will become a breeze.

AJAX Base Object

The 2nd js file, "getEntry.js" performs the interaction between my web server and the client machine (You're the client by the way!). What it does is sends a request to my server for my latest blog entry, my server takes the request and returns just the blog entry. Duh!

 Retrieve Blog Entry

But how does it do this? Using the "XMLHttpRequest" or "ActiveXObject" object instantiated in the "ajax_obj.js" file we use 4 methods/properties. To make this easy let's call this guy "goAJAXReq", short for global AJAX request object.

  • open: This specifies what type of request I would like to make the server, and what URL to call.
  • onreadystatechange: This specifies a "callback" function to handle the servers response to my request. The callback is basically a function created in order to receive the call back. It's like leaving a voicemail message on your buddy's phone and telling him to call you back at this number when he gets the message.
  • send: This tells the "goAJAXReq" to send the request to the server. Kind of like picking up the phone to call your buddy. Except like me your buddy never answers the phone so you'll have to leave a message.
  • status: This tells you the status of your request so far. It's actually and HTTP status, and would be similar to an operator message. "This number cannot be reached. Please try again!" If you don't get this message most people here a "Hello!?" on the other end. The "Hello" is a 404 status. The operator message is like the HTTP 200 or 404 status.

"getEntry()" function. This guy dials the phone number, leaves a message with a "callback" number and pressed # to send the message.

"updatePage()" is the number buddy can call me back at. So when buddy calls me I answer at this number and he gives me the info that I need. When I receive my blog entry back from my server I search for an HTML element on the page called "blog". This is defined as a <div> tag, and I write the data returned back to me in this element. Voila, that's the AJAX on the client side. Now you can go into a lot more detail with how you would like your data sent to you, and how you would like it packaged and unpackaged. But for this example, my call returned straight forward HTML for my blog entry.

Server Side

The server side implementation can be done in so many different ways. Most of the AJAX articles I found on the net used PHP, for this example I am using ASP.NET. The key component in my implementation is the use of "reflection". My AJAX object "goAJAXReq" sends the method name it wishes to run at the server to return the data it wants. In this example the method was "getEntry". Using reflection I parse out the value for the method variable and call that function. This function grabs my latest blog entry, makes sure its valid HTML and returns the data to the client.

 AJAX Call Class

In my AJAX call class I parse out the value for the "method" variable from the request stream. I am using the "method" variable to contain the name of the method I want to invoke. In this example the request stream is sending "method=getEntry". This means the request stream wishes to process the "getEntry" method on the server. After parsing our the "getEntry" name I use reflection to call that method. My "getEntry" method grabs my latest blog entry and writes it directly to the "response" stream. This is what carries the data being transferred back to the client.

Voila! My AJAX call processor is complete. If you have any questions at all please contact me!

#