Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 14 December 2009

Script free MSDN

Posted on 06:33 by Unknown
Obviously anyone who uses MSDN online knows it been updated and now looks like a really poor MySpace page!

But I did find one feature I really like today - 'ScriptFree' mode, this is a god send in a company environment pages now load in near light-speed, check out the 'Switch View' options on the righthand side of this page.

Hopefully they'll bring out a '1992 Times New Roman' version soon ;)


Awkward Coder
Read More
Posted in MSDN Coding | No comments

Thursday, 3 December 2009

Schrödinger's Service

Posted on 05:46 by Unknown
Where I currently work the team has a set of SOA services that are used by alot of different app teams in the bank. In the UAT environment we occasionally get support issues where people can't access the services - they're receiving 404 errors!

When ever we check the services locally or remotely they're working fine and have been all the time - it appears the problem is in the infrastructure between the app team and the service endpoints. This doesn't really help our perception to rest of the bank and it's a bitch to resolve!

So we've come up with a name for the services 'Schrödinger's Services' - by the act of observing the services we've confirmed they're operating correctly and they then work for the app team as well. This happens every time we get this support query.

Check out wiki for the origin of the name.


Awkward Coder
Read More
Posted in Coding Services | No comments

Wednesday, 2 December 2009

Can I make a value object from an entity?

Posted on 03:05 by Unknown
I've built a rich domain model for a private app I'm working on, it feels right, it got the correct mix of business functionality and models the domain problem very well, it even has flexibility for the future. I consciously had to keep focusing the domain expert and myself on the current iteration and not the future!

So I reached a point where I want to expose a 'view' depending on the 'context' of usage.

Simply put I want to expose data from some of the entitles as a 'catalog'. This catalog is immutable - the users of the catalog can't change or modify the contents they can only 'view' what is available. Items in the catalog don't contain an entity identifier and they only contain a subset of an entities data. This catalog item is starting to sound like a value object to me...

So the question is; Can I create a value object from an entity?

I think it's perfectly acceptable to do this - remember a value object should be immutable, the sub-text of the question for me is; is it acceptable to expose value objects via a service? I want a service that allows searching & returning of catalog items (with pagination etc). I also think this perfectly acceptable approach.

I suppose what I've defined here is a 'context' boundary for the core domain model - 'bounded context'.



Awkward Coder
Read More
Posted in DDD Entities Value Objects | No comments

Wednesday, 18 November 2009

Continents move faster than the software industry!

Posted on 03:39 by Unknown
Read this last week and it shows how dynamic and fast moving the software industry really is!

Awkward Coder
Read More
Posted in Coding, Developement, OO | No comments

Removing friction from the process

Posted on 03:35 by Unknown
Oren has a great blog post about friction in the delivery of software and how it should be evaluated and removed ASAP.


Awkward Coder
Read More
Posted in Coding, Development, Process | No comments

Wednesday, 11 November 2009

build for test != build for release

Posted on 02:17 by Unknown
This might seem obvious to a lot of people - the people who actually do testing, but to everyone who doesn't or just waves a derogatory hand in the general direction it isn't...

The differences manifests it's self in how the codebase is structured in your source control system. A codebase setup for test will have all the dependencies in the correct structure so when you pull the codebase, build the code and execute the tests you don't have to know what or how it's installed when the application is released - seems obvious right!

I've just attempted to do this and low and behold a missing dependency, I don't know the application and I don't particularly want to right now but I'm going to have to spend sometime just to get the code to build - I suspect I need to install some application on the system before I can build let alone test - WRONG, WRONG, WRONG!

Shite developers and there are a few, seem to think this job is about friction - friction pulling the code, friction building the code, no testing and friction deploying the code. These are the default parts of the job - we all have to do this so it should be automated and frictionless.
Read More
Posted in Coding Building CI Testing | No comments

Friday, 6 November 2009

When I'm a new team member

Posted on 09:06 by Unknown
Jsut had a meeting about how to improve the build process for the team - the current structure of the code in the source control system means I can't just get the code out and build it - this to me is the sign of a failing project\team!

I believe every project should be structured so that the following use cases are valid for any new developers coming onto a team, there's nothing more demoralising to new team members when you have to some kinda of voodoo to get a project to build;


As a developer I want to install the IDE So that I can compile source code.

As a developer I want to install the source control client So that I can extract code for compiling.

As a developer I want to compile the code So that I can verify the code compiles sucessfully.

As a developer I want to install a unit test framework So that I can execute unit tests for the code.

As a developer I want to execute the unit tests for the code So that I can verify the tests execute successfully.


Now this is not about being able to the run the application in a local debug build this about being able to confirm I'm standing on firm ground and I'm ready to start making changes to code base with confidence. (because the unit tests are all successful). For me one of the reasons for unit testing is to give team members & new starters the confidence to change code I've written without requiring my hand-holding.

There's nothing worse than being a new team member and not being productive ASAP.



Awkward Coder
Read More
Posted in Coding Building CI Testing | No comments

How to reduce url length in C#

Posted on 04:20 by Unknown
I needed the other day to reduce the length of a URL - so I decided to use a URL reducing service like tinyurl.com And I thought I would share the C# .Net code - nothing new I'm sure and there are plenty of examples out there.

public sealed class TinyUrlReducer : IReduceUrls
{
private readonly string _tinyUrl;
private readonly string _proxyUrl;

public TinyUrlReducer(string tinyUrl) : this(tinyUrl, null)
{
}

public TinyUrlReducer(string tinyUrl, string proxyUrl)
{
_tinyUrl = tinyUrl;
_proxyUrl = proxyUrl;
}

public string Reduce(string url)
{
if (string.IsNullOrEmpty(url))
throw new ArgumentException("Can reduce a null or empty url!", "url");

var reducedUrl = "";
try
{
Trace.WriteLine(string.Format("Reduce: Url - '{0}'.", url));

var requestUrl = string.Format("{0}?url={1}", _tinyUrl, url);
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.KeepAlive = false;
request.UseDefaultCredentials = true;
request.AllowAutoRedirect = true;
request.UseDefaultCredentials = true;

if (!string.IsNullOrEmpty(_proxyUrl))
request.Proxy = new WebProxy(_proxyUrl, true, null, CredentialCache.DefaultCredentials);

var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
throw new WebException(string.Format("Failed to call url - '{0}'!", requestUrl));

using (var stream = new StreamReader(response.GetResponseStream()))
{
reducedUrl = stream.ReadLine();
}

if (string.IsNullOrEmpty(reducedUrl))
throw new Exception("Reduced url is null or empty!");
}
catch (Exception exn)
{
Trace.WriteLine(string.Format("Reduce: Failed to reduce url, message - '{0}'.", exn.Message));
reducedUrl = url;
}
finally
{
Trace.WriteLine(string.Format("Reduce: Reduced Url - '{0}'.", reducedUrl));
}

return reducedUrl;
}
}

And a couple of tests...


[TestFixture]
public class TinyUrlReducerTests
{
[Test]
public void ShouldReduceUrl()
{
// Given we have url reducer...
var reducer = new TinyUrlReducer("http://tinyurl.com/api-create.php", "http://PROXY.MY.COM:8080");

// When we reduce a url..
var reducedUrl = reducer.Reduce("http://somereallylongurl/whichhasarelativelylongname/somepage.aspx");

// Then we expect the reduced url to start with...
Assert.IsTrue(reducedUrl.ToLower().StartsWith("http://tinyurl.com/"));
}

[Test, ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionIfUrlNull()
{
// Given we have url reducer...
var reducer = new TinyUrlReducer("http://tinyurl.com/api-create.php", "http://PROXY.MY.COM:8080");

// When we reduce a url..
var reducedUrl = reducer.Reduce(null);

// Then we expect the reduced url to start with...
Assert.IsTrue(reducedUrl.ToLower().StartsWith("http://tinyurl.com/"));
}

[Test, ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionIfUrlEmpty()
{
// Given we have url reducer...
var reducer = new TinyUrlReducer("http://tinyurl.com/api-create.php", "http://PROXY.MY.COM:8080");

// When we reduce a url..
var reducedUrl = reducer.Reduce(string.Empty);

// Then we expect the reduced url to start with...
Assert.IsTrue(reducedUrl.ToLower().StartsWith("http://tinyurl.com/"));
}

[Test]
public void ShouldReturnOrginalUrlWhenReducerFails()
{
// Given we have url reducer...
var reducer = new TinyUrlReducer("http://tinyurl.com/api-create.php");

// When we reduce a url and we know it will fail..
var url = "http://somereallylongurl/whichhasarelativelylongname/somepage.aspx";
var reducedUrl = reducer.Reduce(url);

// Then we expect the reduced url to the same as the original url...
Assert.AreEqual(url, reducedUrl);
}
}
Read More
Posted in Coding C# | No comments

Bad developers love 'The Daily WTF'

Posted on 03:47 by Unknown
When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a bit it became repetitive and boring and a sad indictment of the industry.

Now on my contracting travels around the industry the people who continue to love and read this site definitely fall into the 'bad developer' bracket on the whole, why? Simple because they subconsciously believe this is the way the industry is and always will be and they find it comforting to their bad practices.

Example: This guy tries to ridicule TDD and the ideas behind such practices without regard for his own ability - Oh look there on his blog list 'The Daily WTF'...

Whether this story is true or not it highlights some of the issues for me - the WTF is not the air conditioning guy causing the system outage but the IT department building such a fragile system with no resilience that takes 36 hours to bring back online - if it took me that long to bring a system up I would be ashamed.



Awkward Coder
Read More
Posted in Development Coding | No comments

Monday, 2 November 2009

When will it be finished...

Posted on 02:34 by Unknown
Developing software is synonymous to writing to a book, not because it's a creative task - which I do believe it is, but because when you write a book you go through many drafts before getting to the final released version. Just because the writer completes the first draft doesn't mean the publisher thinks it's ready for publication etc...

Software development is the same unless you (the developer) is prepared to think in an iterative approach you'll never be able to break free from classical development paradigms, you have to accept the first version is never going to be complete and you'll never reach the nirvana of finished, there always something that could be improved.

Oh and just like books code has a shelf life and it's never as long as you think or want it to be, and just because the software no longer fulfills what's required doesn't mean it's wrong, it just means the world has moved on...

An example is the talk Eric Evans gave at QCon earlier this year where he expressed what he learned about DDD since writing the book. Mark Needham has a write up here.


Awkward Coder
Read More
Posted in Development Process | No comments

Friday, 23 October 2009

Auditing user actions

Posted on 06:12 by Unknown
I want to be able audit user actions on the domain model - I want to track when & what they've changed. Now I can do this at the course grained level using nHibernate event listeners, they can tell me when an entity is loaded, saved, updated etc. But without interrogating the state of the entity in depth I'm unable to determine what's gone on between loading an entity and it being saved.

This is where the idea of domain events comes the rescue - the idea of generating events from the domain model. Now this could be done using the standard .Net event pattern, but as described in the above link the use of a decoupled domain events is way more powerful -the use of an intermediary ('DomainEvents' class) to decouple the domain model from the event handlers is simplistic and beautiful.

So now I can have an auditing service listening to both nHibernate & the domain model to track user actions across the domain and when a domain entity is persisted I can then push out the audit data to a message queue for processing asynchronously.

My requirement for auditing goes further than just tracking what a user did, it also includes tracking usage (of the domain model) - we want to track every time a user accesses content to provide usage reports and invoice accordingly...

This will be collected via the same domain events - it's just another specific audit handler, etc.


Simple!


Awkward Coder
Read More
Posted in DDD Domain Events Auditing nHibernate | No comments

Wednesday, 21 October 2009

Unstructured development opportunity

Posted on 10:07 by Unknown
Anyone spot the oxymoron in the snippet of a job spec I received today:

Ability to handle multiple competing priorities, work with minimal formal specifications, and deliver at the highest levels.

It then goes on to say:

Experience of designing, building and maintaining sophisticated automated trading applications with a large userbase and significant business dependency. Equity, future and option experience and working closely with business users.

There really must be some telepathic developers out there - no specification but expected to do some kind of BUF design..

I believe the people who run and develop in these type of teams have no experience of working in environments with any kind of formal structure and expect to spend most of their time & money on support & maintenance - but there again the opportunity is everything in the finance sector!

Also they will say they're doing 'Agile', note they don't do 'agile'.



Awkward Coder
Read More
Posted in Jobs Development | No comments

Monday, 19 October 2009

Property setters are just wrong!

Posted on 01:43 by Unknown
In general I think the use of property setters on classes is a sign of bad class design and a lack of OO principles - in most cases when you modify the 'state' of a class some 'behaviour' is invoked whether it be implicit or explicit;

e.g. when I change the address on a user account I want to make sure the address object has been populated (at least).

So these days I've started to design classes that have public getters & private setters, and if you want to modify state you are required to call a method, e.g. 'ChangeAddress'. This is nothing new, there are plenty of examples out there.

So in the example below 'Token' is property that's defined when the object is constructed and 'Path' is a property which is modified by calling the method 'ChangePath'.
    public class File : ObservableEntity<int>
{
private string _path;
private Guid _token;

private readonly IExtractFileProperties _propertiesExtractor = new FilePropertiesExtractor();


public File()
{
_token = Guid.NewGuid();
}


public virtual string Path
{
get { return _path; }
private set { ChangePropertyAndNotify(ref _path, value, x => Path); }
}

public virtual Guid Token
{
get { return _token; }
private set { ChangePropertyAndNotify(ref _token, value, x => Token); }
}


public File ChangePath(string path)
{
Path = path;

Size = _propertiesExtractor.Size(Path);
Format = _propertiesExtractor.Format(Path);
FileCreatedOn = _propertiesExtractor.CreatedOn(Path);
FileLastModified = _propertiesExtractor.LastModified(Path);

return this;
}
}


Now this attitude has been going well as it's made my classes more behaviour rich with better encapsulation & abstraction.

The only problem I've come across is when I'm trying to re-hydrate objects from the database where the properties I'm attempt to set have some kind of special behaviour - properties representing timestamps & versions that are historically set in the database via some function.

So in the following example I've got 3 properties - 'CreatedOn' 'LastModified' & 'Version'. I don't want to expose a method to set this values - I want them to be immutable...

But this is going to be a problem with an ORM, how am I going to update these values when saving or updating - I want them appear to be auto-updating from a users perspective.
    public abstract class ObservableEntity<T> : IEntity<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };

private T _id;

private DateTime? _createdOn;
private DateTime? _lastModified;
private int? _version;

public virtual T Id
{
get { return _id; }
private set { ChangePropertyAndNotify(ref _id, value, x => Id); }
}

public virtual DateTime? CreatedOn
{
get { return _createdOn; }
private set { ChangePropertyAndNotify(ref _createdOn, value, x => CreatedOn); }
}

public virtual DateTime? LastModified
{
get { return _lastModified; }
private set { ChangePropertyAndNotify(ref _lastModified, value, x => LastModified); }
}

public virtual int? Version
{
get { return _version; }
private set { ChangePropertyAndNotify(ref _version, value, x => Version); }
}

protected void ChangePropertyAndNotify<T2>(ref T2 value, T2 newValue, Expression<Func<object, T2>> expression)
{
value = newValue;
Notify(expression);
}

protected void Notify<T2>(Expression<Func<object, T2>> expression)
{
var propertyName = ((MemberExpression)expression.Body).Member.Name;
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

Now when using nHibernate as your ORM this becomes very easy because you can attach Listeners and do custom actions.

So I've got a custom action when NH saves or updates an entity to set these properties with the correct values.
public class EntitySaveOrUpdateEventListener : IPreInsertEventListener, IPreUpdateEventListener
{
public bool OnPreInsert(PreInsertEvent @event)
{
var hasType = (@event.Entity.GetType().GetInterface(typeof(IVersionable).Name, true) != null);
if (!hasType)
return false;

var now = DateTime.Now;
var createdOnIndex = new List<string>(@event.Persister.PropertyNames).FindIndex(x => x == "CreatedOn");
@event.State[createdOnIndex] = now;
SetPrivateVariable("CreatedOn", now, @event.Entity);

var lastModifiedIndex = new List<string>(@event.Persister.PropertyNames).FindIndex(x => x == "LastModified");
@event.State[lastModifiedIndex] = now;
SetPrivateVariable("LastModified", now, @event.Entity);

var versionIndex = new List<string>(@event.Persister.PropertyNames).FindIndex(x => x == "Version");
var version = GetPrivateVariable<int?>("Version", @event.Entity);

version = version.GetValueOrDefault() + 1;
@event.State[versionIndex] = version;
SetPrivateVariable("Version", version, @event.Entity);

return false;
}

public bool OnPreUpdate(PreUpdateEvent @event)
{
var hasType = (@event.Entity.GetType().GetInterface(typeof(IVersionable).Name, true) != null);
if (!hasType)
return false;

var now = DateTime.Now;
var lastModifiedIndex = new List<string>(@event.Persister.PropertyNames).FindIndex(x => x == "LastModified");
@event.State[lastModifiedIndex] = now;
SetPrivateVariable("LastModified", now, @event.Entity);

var versionIndex = new List<string>(@event.Persister.PropertyNames).FindIndex(x => x == "Version");
var version = GetPrivateVariable<int?>("Version", @event.Entity);

version = version.GetValueOrDefault() + 1;
@event.State[versionIndex] = version;
SetPrivateVariable("Version", version, @event.Entity);
return false;
}

public void SetPrivateVariable(string name, object value, object entity)
{
var entityType = entity.GetType();

var pi = entityType.GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
pi.ReflectedType.BaseType.InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance,
null,
entity,
new[] { value });
}

public T GetPrivateVariable<T>(string name, object entity)
{
var entityType = entity.GetType();

var pi = entityType.GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

return (T)pi.GetValue(entity, null);
}
}

Now if you follow this code, when an entity is saved for the first time then the 'CreatedOn' & 'LastModified' property values are set to the current date & time and the 'Version' property is incremented (the initial value is 0) via the private backing properties. When the entity is updated only the 'LastModified' & 'Version' properties are set via the private backing properties.

This event listener is then instantiated via the fluent NH config.
private static ISessionFactory CreateSessionFactoryImpl()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("Pronunciations")).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IMap>())
.ExposeConfiguration(c =>
{
c.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new EntitySaveOrUpdateEventListener() };
c.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new EntitySaveOrUpdateEventListener() };
})
.BuildSessionFactory();
}



Awkward Coder
Read More
Posted in nHibnerate Entities Events Listeners | No comments

Sunday, 11 October 2009

Lambda beats magic string

Posted on 09:16 by Unknown
Okay magic strings are a pain, in the worst cases they're bugs waiting to happen but I've been living with the following for while and it's always been nagging me when ever I look at the code.

public abstract class Observable<T> : IEntity<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };

private T _id;

public virtual T Id
{
get { return _id; }
private set { ChangePropertyAndNotify(ref _id, value, "Id"); }
}

protected void ChangePropertyAndNotify<T2>(ref T2 value, T2 newValue, string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

So after reading the MSDN article by Jeremy Miller and the example of using the Lambda expression in Fluent nHibernate mapping syntax I thought can we apply this to the above to remove the magic string "Id", and the answer is yes!

public abstract class Observable<T> : IEntity<T>, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };

private T _id;

public virtual T Id
{
get { return _id; }
private set { ChangePropertyAndNotify(ref _id, value, x => Id); }
}

protected void ChangePropertyAndNotify<T2>(ref T2 value, T2 newValue, Expression<Func<object, T2>> expression)
{
value = newValue;
var propertyName = ((MemberExpression)expression.Body).Member.Name;
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

The power of this is the Expression syntax and the ability at runtime to query and manipulate for other purposes other than what it was directly designed for.

Now is there a performance penalty for doing this?

Simple answer is I don't care until it becomes a problem, and to be honest I don't currently think it's going to be - avoid premature optimization at all costs, they're distractions from the requirement.


Awkward Coder
Read More
Posted in | No comments

Thursday, 8 October 2009

Using repositories inside a domain entity

Posted on 08:51 by Unknown
If you follow the principles of DDD you'll be well aware of the persistence ignorance discussion\argument. I believe domain entities should be agnostic of the persistence layer and therefore not statically bound at compile time. Overall I'm happy with this approach but it does give issues when trying to place certain business logic on the entity that requires access to some service (read repository).

Now obviously you can use the 'double-dispatch' approach and pass in the repository via an interface and only couple the entity to an interface, but to me this still seems a level of coupling that's unacceptable - usually we see these interfaces in an 'interfaces' project, to couple this to the domain model (entities) seems wrong.

So to get round this you can use functional programming, to be more specific you can use a lambda expression.

So imagine I have a Registration entity and it has responsibility for generating the user name from other data contained in the registration entity. Now to make sure the suggested user name hasn't already been allocated in the database the Registration entity needs to call the database to work this out.

So to avoid coupling the repository interface to the entity we pass in a Func<> into the method and call this to talk to the database, now from the entity perspective it's doesn't know what or how the func is defined it only know the parameters it has to provide and the result from the function - hence reduced coupling.


public sealed class Registration
{
public int? Id { get; private set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Registration(int? id)
{
Id = id;
}

public void GenerateUserName(Func<string, IList<Registration>> func)
{
var suggestedUserName = FirstName + "." + LastName;
var existingNames = func(suggestedUserName);

if (existingNames.Count != 0)
suggestedUserName += (existingNames.Count + 1);

Username = suggestedUserName;
}
}



Now the Func> takes a parameter and returns a list of Registration objects. And you can probably imagine the Func<> is a call to database looking for all matches of the suggested name.

So from the calling perspective the code now looks like this, with a single line to generate the suggested user name and check it against the database.

public sealed class AssetManagementService : IServiceAssetManagement
{
public AssetManagementService(IRepository<Registration, string> registrationRepository,
ICanValidate<RegistrationArgs> registrationValidator)
{
_registrationRepository = registrationRepository;
}

public void RegisterUser(Registration registration)
{
registration.GenerateUserName(x => _registrationRepository.FindBy(new FindByMatchingUsername(x)));

var result = _registrationValidator.Validate(new RegistrationArgs(registration));
if (!result.IsValid())
throw new ArgumentException(result.Message, "registration");

using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
_registrationRepository.Save(registration);

transaction.Complete();
}
}
}


Now from an OO perspective this is bad, violations of basic principles of Encapsulation & Abstraction, but and it's a big but it is an attempt to become more declarative and it's definitely using a Functional programming style which whether you like it or not will become a standard addition to any developer toolbox in the future. Personally I starting like the declarative nature and the clean code this produces.

Awkward Coder

Read More
Posted in | No comments

Wednesday, 7 October 2009

Functional intro

Posted on 02:37 by Unknown
Jeremy Miller has a great article in this months MSDN magazine introducing functional programming for the OO developer. If you've been using the features of .Net 3.5 - Func, Action, etc. you've probably been using these techniques & patterns without realising. I know I have.

It's a good read!

You might also be interested in Jon Skeet's new book release later this month.


Awkward Coder
Read More
Posted in Coding Functional-Programming | No comments

Tuesday, 29 September 2009

Mocks, Fakes, Stubs - why bother?

Posted on 03:44 by Unknown
Ever wondered why there are so many different names for the objects that mimic behaviour of the 'real' objects in a system - mocks, stubs, fakes, doubles...

I can't help looking at the tables of definitions on this page and think why bother!

Why have all these mocking frameworks gone and raised the bar of understanding for people who don't like TDD or who don't currently do TDD. To me everything is a mock if it's not the real thing - pure and simple. So when I write tests I call everything a 'Mock' so the tests are easy to read & understand by the anyone (including people adverse to TDD). Prehaps this is one of the reasons why I've stopped using mocking frameworks in general.

I'm sure some people think the distinction between a stub and mock is important but it isn't, the test is important not what & how you mock.



Awkward Coder
Read More
Posted in TDD Mocking | No comments

Monday, 28 September 2009

Distributed Systems are Coupled - Period!

Posted on 08:55 by Unknown
If you're doing distributed systems development your systems will be coupled together - period! You can't get away from this statement it's a fact of life. Now how much you're coupled is another question.

After the revelation I had last week that most REST systems aren't REST at all and are in fact just over-elaborated RPC (oh look we've reinvented CORBA again!) - link. I've come to the conclusion that REST systems aren't easy to implement and anyone who tells me otherwise doesn't know anything about distributed systems!

If REST systems were as easy people would make you believe why are so many not classed as REST by Dr. Fielding...


Awkward Coder
Read More
Posted in REST Distributed-Systems | No comments

Friday, 25 September 2009

Devlicio.us boys run out of duct tape!

Posted on 08:24 by Unknown
trying to reply to a blog about duct tape programmers and guess what ;)




Awkward Coder
Read More
Posted in Fun Coding Duct-Tape | No comments

Test Harnesses are counter productive...

Posted on 06:33 by Unknown
How often do you hear:

'Why do I need to write tests when I've got a perfectly good test harness?'

Now I hear this often and I'm not surprised anymore when I hear it, it's a sign of a dis-functional team where team members don't value the team they only value their output.

I've highlighted the words that give it away:

'Why do I need to write tests when I've got a perfectly good test harness...'

There is no 'I' in 'TEAM'!

Anyone who insists test harnesses are just as good as automated tests is plain wrong.

They're selfish developers who only care about the code they've written - and probably don't get involved with the team. The reason it's selfish is because they might well be able to test all edge cases with their test harness but how is anyone else meant to know how to achieve this. They can't unless they understand exactly how the test harness is constructed and to be used. It's more productive from a team point of view for everyone to write automated tests that are run automatically on checkin & build.

Now more than likely the people who refuse the accept TDD methods are either 'duct tapers' or 'old timers' who in general are past their sell by date anyway - if you can't accept knew ideas then you are definitely in the wrong industry.

At all the 'old timers' - do doctors still regularly recommend leaches?



Awkward Coder
Read More
Posted in TDD Team Observation | No comments

Wednesday, 23 September 2009

So you thinking you're doing TDD?

Posted on 02:37 by Unknown
I work freelance and like most freelancers I change job relatively frequently so therefore I do a lot of interviews. One thing I've noticed when being the interviewee is the amount companies lie!

One of the common technical lies I hear is 'We use TDD, all code is under test and we run automated builds...'

I use to take this at face value - being a trusting fellow and not wanting to judge someone to quickly ;)

So if I want to know how much truth is in the statement I could follow up by asking about mocking frameworks, BDD & Dan North etc...

But the killer question for me is to ask about their usage of an IoC container. Now IoC containers have nothing to do directly with TDD but If you're doing TDD you'll be using Dependency Injection and therefore you'll at least considered using one when you've realised your classes start to have to many constructor arguments.

So if they dismiss the usage of IoC without a good reason I know they aren't telling the truth about TDD - it's acceptable not to use IoC in an application you just have to be able to justify it, like every other decision one makes in development.



Awkward Coder...
Read More
Posted in TDD IoC DI | No comments

Monday, 21 September 2009

I know nothing moments...

Posted on 10:00 by Unknown
I was researching RESTful APIs today, it's couple of months since I worked on a RESTful project and I'm thinking of doing a small project with a RESTful API.

I discovered this link and found out that all my previous RESTful APIs aren't really RESTful ;)

So after discussing this on Yahoo groups I feel like I know nothing about REST now :(


Feeling stoopid now...


Awkward Coder
Read More
Posted in Coding REST Knowledge | No comments

Saturday, 19 September 2009

The secret all developers should know...

Posted on 09:08 by Unknown
Dave Laribee gives away the secret ingredient!

http://codebetter.com/blogs/david_laribee/archive/2009/09/08/the-secret-sauce.aspx


nuff said...

Awkward Coder
Read More
Posted in Agile | No comments

Friday, 18 September 2009

How to test a static dependency used inside a class...

Posted on 06:28 by Unknown
This is a question that keeps coming up and I know if you're practicing it's a no brainer but I keep getting asked this by devs (I'm no testing God!).

The long answer is to read this book and pay attention when talking about 'inserting a seam'.

The short answer is carry on reading...

Now several people (read Jimmy Bogard) have already answered this but here is my take on this looking at my current client, they have a lots of deeply nested static dependencies - these are implicit dependencies and what you really want to is explicit dependencies because they are easily testable.

So I see a lot of classes like this nested deeply in some object graphs.

 public class Foo
{
private string _url;
private string _connectionString;

private string _user;

public Foo()
{
_url = System.Configuration.ConfigurationManager.AppSettings["SomeUrl"];
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString;

_user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}

public void Bar()
{
// Do something...
}
}
So this has 2 static dependencies that are hidden and hard to test...

How do I make this easier to test and remove the hidden dependency?

The answer is I insert a seam for each static dependency - this involves pushing the static dependency behind an interface and expose the properties & methods

So instead of using the ConfigurationManager and WindowsIdentity directly in the code we use an interface that's injected via the constructor.

 public class Foo
{
private readonly IProvideConfiguration _configuration;
private readonly IProvideUserInfo _userInfo;

public Foo(IProvideConfiguration configuration, IProvideUserInfo userInfo)
{
_configuration = configuration;
_userInfo = userInfo;
}

public void Bar()
{
// Do something...
var user = _userInfo.UserName;

var url = _configuration.Url;
var connectionString = _configuration.ConnectionString;
}
}

public interface IProvideUserInfo
{
string UserName { get; }
}

public interface IProvideConfiguration
{
string Url { get; }
string ConnectionString { get; }
}


Now because I've created two seams - IProvideUserInfo & IProvideConfiguration these can easily be mocked out and testing becomes a lot easier!

So the implementation of these interface would probably look like this:

public class ApplicationConfiguration : IProvideConfiguration
{
public string Url
{
get { return System.Configuration.ConfigurationManager.AppSettings["SomeUrl"]; }
}

public string ConnectionString
{
get { return System.Configuration.ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString; }
}
}

public class WindowsIdentity : IProvideUserInfo
{
public string UserName
{
get { return System.Security.Principal.WindowsIdentity.GetCurrent().Name; }
}
}

So hopefully some people will find this helpful....

Awkward Coder

Read More
Posted in Coding TDD Refactoring Agile | No comments

Thursday, 17 September 2009

Application auditing - an example why I don't work at the weekend...

Posted on 07:20 by Unknown
Ever had a situation where you're OLTP requirements are impeded by your OLAP implementation, well to put it another way - have you ever come across an auditing solution that causes transactions to timeout when you're trying to save data into your production database.

Well the answer for me is far to often for my liking and this is an example of 'synchronous auditing' and I believe this is an anti-pattern in the making. I'm firmly in the camp that believes auditing should be done asynchronously by a different (application) process. The reasons why I think it's an anti-pattern is because, if how you audit affects the performance of your production database then your performance is going to degrade overtime, and if you insert 500,000 audit records a day that's going to occur relatively quickly. Now DBAs would say lets put a maintenance plan in place to clear down\manage the audit database, or even remove the synchronous auditing and perform a batch load once a week out of normal days operation - AT THE WEEKEND OR AFTER HOURS...

I'm not going to support a such a process or help out when such a process fails to bring the production system back online because the batch load failed - MY WEEKENDS ARE FOR ME...

I design auditing systems that allow production-time maintenance of OLAP databases with no affect to OLTP databases and this is achieved by asynchronous auditing via transactional message queues.

You design your application such that when you need to create an audit record for a user\system action you write this to a message queue transactionally as part of the behaviour (business requirement). There is then another independent process monitoring & processing the audit records (in the message queue) into the OLAP database, it's important this process can be controllable so that it can be disabled when ever the OLAP database requires maintenance, i.e. DURING WORK HOURS NOT AT THE WEEKEND. Whilst the process is disabled the audit records will just accumulate on the message queue and as long as disk space is available you won't loose anything - (RAIDing etc).

Auditing user\system actions is always business requirement - we don't track what user\system do for our benefit so why do it as an after thought...

Oh and you can probably guess I hate triggers on tables too ;)



Awkward Coder
Read More
Posted in Design Patterns Databases Auditing | No comments

Repository pattern - my preferred implementation...

Posted on 05:29 by Unknown
Okay it's nothing new and not even original but I wouldn't to get down my currently preferred implementation of the repository pattern. I suppose this was prompted by a blog by Jimmy Bogard and Oren's statement a couple of months ago the repository pattern may be near then end of it's life.

I still think in the .Net world they have great relevance as most .Net devs can't organise code for toffee and when you try and introduce layering into an application the use of an explicit repository layer is the first layer they seem to understand.

So here is my current repository flavour - strawberry with a twist of lemon...


 public sealed class Repository<T1, T2> : IRepository<T1, T2> where T1 : IEntity<T2>
{
private readonly ISession _session;
private readonly string _traceType;

public Repository(IProvideSessions sessionFactory)
{
_traceType = string.Format("Repository<{0}, {1}>: ", typeof(T1).Name, typeof(T2).Name);
_session = sessionFactory.GetSession();
}

public T1 Get(T2 id)
{
Trace.WriteLine(string.Format("{0} Get - '{1}'.", _traceType, id));
return _session.Get<T1>(id);
}

public void Save(T1 instance)
{
Trace.WriteLine(string.Format("{0} Save - '{1}'.", _traceType, instance.Id));
_session.Save(instance);
}

public void Delete(T1 instance)
{
Trace.WriteLine(string.Format("{0} Delete - '{1}'.", _traceType, instance.Id));
_session.Delete(instance);
}

public T1 FindOne(IFindable findable)
{
Trace.WriteLine(string.Format("{0} FindOne, - '{1}'.", _traceType, findable.GetType().Name));
var criteria = findable.BuildCriteria();
return criteria.UniqueResult<T1>();
}

public IList<T1> FindAll(IFindable findable)
{
Trace.WriteLine(string.Format("{0} FindAll, - '{1}'.", _traceType, findable.GetType().Name));
var criteria = findable.BuildCriteria();
return criteria.List<T1>();
}
}

One of the first things to notice is the use of two generic types T1 & T2 - I'm not great at naming generic parameters so they never got better names. Hopefully it's obvious but T1 is the domain entity and T2 represents the 'Id' column for the entity (All DDD entities have Id's).

The other important feature is the 'FindOne' & 'FindAll' methods they take an implementation of the interface IFindable which performs the magic. Now this is where the generic repository starts to have a 'leaky abstraction' and this happens to be exposing nHibernate's ICriteria interface vai the IFindable interface. The implementation of the IFindable is responible for the creation of the NH criteria and returns this when requested, this is then executed by the repository and volia the results are returned.

So my current repository pattern is designed to be used with NH, but if a client dictates I can't use NH then I will modify the IFindable interface accordingly or I will terminate the contract depending on how I'm feeling :)

 public interface IFindable    {        ICriteria BuildCriteria();    }


An example of this could the a Findable class that returns an NH criteria that will return bank customers with a balance greater than million - Millionaires!



public sealed class FindValuedCustomers : IFindable
{
private readonly ISession _session;

public FindValuedCustomers(IProvideSessions sessionFactory)
{
_session = sessionFactory.GetSession();
}

public ICriteria BuildCriteria()
{
return _session.CreateCriteria(typeof(Account)).Add(Property.ForName("CurrentBalance").Gt(1000000));
}
}


Now I can see how Oren goes from this to the idea of just using NH Session anywhere in the code you previously used a Repository but I do think there is still some requirement to provide a layer & abstraction for testing purposes.

One other thing to note, I do believe the Repository pattern has valid uses outside of DDD, as Eric has stated most of the common patterns in DDD existed before the book.



Awkward Coder
Read More
Posted in nHbiernate Repository Pattern Criteria | No comments

Auditing with nHibernate...

Posted on 02:02 by Unknown
Long time since I've posted anything but I came across an interesting problem the other day whilst I was working - 'How can I audit changes to specific entities when using nHibernate?'

There are several implementation out there already (see Oren's & others posts) but of ones I've seen they are to low level for my liking - they push the auditing of changes into the NH infrastructure away from the Service implementing the business behaviour. I want my service to control and define what is audited I don't want everything audited in the same manner. Auditing for me is the pushing out of events that have affected entities persisted in an OLTP database to OLAP database ideally in an asynchronous manner via some queuing mechanism (MSMQ).

So how do you get events from NH?

Now if you want to observe changes to entities in NH you have to register you're interest by passing an implementation of an IXXXListener interface to the NH configuration when create the SessionFactory, this is the classic implementation of the observer pattern and I guess it's like this because this is a straight port from java - it doesn't follow the .Net approach of EventHandlers & Events, I'm liking this approach as it gives exposure to a different implementation.

What did interest me about this implementation was that as user of the NH Session I can't register with the Session my interest in observing changes to the entities. I have to do this with the SessionFactory and therefore I'm getting notified of ALL events to ALL entities whilst this SessionFactory is alive.

So you can register your interest by implementing a class and passing this to the NH configuration - I've tried to keep it simple by register for events that tell me when CRUD operations have been completed on entities, this is done by implementing the following NH interfaces:

IPostInsertEventListener,
IPostLoadEventListener,
IPostUpdateEventListener,
IPostDeleteEventListener.
I also created an interface called IObserveNHibernate that fires traditional .Net style events when an NH event has been observed.

I've left out all the XXXEventArgs classes from the post for brevity - I hope you can figure out the structure!

public interface IObserveSession<T> : IDisposable where T : IEntity
{
event EventHandler<SessionEventArgs<T>> EntityLoaded;
event EventHandler<SessionEventArgs<T>> EntityCreated;
event EventHandler<SessionEventArgs<T>> EntityUpdated;
event EventHandler<SessionEventArgs<T>> EntityDeleted;
}
So the class looks like:

public sealed class NHibernateObserver : IObserveNHibernate,
IPostInsertEventListener,
IPostLoadEventListener,
IPostUpdateEventListener,
IPostDeleteEventListener
{
public event EventHandler&lt;NHibernateEventArgs&gt; EntityLoaded = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityCreated = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityUpdated = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityDeleted = delegate { };

public void OnPostDelete(PostDeleteEvent @event)
{
EntityDeleted(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostInsert(PostInsertEvent @event)
{
EntityCreated(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostLoad(PostLoadEvent @event)
{
EntityLoaded(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostUpdate(PostUpdateEvent @event)
{
EntityUpdated(this, new NHibernateEventArgs(@event.Entity));
}
}

And this class is then used when creating the SessionFactory for NH. Now currently I wrap the creation of the NH SessionFactory into a custom SessionFactory - this class usually exists as a singleton in the host process and lifetime is managed by the IoC container (it's marked as a singleton).

This SessionFactory is backed by an interface, that defines 2 methods - one for access to the Session & the other for accessing an implementation of SessionObserver<T> exposed as an IObserveSession<T> interface, where the generic T represents the entity type I'm interested in observing.

So the interface looks like:

public interface IObserveSession&lt;T&gt; : IDisposable where T : IEntity
{
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityLoaded;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityCreated;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityUpdated;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityDeleted;
}

The interface implements the Dispose pattern so the un-hooking of events automatically happens when you've finished observing NH events. The implementation of the interface is show below:

public sealed class SessionObserver&lt;T&gt; : IObserveSession&lt;T&gt; where T : IEntity
{
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityLoaded = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityCreated = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityUpdated = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityDeleted = delegate {};

private IObserveNHibernate _observer;

public SessionObserver(IObserveNHibernate observer)
{
_observer = observer;
_observer.EntityLoaded += (HandleEntityLoaded);
_observer.EntityCreated += (HandleEntityCreated);
_observer.EntityUpdated += (HandleEntityUpdated);
_observer.EntityDeleted += (HandleEntityDeleted);
}

public void Dispose()
{
_observer.EntityLoaded -= HandleEntityLoaded;
_observer.EntityCreated -= HandleEntityCreated;
_observer.EntityUpdated -= HandleEntityUpdated;
_observer.EntityDeleted -= HandleEntityDeleted;

_observer = null;
EntityCreated = null;
EntityUpdated = null;
EntityDeleted = null;
}

private void HandleEntityDeleted(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityDeleted(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityUpdated(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityUpdated(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityCreated(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityCreated(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityLoaded(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityLoaded(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
}

So I have a custom SessionFactory that looks something like the following - pretty standard NH Session semantics and the new method SessionObserverT - this creates an instance of the SessionObserver<T> per request.

SessionFactory interface:

public interface IProvideSessions
{
ISession GetSession();
IObserveSession<T> SessionObserver<T>() where T : IEntity;
}
SessionFactory class:

public sealed class SessionFactory : IProvideSessions
{
private readonly ISessionFactory _sessionFactory;
private readonly NHibernateObserver _nHibernateObserver;

public SessionFactory(string connectionString)
{
_nHibernateObserver = new NHibernateObserver();

var cfg = new Configuration();
cfg.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] { _nHibernateObserver };

_sessionFactory = Fluently.Configure().ExposeConfiguration(c => cfg.Configure())
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IEntity>())
.BuildSessionFactory();
}

public ISession GetSession()
{
return _sessionFactory.GetCurrentSession() ?? _sessionFactory.OpenSession();
}

public IObserveSession<T> SessionObserver<T>() where T : IEntity
{
return new SessionObserver<T>(_nHibernateObserver);
}
}
So an example of how I would use this is show below, it's a little contrived and not tested but I hope you get the idea:

public class CashService
{
private readonly SessionFactory _sessionFactory = new SessionFactory("SOME CONNECTION STRING");

public void Debit(string accountNumber, decimal amount)
{
using(var session = _sessionFactory.GetSession())
using(var trans = session.BeginTransaction())
using(var sessionObserver = _sessionFactory.SessionObserver<Transaction>())
{
sessionObserver.EntityCreated += ((sender, args) => AuditTransaction(args));

var account = session.Get<Account>(accountNumber);

session.Save(new Transaction(account, amount));

trans.Commit();
}
}

private void AuditTransaction(SessionEventArgs<Transaction> args)
{
// Write transaction event to audit queue...
// if fails the throw exception...
}
}

Now I've not tested this fully and I'm not sure of the viablity of this option or whether I like the end usage - I suppose I could wrap the NH Session behind a custom Session class that exposes the events directly. But it's a start at thinking how I'm going to achieve the auditing required.


Wow that was longer thanexpected ;)

Anyway till next time...


Awkward
Read More
Posted in nHibernate Auditing Design Fluent | No comments

Thursday, 2 April 2009

Maybe courage is the key...

Posted on 04:37 by Unknown
I went to an all day planning session yesterday for the next set of sprints for a client, they're doing 3 sprints for the next release with each sprint being 2 weeks long. I was there to provide architecture advice on the implementing the functionality using their newly adopted MVC(P) pattern and layered architecture.

I sat in on several sessions for one team and they where going great guns at producing a development backlog. By the end of the session they had a good break down of the technical tasks required for the sprints, this included estimations of the time required for the tasks and the total estimated time fitted well with the total time available per sprint.
At the end of the day the team then presented there proposed sprints to the whole development team. When one of the other teams was presenting it became apparent they had fallen back into the safe & familiar waterfall approach. The glaring evidence for this was an ad-hoc Gantt chart stuck to the wall!

It became obvious they'd taken their backlog and not only assigned tasks to specific developers ahead of time but had also assigned an order for implementation with hard dates & times for all tasks. This instantly made the sprint structure fixed and brittle - it would be unable to deal with changing requirements and feedback from the customer, they didn't have there Agile thinking hats on! They were seeing dependencies in the order of the tasks where they didn't need to - you know like 'you can't build that before this because...'. These type of dependencies are broken by building software in a more Agile manner because principles like dependency injection, mocking and BDD (I'm starting to think BDD really ROCKS!) allow you to develop systems without have all your dependencies implemented before you start.

Now there are plenty of blog entries out there about why Gantt charts don't feature frequently if at all on Agile projects. I was more interested in why it appeared and I started to think about this, it then became apparent the person who produced the Gantt chart didn't have the COURAGE not too! They didn't have the courage to say 'I don't know how this fits into the time scale for project' you can probably tell this came from a senior person on team - one of the guys managing the team. This intern made me realise they didn't have the courage to trust their team to deliver and this is a symptom that they didn't trust the agile process. Plus I get the feeling they're still thinking in a chronological approach to delivery when they should be thinking in a feature based approach.

So for me at the moment the most important Agile principle is courage - not only the courage for a team to communicate back to a product owner problems or the ability of team members to be honest about their technical knowledge, but the ability of the management layer to communicate their worries and concerns without resorting to waterfall methods of reassurance.
Read More
Posted in Agile Courage | No comments

Monday, 30 March 2009

Applying context to a model...

Posted on 06:32 by Unknown
I didn't attend QCon earlier this month, but I followed several attendees blogs and co-workers responses to the Eric Evans opening presentation. Alot of people mentioned the fact that Evans wished he'd dealed with 'Bounded Contexts' earlier in the book.

I'm now getting this feeling very much on my current assignment - over the last week we've had a great realisation that the application is a chameleon or if I'm feeling less generous a 'wolf in sheep's clothing...'

The minute you realise you've multiple different user types using your application you definitely have different 'Bounded Context's'- you could have users who care greatly how 'Orders' are modelled and the behaviour contained within, but you can also have other users who care nothing for how 'Orders' are modelled per say - typically I'm thinking of users who focus on reports etc.

This is not to say even if you have a single user you shouldn't give your model context within a certain area, I think a rule of thumb on this front is - if it's getting to difficult to add behaviour to the model may be it's time to break to the model apart into separate contexts. And remember it's not a bad thing to duplicate entities in different context's because more than likely they're not offering the same behaviour...

Do I think you can share entities between context's - 'Shared Kernel' springs to mind...
Read More
Posted in Bounded Context, DDD | No comments

Sunday, 29 March 2009

IT - a fall back opportunity...

Posted on 07:15 by Unknown
I don't mean to demean teachers & teaching but 'IT' has become what teaching had become to any university graduate before 1995 - a fall back opportunity in case you couldn't think of anything more interesting to do with your life. I remember quite a few graduates of the early 1990's who did teacher training just because they couldn't be bother to work out what they wanted to do with their lives, not exactly an encouraging state of affairs for the education system. It was only a fictitious TV show but Teachers hit the mark for me.


And now we're reaping the reward of this thinking in the computer industry, notice I don't say IT, I hate the expression 'IT', when ever I hear someone say I work in 'IT' - it tells me 'I couldn't be bother to work out what I wanted so I chased the easy money...'.
I'm not saying you have to have a PhD in 'pixel fibrillation and the effects on digital e-commerce' to work in this industry you just got have a passion for doing the job, some of the most passionate people I know don't have any qualifications.


The industry is now made up of too many people who don't care about the projects they work on, they only care about bonuses and the latest 'corporate handcuffs'. In the development community these are typified by people who either become managers because they didn't like writing code or developers who expect the company to provide training in technology. These people are the 'bad apples' in any development project they don't want to learn and they don't understand how developers think, they just don't get the statement 'the devils in the detail'. Ultimately these people are why methodologies like Agile & SCRUM will fail to deliver the benefits to the majority of software projects because these methodologies require people to take responsibility for their actions and do the job to the best of their abilities and these people definitely don't.


What's the out come of this?


Simple - The clever people are thinking of leaving...


I'm not one of those clever people (yet!), I care greatly about my time at work and the code I produce. And if this code is not up to the job it causes me great anguish when I've failed to deliver what's required. A good example was last week when we were having an OO analysis & design session and I produced a design that was sub-optimal compared to the final solution. This caused me some mental discomfort for the next 2 days. The outcome of which was I realised I need to improve my analytically skills when it comes requirements and use cases. I often discount stuff to early when analysing what's required. I meet to many developers\managers who don't think this way, to be blunt they don't care they didn't produce a solution the end user wanted. This attitude for me is why so many of the good people want to leave the industry.
Read More
Posted in Observations, Rants | No comments

Thursday, 19 March 2009

No one owns the Domain Model...

Posted on 13:42 by Unknown
May be I should be more precise, and say 'No one developer owns the Domain Model...'. We all share the 'code ownership' and no one coder is responsible for the state of the domain model. Now you're probably thinking I'm going to elaborate on the fact the team I'm currently working with don't take code ownership seriously - they don't - but I'm not going to mention that. I'm talking about when you're a tech lead\coach you don't have 'first dibs' on the structure of the model and how it's implemented. To be honest in a DDD environment we don't have control over the structure of the domain model, the business do!

So this week I realised I was living up to my pseudonym, I've been being awkward about other coders adding to the domain model, I've been worrying about what they're going to add or change. Now this is just my hang-up and I realised, how are they going to improve at modelling & design if they aren't allowed to fail. Just because other developers & management recognise you're the best coder they've got doesn't give you the right to stamp the domain model as yours.

To put it another, way by acting as the only person who can change the domain model you're creating a single point of failure and you're lowering the standards required by your team. Now this is an anti-pattern in the making and has no place on in an emerging Agile environment.









Read More
Posted in DDD Coaching | No comments

Sunday, 8 March 2009

ReadOnlyCollection<T> meets BindingList<T>...

Posted on 06:26 by Unknown
Okay my first post and I was going to jump right in and try a fill a gap in the blogging worlds knowledge about having a read only collection that supports notifications of modifications to collection members when programming in .Net - what happens when ReadOnlyCollection<T> meets BindingList<T>? 

The simple answer to that question is ReadOnlyObservableCollection<T> in version 3.0 or higher - it provides the exactly functionality I require and gets away from the awful 'Binding' prefix name which has to much association with 'Data Binding' in the MS world. But in version 2.0 you don't have a such a luxury :).

This is really the sub-text of this post and the problem I'm trying to solve - How can I observe events on a domain entities (including collections) when implementing Domain Driven Design in a winforms environment that utilises an MVC(P) pattern?

If you don't know much about Domain Drive Design check the out website and for a great set of posts on see Casey Charlton's blog and accompanying DDD website.

Back to the question, By implementing the interfaces INotifyCollectionChanged and INotifyPropertyChanged we allow the domain entities and value objects to notify anyone who is interested when their state changes. So if we have our entities deriving off a base class that implements INotifyPropertyChanged and a property changs we fire the event PropertyChanged and anyone observing gets notified.

A simple base class that implments INotifyPropertyChanged:

    public abstract class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected void NotifyPropertyChangedObservers(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

And a domain entity that derives from this, finding a quick and easy domain to model is tricky :)

    public sealed class Person : Observable
    {
        private string firstName;
        private string lastName;

        public Person(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public string FirstName
        {
            get { return firstName; }
            set { SetProperty(ref firstName, value, "FirstName"); }
        }

        public string LastName
        {
            get { return lastName; }
            set { SetProperty(ref lastName, value, "LastName"); }
        }

        private void SetProperty(ref T existingValue, T newValue, string propertyName)
        {
            if (!Object.Equals(newValue, existingValue))
            {
                existingValue = newValue;
                NotifyPropertyChangedObservers(propertyName);
            }
        }
    }

So this mechanism work great, I'm now able to observe any changes to any value type properties on the domain entities - this is really useful in a our Model View Controller Presenter pattern, we can now bind our Model to the View and the View now gets automatically notified of changes to the Model and knows how to handle updating the UI. It should be said we don't couple the Model directly to the View we use a Presenter hence the MVC(P), the Presenter creates a Presentation wrapper around the Model that is bound to the View.

But what about when the properties start to represent more complicated such as collections?

Lets tackle the .Net 3.0 version first- Simple we use the ReadOnlyObservableCollection<T> and we now have the advantage of observing any changes to the entities inside the collection but we don't let anyone change the contents of the collection - you wouldn't want anyone to come along and just add more children to your family without your say so would you :)

    public sealed class Family : Observable
    {
        private Person firstParent;
        private Person secondParent;

        private ObservableCollection children;

        public Family(Person firstParent, Person secondParent, IList children)
        {
            this.firstParent = firstParent;
            this.secondParent = secondParent;

            this.children = new ObservableCollection();
            foreach (Person child in children)
                this.children.Add(child);
        }

        public Person FirstParent
        {
            get { return firstParent; }            
        }

        public Person SecondParent
        {
            get { return secondParent; }            
        }

        public ReadOnlyObservableCollection Children
        {
            get { return new ReadOnlyObservableCollection(children); }
        }

        private void SetProperty(ref T existingValue, T newValue, string propertyName)
        {
            if (!Object.Equals(newValue, existingValue))
            {
                existingValue = newValue;
                NotifyPropertyChangedObservers(propertyName);
            }
        }
    }

Now to do this in .Net 2.0 becomes a bit of an issue we don't have the luxury of ObservableCollection or ReadonlyObservableCollection we have to role our own implementation that some how combines the functionality of ReadOnlyCollection and BindingList. My first attempt was to derive from BindingList and override any method that modifies the list

    public sealed class ReadOnlyBindingList : BindingList
    {
      ...
    }

But I discovered an important thing I wasn't able to override methods like 'Add', 'Remove' I had to use the 'new' operator which set alarm bells off - this is a code smell if ever I've seen one. This was confirmed when talking to another dev who pointed out this would break Liskov's Subsitution Princple if I were to replace an use of my ReadOnlyBindingList with a normal BindingList. So that attempt fails before getting of the launch pad...

So the answer is to use containment of the BindingList collection and implement the IBindingList interface...

    public sealed class ReadOnlyObservableCollection<T> : IBindingList<T> where T : class
    {
        public event ListChangedEventHandler ListChanged = delegate { };

        private BindingList<T> innerList;

        public ReadOnlyObservableCollection(IList list)
        {
            innerList = new BindingList<T>();
            foreach (T item in list)
                innerList.Add(item);

            innerList.ListChanged += HandleListChanged;
        }

        void IBindingList.AddIndex(PropertyDescriptor property)
        {  
            ((IBindingList)innerList).AddIndex(property);
        }

        public object AddNew()
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool AllowEdit
        {
            get { return true; }
        }

        public bool AllowNew
        {
            get { return false; }
        }

        public bool AllowRemove
        {
            get { return false; }
        }

        void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
        {
            ((IBindingList)innerList).ApplySort(property, direction);
        }

        int IBindingList.Find(PropertyDescriptor property, object key)
        {
            return ((IBindingList)innerList).Find(property, key);
        }

        bool IBindingList.IsSorted
        {
            get { return ((IBindingList)innerList).IsSorted; }
        }

        void IBindingList.RemoveIndex(PropertyDescriptor property)
        {
            ((IBindingList)innerList).RemoveIndex(property);
        }

        public void RemoveSort()
        {
            ((IBindingList)innerList).RemoveSort();
        }

        ListSortDirection IBindingList.SortDirection
        {
            get { return ((IBindingList)innerList).SortDirection; }
        }

        PropertyDescriptor IBindingList.SortProperty
        {
            get { return ((IBindingList)innerList).SortProperty; }
        }

        bool IBindingList.SupportsChangeNotification
        {
            get { return ((IBindingList)innerList).SupportsChangeNotification; }
        }

        bool IBindingList.SupportsSearching
        {
            get { return ((IBindingList)innerList).SupportsSearching; }
        }

        bool IBindingList.SupportsSorting
        {
            get { return ((IBindingList)innerList).SupportsSorting; }
        }

        public int Add(object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool Contains(object value)
        {
            return innerList.Contains(value as T);
        }

        public int IndexOf(object value)
        {
            return innerList.IndexOf(value as T); 
        }

        public void Insert(int index, object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool IsFixedSize
        {
            get { return true; }
        }

        public void Remove(object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public object this[int index]
        {
            get { return innerList[index]; }
            set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
        }

        public T this[int index]
        {
            get { return (T)innerList[index]; }
            set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
        }

        public void CopyTo(Array array, int index)
        {
            innerList.CopyTo((T[])array, index);
        }

        bool ICollection.IsSynchronized
        {
            get { return ((ICollection)innerList).IsSynchronized; }
        }

        object ICollection.SyncRoot
        {
            get { return ((ICollection)innerList).SyncRoot; }
        }

        public bool RaisesItemChangedEvents
        {
            get { return true; }
        }

        public void Clear()
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        public int Count
        {
            get { return innerList.Count; }
        }

        public System.Collections.IEnumerator GetEnumerator()
        {
            return innerList.GetEnumerator();
        }

        private void HandleListChanged(object sender, ListChangedEventArgs args)
        {
            NotifyListChangedObservers(args);
        }

        private void NotifyListChangedObservers(ListChangedEventArgs args)
        {
            ListChanged(this, args);
        }
    }

So to implement a ReadOnlyObserableCollection collection in .Net 2.0 can be done relatively easily, but it's a no brainer if you're using a newer version of the framework :)

There is one issue relating to providing observable entities in the domain, am I coupling the presentation functionality into the domain entities by doing this?

I don't think this is as black and white as using repositories from domain entities - I don't believe you should use repositories in domain entities. The reason I believe this is because by providing observable entities in the domain doesn't mean they will be used by the presentation nor am I doing this to support any presentation pattern.

Read More
Posted in DDD, ReadOnlyCollections | No comments
Newer Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ▼  2009 (32)
    • ▼  December (3)
      • Script free MSDN
      • Schrödinger's Service
      • Can I make a value object from an entity?
    • ►  November (7)
      • Continents move faster than the software industry!
      • Removing friction from the process
      • build for test != build for release
      • When I'm a new team member
      • How to reduce url length in C#
      • Bad developers love 'The Daily WTF'
      • When will it be finished...
    • ►  October (6)
      • Auditing user actions
      • Unstructured development opportunity
      • Property setters are just wrong!
      • Lambda beats magic string
      • Using repositories inside a domain entity
      • Functional intro
    • ►  September (11)
      • Mocks, Fakes, Stubs - why bother?
      • Distributed Systems are Coupled - Period!
      • Devlicio.us boys run out of duct tape!
      • Test Harnesses are counter productive...
      • So you thinking you're doing TDD?
      • I know nothing moments...
      • The secret all developers should know...
      • How to test a static dependency used inside a clas...
      • Application auditing - an example why I don't work...
      • Repository pattern - my preferred implementation...
      • Auditing with nHibernate...
    • ►  April (1)
      • Maybe courage is the key...
    • ►  March (4)
      • Applying context to a model...
      • IT - a fall back opportunity...
      • No one owns the Domain Model...
      • ReadOnlyCollection<T> meets BindingList<T>...
Powered by Blogger.

About Me

Unknown
View my complete profile