Tuesday, December 25, 2007

Post sharp

It looks like you can hold a reference to the method you are entering and exiting by using the MethodExecutionTag.
You can assign what you want to it as it is just an object and is bound to the eventArgs of the enter and exit events.
Sweet.
This means you could also make every single method a transaction if you wanted to (if you were Juval Lowy/mad man), or mark entry and exit of a specific instance call of a method using a GUID as colleague had mentioned would be nice for logging.
As this is weaved in to the IL its should have not have any more a negative performance impact on calling the method, over over putting the code in to the method to do exactly the same. You do however have a whole load more flexibility to pull out and put in what you want and where (ie certain assemblies, classes or methods).
I am loving PostSharp :)

Monday, December 24, 2007

DBC within the C# language - Spec#

Spec# or SpecSharp
I have been hoping for something like this for quite awhile. I am hoping this will be something that will aid in compile time assistance for Design By Contract programming.
I have been looking into third party apps and even building my own libraries, however what i really wanted was compile time errors as opposed to run time errors, which although Test would usually find, don't really help other developers as they leverage of my code.
Currently i have comments and run time checks however this still does not force consumers of my method to adhere to the contract, it only throw run time exceptions when they break the contract. the benefit here is they fail fats and they get a more meaningful exception message as to WHY the parameters are not valid. But it often also means that i have code the looks like:

public class Foo: IFoo
{
public void Bar(object param1)
{
Check.IsNotnull(param1, "Foo.Bar: param1 can not be null");
if(param1 != null) //***this line is effectively redundant
{
//do something with param1...
}
}
}

The null check is still in place to prevent FXCop errors arising by not checking for the objects state before using it.
I really hope the Spec# C# additions will aid in this.

Tuesday, December 18, 2007

When is a bug not a bug?

I am sure the Tester at the place I currently work at secretly hates me. He is far too nice and far too professional to ever say... but i am sure of it.
He is in a position where he knows what the application we are building should do and how it should do it. Unfortunately this is only ever communicated to me after I have built the module. He doesnt write the use case so dosen't get a chance to prewarn me.
These changes are raised as bugs (as we only have the concept of bug, no concept of a change request) and so it looks like my code sucks as i have a couple of dozen bugs logged against my name (which is standard across the team). I dont like the idea of my code sucking. While looking through the buglist today, after reading the first 12 and realising that they were either A) Not bugs, but changes or B) not my bugs to fix; I got a little stroppy.
*begin blowing trumpet*
Now, when I get a use case I assume that this is what is required... I know, what an idiot... so I write my unit tests and do the whole Red, Green, Refactor like a good TDD agile boy,
*end blowing trumpet*
however I forget that we only call ourselves agile we are in fact... dreamers.
Huge numbers of tests fail and are left unattended, iteration after iteration... our scope is non existent.. our use case are guesses at what we kinda, maybe want and are completely ok to change at any time with the expectation to deliver on time still intact.
So I have tried to push back.
-A bug is raised
> If in use case ==> FIX NOW!
>Else ==>can be done in next iteration and is logged as "Not in spec/Functional change".

I thought this may rustle some feathers and hopefully means the uses case would be a little more robust. It also means the actual bugs got higher priority, as I think they should.
No...
Now we just do non-functional iterations where we do "bug fixes" on all the functionality that was never originally asked for.
As there are a few developers (6-12) all on UK rates (not exactly cheap) and one BA (still only UK rates, but only 1), I would think it would make sense to focus the effort on the up front work, hell maybe even hire another "BA" so the development team don’t have to handle code 2,3,4 + times.
It also means the teste (again on UK rates) has to test and then retest every time the change is made... how do you spell D.R.Y???
To say this annoys me is somewhat of an understatement. It is pretty hard to be focused and passionate about what you are doing, knowing full well in only a few hours/days/weeks it will all get thrown out because someone threw together a Use case, with out putting more than 5 minutes thought into it.
More time scoping => less time "bug fixing"*

*i.e. retrofitting missing functionality

Now I know Agile encompasses the ability to "handle change", but never getting the original scope correct... ever, through laziness, is not Agile, it's just software cowboy bollocks.

Unfortunately nothing is going to change. This could be a really good project, even a flag ship project for the company as it is using new exciting tools for the comapny (.Net 3.0, Nhibernate etc) and it would honestly only require the smallest extra bit of effort. But it wont and that’s a shame.

end of yet another rant...

M$ and OSS playing nice!

http://codebetter.com/blogs/jeffrey.palermo/archive/2007/12/11/mvccontrib-now-has-ioc-container-support-for-quot-the-big-3-quot.aspx

Windsor, Spring.Net and StrutureMap can now bolt in directly in to the new MVC framework... hopefully this is a begining... :)

Wednesday, December 12, 2007

Apache.org = 404

It really pisses me off that anytime i try to get something from Apache there are 404 error all over the show. I normally use Nlog, however at work we are using Log4Net. I went to the log4net site and most of the links i click on a dead... 404 bloody everywhere.
PITA!
As such i continue to use pretty much no Apache api's in my dev.

<UPDATE>
...and the downloads are 1.1 that dont run... NLog has just cemented its place in my toolbox.
</UPDATE>

Sunday, December 9, 2007

XBox

Yeah I had to get one.
At the apartment we have a huge HD screen. Gears of War and Assassin's Creed are awesome on it.
This thing blows my mind, the graphics are unbelievable... clearly I have not been up to speed on gaming or HD tv's....

I am addicted to the creed... stealth kills.. I feel like a bad man ;)

DSL's and tearing up tiers

Boo:
I read a lot of Ayende's post, well actually I read everything he puts out, so as he references his work with Binsor and Brail (which are Boo off shoots/DSL), I figured I had better see what its all about. Well I am still getting my head around things, I haven't learnt a new language in so long (shame on me). However I can now see why Bindsor would be so handy. I am not a huge fan of strings and XML to me, is one massive string. If i can get compile time checking AND get the flexibility of easy config. Sweet. Another thing on my massive to do list DSL up my configs.

Volta from MSDN labs is out... another thing I need to play with. Could be great for small teams teams if it works... after reading the blurb i am wondering if this is stepping on CSLA.Nets toes?

Saturday, December 8, 2007

Coding style and preferences

There are a couple of things i try to keep in mind when writing code, well they is plenty but specifically for this post 2.

Re-usability and Reliability.

I do all that I can to fail fast. I want my errors to come up as I type, ideally your IDE will support you on this, if not plug ins like ReSharper help. Other wise I want build errors to tell me, “Hey mate your code is junk this does not make sense!”. The last thing I want is run time errors. This is not obviously shared with others.

In my mind using strings for business logic is a last resort and if done there are always constants.

Casting is also a last resort, and usually only done from a know parent class to a subclass.

I would much rather use enumerated constants, generics, type checks to perform this business logic or flow control.

i have spotted in a few place where effective type checks are being done using string

if( Object.symbolX = "Fully.Qualified.Name.Space.ClassName")
{...}

if some one changes that name space then every check now has to be changed and the compiler will not pick it up.

it would have been just as easy (actually easier) to write

if( Object.symbolX = typeof(Fully.Qualified.Name.Space.ClassName).Fullname)
{...}
or even just do a bloody type check!

Secondly re-usability:
I am currently working as a contractor on an application that was many many week behind schedule largely due to an over worked non functioning UI. Myself and another contractor worked very hard to rebuild the UI framework (ie throw all the old stuff out and create new projects for the client side!) We knew it didn't have to be the best looking code it just had to work so the the user could see the application. 14 weeks and no visible app is pretty bad. 2 weeks later we had a app that functioned, very basically but you could so stuff. We are now almost up to schedule (6 weeks to catch up 14 weeks with 2 guys fired is not too bad).
The other developer who I wrote the UI framework with was reworking some of my code and asked if he could change (or overload) the constructor so he could inject the views controller into the view. I explained I prefer not to as it means the view become more tightly coupled with the controllers and I don't want the views to know anything other than they are Win or Web Forms.
I could understand were he was coming from, calling the controller from the view means its is easier and faster to write code. ie to save from the view just type this.IXXXXController.Save(XXXXX);
His points were valid. It is easier to code against, it is kinda loosely coupled as the View only know of the common interface assembly. I was starting to doubt why I go to the bother of creating events and delegates and event handlers (even most of them get reused).....
Then I had to make a change to a view and i realised why I follow this.
Raising events means that ANY controller can use the view. i am reusing a lot of my views. Having knowledge of the controller leads to spaghetti code..... as the other developer i currently work with is a pretty good dev I am not really worried that he is going to go down that path, worst come to worst we can retro fit the events when/if we get the time. However when we got another contract dev involved, it went pear shaped fast. He is gone now, thank god.

Benefits of using events
  • They can go on your interfaces
  • As many other class can subscribe to the event as needed
  • separation of concern
  • Changing the EventArgs doesn't change signatures of events meaning you wont break the build (provide nothing of importance is removed!)
  • Its clear where calls are coming from and where they are going. If i see a method in my controller called SuperView_RhysKicksAss(object sender, AssKickingEventArgs e){...} it is pretty obvious where this method is being fired from and why it is being fired (because I am Kicking Ass!), but you may want to check it is actually assigned a handler if you didn't write the code...

Negatives
  • You have to write your EventArgs and Event Handler. This is perceived as a headache to pretty much everyone i have worked with. When I explain the xxxEventArgs is just a DTO and the handler is a one liner they usually easy up a bit. BUT it is still an extra dozen or so line that need to be created.
  • Its easy to write sh1te event code if the devs are not aware of coding standards, meaning it is hard to understand what is going on. Follow conventions to save headaches later
  • testing frameworks offer crap support for testing events
After weighing it all up, i think for the mean time I am going to stick to events when calls need to go out of scope.

Thursday, November 22, 2007

Todo list

As always there is far to much stuff happening in the world.... I need a list!

Languages I want to learn (or at least learn more about):
  • Erlang
  • Boo
  • IronPython/Ruby
Things I want to play with:
  • VS 2008
  • Cruisecontrol.net (I have never actually implemented it myself.. which is bad)

Stuff I have been playing with recently:
Oracle. Its a big beast and is really quite different to MS/MY/T SQL. But I can see why it is the dominant RDMS...
Things I Don't like about my Oracle experience:
  • PL/Sql Developer by Allround Automations. I sucks and doesn't handler cut and paste functions properly (e.g white space characters it doesn't recognise breaks the code... why not just remove them?!?)
  • Shit schema's are not just the domain of T-SQL... they are everywhere ;) hehehe
MonoRail. The original MVC web platform for Asp.net. Its pretty cool, i have just built my new site, www.FullStack.co.uk on it and managed to get it together very fast, including the learning curve. Will i continue to use it? personally i have never really had to many issues with Viewstate and PLC. I don't put a lot of logic in my code behind so don't get in to too much troubles there.

PostSharp: I like it. It is a cool little AOP IL weaver that made my logging stupidly easy. Was going to try to add security with it too, probably wont tho...

Every day i would spend at least 2 hours read technical content, but mostly articles blogs and forums. I really don't read enough books...So lately i have been catching up on my essentials list.

Books I have just read:
The Pragmatic Programmer. Its hard to believe this is almost 10 years old. Sure it has been revised and there are some old references to languages like small talk (as opposed to newer languages like c#), but this is as relevant today as it ever was. Thoroughly recommend it.

Head First Design Patterns: I really wish i read this before GoF and Fowler... it makes the whole process a lot easier. I must say i felt like a dick buying the book as it feel like a high school book, but it is well worth it... i did make up for by buying Slash's Bio and the Flight of the Conchords dvd... sweeet.

Books i want to get
Erlang and NUnit from the Pragmatic series. I unit test every day but i would like to see "How Correctly" I am doing it. The xUnit testing book just far to big... its like 900 pages, come on...

On a side note; well done to the ever growing Open Source guys* that are getting snatch up by M$. Its nice for them to finally get some financial reward and its good to see M$ backing the real drivers of the community.

*Specifically Rob from Subsonic and Alex from Base4, but there seems to be many others at the moment too

Friday, November 9, 2007

Dependency on self?

I am worried that DI is the new singleton. A pattern with good intentions and fantastic helpful when used properly but slipping into the realm of the abused.
Wehn leaving Australia i was working on a project where there where dozen and dozens of unnessecary singletons. they really just ahd no reason to be there other than to slow things down.
Recently i have seen in quite bit of code using "constructor injection", no problem. But when you are passing in a object and then make this object dependent yopu are in effect providing circular references. However using interfaces this is allowed.
eg

My problem is: why?

I am seeing this specifically in the MVC pattern.
I dont need my views to know anything about my controller, so why pass the controller in as a constructor parameter. if it need to communicate with the controller raise an event, if the controller cares about this event it will subscribe to it.
I belive people are dodging using events because it seems tricky and DI is "cooler".
bollocks to that I say.

Strings

Strings are really beginging to annoy me. People need to think when they design API's if strings are really the best thing to use.
String are for reading, for humnas to read.
I am using a system where most of the strings should be replaced with enum or custom value. the reduction in runtime errors would be significant.
i have to campare time code in one exapmle, these are in string format. i now need to know and understand the other applications time code format so i can do a comparison instead of using
if(timecodeA > timecodeB)
{
//DO LOGIC
}
which would be the logical thing to do.

Tuesday, October 23, 2007

AOP vs IoC/DI???

An explanation to a colleague today that may be easier to understand than the typical ambiguous answer that he had recieved: "oh yeah its when you want to shove something in from the side"

AOP is different to IoC or Dependency injection (which is what Object Builder is) and can be used in conjunction with it.

IoC lets you code to interfaces and create object instances at runtime by calling the IoC Container (or dynamic factory) at runtime with the string key or Interface, to give you a concrete implementation of that interface (or sometime base class).

Spring.net and Windsor/Castle are the most popular open source IoC Containers and they both kind of do AOP as well, but it’s a bit convoluted.

Most people use AOP for “cross cutting concerning”, things like Logging, Security, Exception handling where you want a standard way of handling these things up and down the stack. The problem is that often at each tier, or even layer you get different people doing different things and it also mean you have code bloat like:

Public void MethodX(Type1 param1, int param2)
{
Log.(“enter MethodX);//Logging
Check.UserCanDo(MethodX);//Security
Try
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}
Catch(ExceptionY ey)//Exception handling
{
GlobalExceptionHandler.DoStandardExceptionHandling(ey);
Throw;
}
}

Where that whole thing can now be refactored to:

[StandardPublicMethodAOPHandler]//Logging, Security, Exception handling
Public void MethodX()
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}

Even better you can put that attribute on the method/class/assembly and then the normal devs don’t even have to worry about following standard procedure and code is a whole lot easier to read.

HTH. :)

Using AOP

I have been dodging AOP for a while now for the main reason that is "Looks to hard", especially when you have to explain it to PM's and other dev's who are still trying to get to grips with basic IoC and ORM concepts, after all projects are not solo efforts.
However I have now found a nice looking framework that may help.
PostSharp is an Attribute driven lightweight AOP framework that modifies the IL as a Post build event in the .Net framework.
This article here has got me very excited about implementing standardised Logging, Security, Exception Handling and maybe even Design by Contract.

Once i get my home development PC back from the dead I will post more about how easy it is (or isnt) and how it affect the project at runtime.
Should be interesting.

Friday, October 19, 2007

..made me laugh

I just got an email from Lloyds TSB (a bank) that I opened an account with weeks ago to say my online account is ready.

Yours sincerely,

Anita Hockin

Anita Hockin
Head of Internet

Head of Internet... that's an awesome title! She will however be getting emails from me when my wifi/browser stops working or when I cant log in to face book hehehe

On a side note, what took Lloyds TSB 6 weeks to do it took HSBC 1 day to do. It took 40 minutes from walking in the door to having 2 personal accounts, 2 business account and a credit card set up. I cant see me dealing with LTSB too much more...

Wednesday, October 17, 2007

Infragistics Controls

There are some time where a defined and limited structure is a good thing.
There are some time where a bit more flexibility is a good thing.
Then there are time when a blank canvas is ideal. I think Infragistics has gone for the third option.

I have been doing some UI work with the Win forms arena and the project i am on is using the Infragistics controls. I have no problem with that, at least they have define a UI standard in that regard. what i have problem with is just trying to find the most trivial operations on what should be basic controls.

I assume the Ultra Grid to be very flexible and somewhat insane as far how many methods and properties that are accessible... but a drop down list does not need to have that many options.

If it does, then a good idea would be to follow the basic MS naming standards so developers can find the appropriate properties/methods/events with out having to trawl through the slew of options intellisense give me... its been painful to say the least.

I cant see me buying the package for home any time soon.

Friday, October 12, 2007

"Public" API's

I have for along time prided myself on writing code that other developers would want to use. It was my brother that actual gave me that definition of good code and i think it is a good way to think of how to write code.

I have recently been using "legacy" code and am constantly amazed that none of the public methods /classes are commented or documented or have argument checks. What I find slightly amusing is the screeds of code that is commented out in certain code files. I have no problem commenting out code while running test etc, but delete before you check it in, that's what source control is there for! Certainly do not release code with all that crap in there...

If you write c# in the .Net framework you probably use VS. Turn on FX cop.
For gods sake its there to make you a better coder, not to just randomly show arbitrary message at the bottom of your screen. If i am working on a project i prefer the set warning to errors from the start, then the code stays clean.


Use ReSharper. Your code will be cleaner. I am the only one using it at my current place of employment and the HUGE amount of redundant code that shows up is unbelievable! It may go a way to explaining why after 14 week the U.I. was still not up and running.


Use GhostDoc. Its makes commenting a completely trivial task and also helps you name methods in a more appropriate manner. If I notice the comments don't make sense then instead of rewriting the comment I now rewrite the name of the method till the comment makes sense. The more you use it the less this occurs.


Check your arguments on all public methods. This is call Design By Contract. I basically check everything that isn't a Boolean.

These things all reduce the chance of you being one of those developers... the one that i curse at as i work with their code.

Look at your code.
Is it clean to look at, with out even reading it?
Can you, at any stage, generate meaningful documentation from your code?
Do you know off the top of your head what the code coverage is likely to be on your current coding project (assuming this is greenfields)? Is it appropriate?

Some colleague I have worked with think this is Gold Plating.
Bullshit. We get paid good money to do our job.
Number one priority is to develop working code on time, sure.
But I believe, certainly as a contractor who may never be seen again, it is also my duty to make it as easy and intuitive for the next guy, of whatever ability, to use, re factor, debug and modify my code.
These practices do not deter from our number One priority. In fact I have found the above implementations, along with TDD, usually mean that you are more likely to handle code once and not have rummage through it again later looking for bugs. And if you do, I guarantee it will be a lot faster than if you had not put these practices in place.


* certainly since I have been a contractor!

Monday, October 8, 2007

Still catching up..

Since I have been in the UK I have been trying to get back up-to-date with everything going on in the Geek world.

this has to be one of the big ones:
Releasing the .net source code!!!!

Holy cr@p!

Friday, October 5, 2007

VSS 6.0

Visual Source Safe sux.
It sucks ass.
It is a big pile of crap and I hate it.
Its up there with a poorly implemented Perforce.

Please bring me back to TFS...

Monday, October 1, 2007

Geek speak to Layman terms

Often I forget that the typical developer is not that well rounded; We are geeks and not all us have the best social skills. This article highlighted in a readable way, how you could articulate this to your geek team:
Can Your Team Pass The Elevator Test?

Something I think all employees should be able to do, especially in small agile* software houses in which your end developer may/probably will talk to the end client.

*agile in the true sense not necessarily the methodologies...

Thursday, September 27, 2007

Scott's Tools list

I am a tool whore, but clearly not as bad as Mr Hanselman... jeez.

http://www.hanselman.com/blog/ScottHanselmans2007UltimateDeveloperAndPowerUsersToolListForWindows.aspx


Luckily most of dev ones are familiar and i have kicked their tyres, most of the Smart people are on my regular read too... sweet.
At least my fingers are vaguely on the pulse *somewhat reassured*

Tuesday, September 25, 2007

Sweet Silverlight

Some cool stuff is being done with WPF and Silverlight of late. The offical SL release is now out as well as Alpha 1.1 for developers (get them here).
Moonlight is on its way, which with help from Novell will mean Linux users will be able to experinces SL too.

A guy named Jose Fajard from Sydney, Australia (AKA LiquidBoy AKA AdvertBoy) has been doing some cool stuff with a pretty quick turn-around.

Check out this dudes site:
http://advertboy.wordpress.com/


He has a sweet little blog explaining how he is buildiong an online version of iTunes and has a nice bunch on Silverlight controls... ready for download.
Tres cool.

Demo of the controls on his "Beautiful Website"

Source code here on Codeplex for the iTunes app (and for the controls I believe)

Sunday, September 23, 2007

xUnit.Net

James Newkirk and Brad Wilson have put out a new testing framework to paralell some basic standards (ie no SetUp/TearDown methods, better expected Exception handling and use of generics)

download here:
http://www.codeplex.com/xunit

read Jims blog here:
http://jamesnewkirk.typepad.com/posts/2007/09/announcing-xuni.html

Looking forward to using it. :-)

Friday, September 21, 2007

How to get a .Net contract in London

1st: Call GCS and talk to Doug Viney. I'm not kidding, he's that good.
2nd: Put your CV on Monster.co.uk
3rd: Look on JobServe.com for jobs you want.

CV has to be short, 2 pages, with no fluff.
Tell them what technologies you worked with, what you managed to achieve at that job/on that project, and how long you were there for.

Have your phone charged with money and batteries, the more calls you make and recieve, the faster you pick up job.

Easy.

Back into cutting code

Well I have landed on my feet pretty well here in London, weather has been good, met lots of friends and family and have found work easily.
My first contract was found in 2 days, was only a short contract to help out a media company for 3 weeks. It was basically fixing some issues in a custom built CMS implementation.
ASP.net gone wrong.
1/2 tier design, SQL in the aspx's, no testing of any description, no documentation, no arguments checks on public methods, no reliable source control... it was not too good.
Fortunately the people there are absolutely wonderful and the application was pretty small so pretty easy to hit the ground running. Hopefully I helped them out and gave them what they needed and was good value for money!

Well 3 weeks didn't eventuate as I got offered a job by another media company for better pay, longer contract and seemingly better code base/practices/procedure's.
My recruiter for this particular job has not really impressed me. I was confirmed for the interview 90 minutes before it occurred. I was casually dressed and ill prepared. I was given the wrong address and sat waiting in the wrong reception of the wrong building of the right company for 35 minutes as we couldn't get hold of the HR person. Luckily the IT guys i was doing the interview with figured something was up, notified reception and sent me along. I then proceeded to meet the Lead Dev and Architect, while i got grilled about things like Nhibernate, WCF, SCSF and heaps & stacks....

Having
A: Not written more than 10 lines of code in any given day while i was in the states,
B: not really being pushed at my existing contract,
C: an awful experience leading up to the interview
..I was pretty horrific in my interview and answering of most questions (well at least i wasn't happy with some of my answers.. yes there was an exam)

I left, having met some nice guys who seemed to know what they were talking about, and was a little disappointed that i hadn't been better prepared.

Any-who I get a phone call about an hour later; I somehow managed to get the job.
Sweet.
I told the current agency I was working with that I was cutting my contract short, which they were fine with, and accepted the offer.

So I am back to
Win form apps (CAB influenced)
WCF
NHibernate
N tier dev (where N is greater than 2 ;) )
TDD (TFS and Nmock)
Agile Dev (team is stilling learning... but who isn't!)

soon to be introducing for IoC either
Castle/Windsor or
Spring.net

And new for me is
Video on demand
&
Oracle (which I have already learned that triggers can NOT modify data in its owner table.. apparently...)

The pay is OK, was aiming for a bit more, but what really pissed me off is my agent gipped me on putting me on day rate not hourly (bastard) and then didn't tell them I have a holiday booked for mid October (Rugby world cup match in France!!)
Oh well worse things can happen.

So all is good in the city of London, just need to find a nice studio to fill with new computer, new guitar amp and a huge new bed... then I will be very happy.

PS
I did have an excellent experience with one recruitment agency called GCS, specifically a guy called Doug Viney. If you are a good, experienced .Net contractor looking for work in London talk to this man. He is very professional, personable and very efficient. He came recommended to me and I highly recommend him too.

Code snippets... yay!

I am starting on a new project without resharper... so i have to write alot more code than I am used to... enter VS intellisense code snippets!

Here is a very basic one I have for NMock;

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Create a NMock Test</Title>
<Description>Create a NMock Test using mocks to improve testability.</Description>
<Author>Rhys Campbell</Author>
<Shortcut>testmock</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>IMockClass</ID>
<ToolTip>Replace with the type of interface of the mocked object.</ToolTip>
<Default>Interface</Default>
</Literal>
<Literal>
<ID>mockObject</ID>
<ToolTip>Replace with the name of the mock object .</ToolTip>
<Default>mockObject</Default>
</Literal>
<Literal>
<ID>TestObject</ID>
<ToolTip>Replace with the type of the test object .</ToolTip>
<Default>TestObject</Default>
</Literal>
<Literal>
<ID>testObject</ID>
<ToolTip>Replace with the name of the test object .</ToolTip>
<Default>testObject</Default>
</Literal>
<Literal>
<ID>MethodToBeTested</ID>
<ToolTip>Replace with the name of the test method to be called .</ToolTip>
<Default>MethodToBeTested</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
[Test]
public void TestExpect()
{
// mock the dependency by way of interface
IMock $mockObject$ = new DynamicMock(typeof($IMockClass$));

// setting up values
$mockObject$.ExpectAndReturn("Mock object expected method call", "Mock object expected method return value"); //remove and replace with appropiate expectation. NB: NMock uses strings not strong naming for it method calls.

$TestObject$ $testObject$ = new $TestObject$(($IMockClass$) $mockObject$.MockInstance);
AssertEquals("Some sort of valid repsonse", $testObject$.$MethodToBeTested$()); //replace with approriate test

// Verify that mock expectations are met
$mockObject$.Verify();
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

(you may want to format that) ;)

As per the M$ site:

Before you can begin writing your code snippet, you must create an XML file with a .snippet file name extension.
To create a .snippet file

  1. On the File menu, click New and then click File.

  2. Click XML File and then click Open.

  3. On the File menu, click Save .

  4. In the Save as type box, select All Files (*.*).

  5. In the File name box, enter a file name with the .snippet file name extension.

  6. Click Save.


What they dont say that you should save it somewhere that VS will know where to find it. the easiest is My documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets\
this is where VS looks by deafult, this means you dont have to import it it is just ready to go.
so to get the code to work just type in:
testmock
in any C# file and *Bam* there is you intellisense code block ready to fill out.

this propbaly wont change you life but its certainly a nice to have, espeically without my blessed ReSharper...

For more info: Go to the MSDN site

-oh the imports staements dont work in C# so i cant import my testing namspaces which sucks...

Wednesday, September 5, 2007

WPF

In my pursuit of jobs in London I have noticed a disitinct lack of .Net 3.0 and Ajax orientated ad's.. which for some reason reminded me of a conversation i had when silver light and WPF where hitting the seen... Why? Flash is not really used heavily in enterprise solutions.. why is MS going down that path?
Well for starters, why not? It provides another option for the MS sector to compete with the those "other" types and if MS has the resources.. then give us the options!
Secondly it helps create more usable UI's and therfore, possibly, a better user experience.
WPF is been used in several financial institutions that I am aware of. It make sense to make the experience as easy as possible.
I one instnace training is a very costly execise, especially for markets where there is a high turn over of staff that still require a certain amount of relevant businesses knowledge.
In another situation, large amounts of data that needs to be represented in a user friendly manner (different graphs shown changing in real time) can now more easily be created so user can make more educated descisions in a more timely manner. these are more easily configured and manipulated again in real time for optimal UX...

It seems that these companies that are throwing massive amounts of cash into prelim studies, R&D and then on the not-so cheap teams of contractors to learn and implement these new trendy technologies must be of the opinion that the cost of dev is worth it.
Good for us I say!

Friday, August 31, 2007

I'm back...

No blog posts for the last few weeks as I have been difting around the US of A playing Water Polo, road tripping with mates, meeting cool people and basically just chilling out and having a good time.

I will be landing in London in a few hours and will be back into suit wearing, geek talking, key board bashing work and to be honest, I am looking fwd to it. I took my laptop away with me, however only really managed to check emails (still hundreds unread) and maybe got 8 hours of code done... in 5 weeks... not so good.
Will be going over all my favourite blogs over the weekend to catch up top the rest of the world... updating my CV to reflect the last few projects is was involved in and stream line the contents for the more agressive UK job market.

I have even splashed out and got myself a new CK suit in NYC... I am looking fwd to the challenge... interviews begin on monday... wish me luck!

Monday, July 23, 2007

New stuff to play with

More stuff to go onto my "To play with" list
IronRuby: Relased today in a pre alpha state. Im actually quite excited with the DLR...
Rhino-ETL : Ayende is fast becoming a legend in my book. Coming from a background where intergration was part of the daily grind, this could be a nice tool to have in the tool box :) It may even work nicely with a project i am working on, on the side... hmmm

Measuring Productivity

LOC is possibly the most stupid way to measure productivity. It really doesnt show anything and possibly encourages bloated code for the not so noble coder keen to grease up to the project manager.
Possibly a better option is measuring based on passing Unit Tests.
Why?
  • A unit test usual defines one part of functionality.
  • It encourages the developer to write untis tests and encourages more robust coding.
This is kind of a brain dump, but i think it may have merit...possibly.

Tuesday, July 17, 2007

Working in "Verticals"

I am currently wrapping up my time contracting/consulting to a company building a POS system in CAB.
Long story short the team seems to divide work in to verticals. i.e. can you build this piece of functionality.. the MVC components, the services, the persistence, everything. I really find it odd. I have raised the issue a couple of times and the team assures me that the system is so intermingled that you couldn’t possibly work in "horizontals" i.e. tiers. This has caused, IMO, a huge number of issues, including redundant work, rework and re-rework as people don't "get" certain patterns or reason for the code. It also means a Graphics guy is handling the DB and the DAL.
Jesus.
To be honest I would have put the juniors at the front end. They could have learnt all about MVC, Win forms, CAB with its dependency injection (of sorts) events & delegates... that’s plenty to take in for people new to C# and .net!!!
A proper DBA should have been in charge of the DB. Instead developers have clearly written it. Normalisation in my mind is generally a good thing. DB schema changes weeks out from release are not, especially when a DBA out of college could have spotted most of the mistakes.
The the intermediate & snr dev work on DAL, Services and business logic while the Lead (there never was an architect) focus on architecture, framework and code reviews.
Making mistakes is not always a bad thing, but you have to learn from them to get anything out of it. Perhaps I am not doing my job well enough if they still don’t get it. :(

Thursday, July 12, 2007

Acknowledging progress

I quite like this idea:
When projects seem like they are going on forever... something like this could be quite a good motivator for the team. I probably wouldn't put in the direct eye of clients as it is pretty messy (but in my experience most coding environments are anyway...)

Tuesday, July 10, 2007

Open Source list

Jeff Atwood is pushing to help reward some of the .Net OSS community by donating $10k to the most deserving application (or the group that runs it). That’s pretty nice but I am much happier that there is a pretty comprehensive list of GOOD .Net OSS application/frameworks/tools here:

http://spreadsheets.google.com/pub?key=pKxDW35algYebfs8nssTjIQ

I don’t know if this link will work forever... perhaps just for the length of the "competition".

Shot Jeff!

Saturday, July 7, 2007

SubSonic

Like a lot of people, writing Data Access Layers is not something I really want to spend a lot of time doing. Thankfully there are a vast number of ways that you can improve the process, ORM's and code generators are the two basic methods of assisting in this fashion. Many will be familiar with Hibernate (and its .Net equivalent), possibly the most popular ORM on the market. I quiet like it, but it’s fiddly and config heavy in terms of mapping files. You can Generate these thanks to product like MyGeneration but it often requires tweaking. once its up and running it really is a nice way to deal with persistence for very OO based applications. The other option I have used is Codesmith with it NetTiers templates. Well, up until finding Subsonic. It (so far) has been great.
What I like:

  • Can have the benefits of SP’s and ORM

  • Can set it to generate the code at build time, so you know every time you run it it is synched with the data base

  • If you don’t like the generate on build option you can easily generate the class files for the DAL as well as the create scripts for DB including data, all from with in VS (great for Source control!)

  • Author(s) seem to be very proactive in their support and maintenance

  • Can be used with in VS as an external tool, meaning one click generation from within VS.

  • Minimal additional config settings

  • Video showing you how to do it.

  • Its pretty fast

I last ran into Subsonic when it was ActionPack. Being happy with Codesmith I didn’t really follow it up. However, as I no longer have a license for CodeSmith, SubSonic being OSS is looking a lot nicer :)
No doubt as I continue to play with it I will find features and bugs, but so far so good.

Wednesday, July 4, 2007

"Just one test!"

I have read in a couple of places now (amongst other generalities) that a unit test per method is the standard "rule of thumb". I have been surprised at this. I understand that at least one test per real method (not one line getter/setters) is a minimum but to generalise it to only one is a bit odd.
This was kinda sparked off by this post http://blog.sidu.in/2007/06/pre-run-tasks-unit-testing-anti-pattern.html. I am not coming down on the poster at all and I may have over reacted to an aspect of the post that was certainly not the main point of the thread.
But just one test per method? It got me thinking.
I generally have a test to cover each of the paths in the method (to an extent).
I never really thought about it but I guess complete coverage* would come from tests that match each of the paths and therefore the cyclomatic complexity of that method. If you have an increasing number of tests for a method you may want to reconsider the functionality of the method. Can it be refactored?
This I believe is another benefit of TDD. It forces you to think about function design first not just start the torrent of code and hope that what comes out works. This is also a reason to write the tests first. I find it amusing that some still write the test after they write the code. I mean really, why not define what you want then build it.

* no im not a coverage nazi :p

Monday, July 2, 2007

ICloneable = mess

I have never really taken it consideration of the reasons of why not to use ICloneable. I know not to do it, so have never had any issues. However the current project I am working has object inheriting from a certain base object that implements ICloneable (why? I don’t know).
Now the fact that none (or very few) of the ICloneable methods returned anything other than null, could have been the first sign that it might not be the best interface to implement. Then there are the deep versus shallow clone issues... who know’s what is doing what.. and then the returning of type object. Excellent. :(
Unfortunately it was a Microsoft consultant that apparently suggested using it.

Now we have a non standard clone implementation that some time does deep and sometime does a kind of shallow clone. Yuk. At least some of it is now documented.
As the classes are shared across other projects a cant just go an remove the interface… not that it looks like any one is actually using the method; as it is returning null everywhere… weird.

Back to asp.net - PageMethods

A little bolt-in that I found a while back and have never used is finally getting a test drive.
PageMethods basically helps you "strong type" parameters for aspx pages, meaning you get such benefits as intellisense & compile type errors.
Again, I'm a sucker for little helpers like this, because errors like mispelt paramtars tend to really peeve me off. ;)

Thursday, June 28, 2007

Higher learning...not so specific

I thoroughly agree with this post by Jeff:
http://www.codinghorror.com/blog/archives/000895.html

The most valuable things I learnt at uni were the ability to critically think, analyse situations and "learn how to learn". Although I really don’t use a lot of my studies on a daily basis I believe it helps me every day mainly in R&D

Wednesday, June 27, 2007

NHibernate gotcha for Generated files

To save yourself repeated banging of you head make sure you HBM.XML file are embedded resources in the nhibernate project, otherwise how is nhibernate going to find these mappers....d'oh!
This highlights a point: Its nice to generate what you can. Hell, if you have already written the database tables, why not Gen the majority of your data access? You still however, have to know what is going on under the hood, whether its nhibernate, other ORM or straight ADO.Net. Otherwise how fix you fix lower level problems when you run in to them...

Tuesday, June 26, 2007

TDD still not with the masses?

Recently I have been a contractor on a project that I have been given I little bit of grief (perhaps light heart, perhaps not) regarding the number of unit tests I have written in comparison to the production code I have submitted. Upon talking to some external mates in the development field there still seems to be some confusion as to why to test, how to test and when to test. I will happily admit that I am no TDD guru and am relatively new to the having only really being diligent about unit tests over the last year or so.

I did want to share some of my reasons, that may not be so text book, for using TDD. I will start with aspects of TDD, that on my most recent project, I have directly benefited from:

Define the Functionality of the Module
In the last project requirements were somewhat lose, so writing the unit test help the guy with the business know how and myself knuckle out what exactly we wanted these blocks of code to do. The people that will have to maintain my code as I move to the next project will probably find this module easier to maintain because of the reasonably well named and documented tests that are in place, meaning reduced ongoing cost of the code base.

Ability to Refactor with Confidence
As I was receiving information about the requirements in a piecemeal fashion, I was forced to write code for the functionality as I got it. This quickly became quite a large amount of code which later we found had aspects replicated across multiple classes. Refactoring these classes to strategies that inherited from a base strategy which inturn implemented an interface with the real business logic held in a handful of delegates meant we reduced the lines of code by 73%. As we refactored we made sure the entire block of unit tests still passed. The code is now a fraction of the size, very easy to read and maintain, fast and still fulfils the requirement set forth by the business. Refactoring all that code that took weeks to write was done in a day, in confidence because the unit tests were written up front.

Reduction of “Gold Plating”
In some case I get carried away and start writing things that I haven’t got a test for, because they may be needed in the future. This is by and large a bad habit of mine, I don’t get paid to gold plate, I get paid to provide a quality solution to a defined problem, even if that problem is not very well defined!
How has TDD helped? If it was not being covered by a unit test, it either needs to be or it gets removed. 9/10 it get removed as the tests are written first and they define the functionality.

Code Confidence
Although test don’t prove you code is good (see TDD Anti Patterns) it odes show that I have thought about what I am doing and give other developers or interested parties a direct view at what my code does. Most of my test methods are named so it is pretty obvious what they do, sure some get pretty long but I can find a unit for a module that I wrote months ago pretty bloody quick and figure out with in seconds the exact functionality. This is especially helpful if you have no BA support or business requirement documentation (yes it happens). Not only am I more confident in my code but I am more confident in other code if it is unit tested.

Encourages Correct Separation of Concerns
Especially when using mocks it becomes apparent when projects are starting to take on more functionality than they should.

Up-to-date Code
As I am writing tests for my code, as I go, I find that I am more likely to be within minutes of a previous compiling working solution. Formerly I used to go on tangents and write pages of code which may have been in a state far removed from a submittable state. If for some reason I was asked to shift on to other functionality I would have to shelve changes roll back and then work on something else. If I ever cmame back to that code I often had no idea where I was up to. Now I know exactly where I am up to… the method that breaks the unit tests! It is also more likely that I wouldn’t have to shelve as it is probably only a minute away from being in a compilable stae that I could check in to source control.

Easier to Make Changes
There have been some instances where the business requirements, or my understanding of them have been (a little bit) off. Having the test there means I can modify the test to assert correct assumption run the tests, see it fails and then make an isolated change in the code. As the test marry up nicely to the code the place where the change is required is very easily found and fix. ..Run test…. Pass test… Check in.

So how do i go about it? Well my"why" is covered above. For more reason check out http://www.testdriven.com or any other of the plethora of sites and books dedicated to TDD... as for the when and how...

When to test?
Before you have even written the functionality! Define what you want the method to achieve. You will probably find your self writing multiple tests per method and test fixtures are generally a lot larger than the class they test, bu the time you save in reduced debugging time and easier maintenance is well worth it.

How to test?
There are heaps of tools to use and can be a personal thing. Currently I am using TestDriven.Net with NCover and NUnit as well as ReSharper & Rhino mocks. As ReSharper is the only tool here I have paid for there is no reason not to get these widely used tools (I probably should throw some money at Testdriven.net).
Try to get a test project for each business project and a test fixtures should closely marry up with the projects classes. I don’t test minor thing like properties… there should be reason for the test!

Most frameworks now are very open to TDD, so there is very little reason not to use it. Right up to UI patterns, all but the view are very easy to test and mock. And as the view is completely stupid it should not have a lot scope for error.
So start testing; the initial growing pains are well worth it.

RhysC

Monday, June 25, 2007

Win form UI dev

<Disclamer>I suck at Win forms dev, the only time I use it is for test rigs and for uber basic (in terms of UI) CE apps </Disclamer>

I have been trying to set 3 total values to right align at the decimal point in a panel on a WinFom app. It proves to be not as trivial as I expected.

I have to place each of them in a panel and then dock these labels to the right side of the each holder panel. What over kill! Why can’t the AutoSize and Anchor functionality do this for me? Oh well…

WS... not so interoperable..

from Udi:
http://feeds.feedburner.com/~r/UdiDahan-TheSoftwareSimplist/~3/127874396/

"...So imagine my surprise when we “Web Service-ized” a bunch of Java components that exposed just that kind of interface, and it didn’t work. After mucking around for almost the whole day, we started returning to basic principles. We started throwing out parameter after parameter, structure after structure, until we were left with something that should have just worked:
string SomeFunction(char c);
But it didn’t.
This was ridiculous. If Web Services couldn’t give me interoperability at this most basic level, I swore that the whole thing must have been a conspiracy. After some ill-mannered googling, I found out that:
The Java char datatype is not supported because of an omission in XML Schema..."

Tuesday, June 19, 2007

Translating Geek-Speak to Suit-Speak

A colleague and I were talking of the technical debt being incurred on the project we are currently consulting for, when I commented its a bit of a wanky term. CDS quickly reminded me that its a term probably used when a Dev, Architect, consultant is talking to someone in more of a business role and that we have to talk in their terms, i.e. ROI, Debt, Interest, Inflation... i.e "$$$ speak".
It was a good reminder that in times when you need to emphasise crucial points it probably best to talk in a language the other party will actually understand, and therefore "get" the significance of the problem. It is then up to them to make a more informed business decision from there.

Recurring events and SQL

Working with "Recurring events" is proving to be interesting. I am trying to create a framework that will allow for adding recurring events (such as training times from a given team) with reasonable flexablity, reasonable speed in creating and querying and still reasonably maintainable.
It looks like there will have to be a trade off some where.
I am using the concepts from Fowler's recurrence essay and extending that. Putting that into a Database pushes me to wanting to use the XML datatype... the more i think about it tho, the less I like it as the querying power would be, well, not so good.
If I use table to map to the temporal expression it could get messy quick too. Either way i am wanting the abiltiy to create db entry for an instance of the recurrence so people can leave note etc for specific occurances...

this is going to be interesting... only post i could find so far has been

http://forums.devx.com/showthread.php?threadid=136165

I may have to step back again and relook at what i'm doing ;)

Sunday, June 17, 2007

Investigating ORM's - dOOdads

As I continue to play with various ORM and DAL code genrators i come across things like:
"Since dOOdads doesn't handle joins, I prepare the joins ahead of time by creating
views"
.... arrrhg, OK.
Look's like dOOdads is off the list.

Tuesday, June 12, 2007

Open source TDD and Unit Testing Tools

Having moved to a project without the luxury of VS-TFS, I have had a look around for some other open source tools to make up for some of the aspects of TFS I have become acostomed to.
No need to go into the details of them, their sites explain all. I assume everyone is aware of NUnit.

TestDriven.Net
NCoverExplorer
NCover
NUnit

Common MS SQL “Mistakes” - Part 1

In the last year or so I have moved more in to more consulting and contracting based work which means work working with a larger spread of developers with a an equally wide range of skills and abilities. There have been many generic mistakes I have scene (as well as some great code) but the majority of major mess ups I have seen is by far based around Database and Data Access. This is probably one of the major reasons why so many people are moving to ORM’s, because it removes the responsibility of creating the DA layer and the potential pitfalls that can come with it. This is fine, but it also means that a lot of people are becoming ignorant of the details of these layers. Generally these layers are the very foundations on which the application or applications are built on, I believe the blasé nature in which the technologies are approached is the reason why some run in to such major issues mid project. This late in the scene it is very hard to go back and make schema changes, especially if multiple teams are working off this schema.

I have decided to compile a list of issues that I have run in to in the last year, that I believe are potential short comings of the data related architecture. Often these points by themselves are not huge issues, but when I see one I usually can find another just around the corner.

Hopefully these come as some help to you and your design. Please remember this is coming from a developers perspective, a .Net and MS SQL developer at that, and I, in no way, proclaim myself to be a guru in any regard, however I feel these are basic points should be a general rule of thumb.

Database structure
Normalisation
Normalisation to the 3rd normal is standard. If you don’t know what 3rd normal is then it is a good hint that maybe you may not be the best one to be designing the DB. Sure there are reasons to move away from this rule but it should be just that, a reason, not bad design. Perhaps you may even want to document these reasons so it is clear why.
Nullable Columns
There will always be a need for nullable columns, however when tables start to have a growing number of nullable columns, you should start questioning why. Perhaps these can be moved to a separate table.

Property Tables
If a table is starting to have a lot of columns and many of them are null then you may want to implement a Property table and a PropertyType table. This is relatively clean and easy to set up and if done properly, is a fast way of getting a potentially large albeit often unknown number of properties, and a lot cleaner.

Incorrect Use of the Primary Key
Recently I saw a table that had a multi column primary key over five columns. After spanning more than 2 columns alarm bells go off in my head. In this case this was just bad design. The table only needed one Primary Key with one index on another column. Often this set up I find is good especially when there are unique values such as “Product Codes” that could be the PK but are in a format that does not suit performance (e.g. varchar(1000)). Using a smaller data type for the primary key improves performance. I also generally prefer to use [int] IDENTITY(1,1) as the default primary key for tables. Using large columns as PK’s in my mind is a bit of a no-no. Some times GUID’s are used if there is movement across to other databases. If this is happening then there is probably a properly qualified DBA involved leaving us developers to move back up a layer J

Incorrect Use of the Foreign Key
I have actually seen foreign keys been “used” without the being specifically being set, meaning referential integrity can not be there! Why this was done, god only knows, as it was not documented.

Not Appling Basic Coding Standards
Commenting code is a given. I can’t stand working on projects where Classes, Methods, Properties or Parameter are not obviously named and well commented. Most developers share these views, especially one who have come into projects late. For some reason these principles are ignored when it comes to Database development. Columns get named things like “DscInd” and have no comments associated to them. As far as I am aware there are no real penalties for naming you columns something that is easily understandable. The benefits are however large. People now understanding what is actually being stored! These basic procedures also help spot flaws in any business logic. If the intention of a piece of code is explicitly commented then, if for some reason it is wrong, alarm bells go off a little easier.
Naming conventions are typically applied in managed code but again are often missed in DB Development. I could go on, but you get the general idea. Treat DB dev in the same way you would when it comes to basic procedure such as naming, commenting and using the correct types.

Monday, June 11, 2007

Quote of the day

"I used to use Linux, but then I finished University" - CDS

hahahahaha.... I giggled.

Saturday, June 9, 2007

False Economies

As I get older and more experienced in the IT game some basic truths continue to rear theirs head... One I am currently running into is the idea of not doing some standard practice thing because it will “take to long” or “cost too much money” to do.
I have no problem with not doing some because it is too expensive, however when you are building a business critical application for a publicly traded, Tier 1 company, you had better make sure that those things that you are not going to implement don’t bite you in the ass later.
Documentation and Unit testing should not be negotiable. Especially around business object and other lower level layers. If these layers are not working correctly, how can the layer dependent on these be reliable?
One thing I see more often than I like is not putting enough emphasis on DB design. If you are using a very basic OO model and the DB is literally just a persistence layer then I am all for ORMs. If you have complex set based structures, hire a good DB geek that can architect a proper data persistence approach in terms of DB design and helping with Data Access. Often a developer is not the right person to be doing this.
(I think I have already emphasized this enough on this blog)
Another issue is allowing for future changes. Udi Dahan proposed a design principle which I agree with and employee:
For any classes A and B in a system where both A and B have behavior, A should interact with B through an interface.
The interface which separates two concrete classes should be packaged separately from either of those classes
By employing the strategy above, you allow for the ability to have tests to isolate each “layer”. You also then allow for changing of dependency. As long as the new class implements the original interface, how the business logic occurs is irrelevant. This came up specifically this week with regards to the data access layer. Using this strategy we could investigate different options in terms of the DA, such as using the current implementation, a modified version of the current, an ORM or a Generated layer based on the DB schema. If this had been done earlier it would have take lesser than a minute for each class. Not really a huge time loss there.

I dont take all of this as bad things, it is learning from mistakes, whether they be yours or others. The point is we need to learn from them so we can find ways to avoid or fix future encounters.

Tuesday, June 5, 2007

Currently Playing with Castle stuff and GhostDoc

New (to me) stuff i have been playing with:

As well as the CAB/ SCSF stuff ihave been working on at work, I have been playing with AR & AW at home. They dont really go with my normal views on enterprise level data access, however in my vague attampts to broarden my horizons I have started to dable in their worlds.

Benefits:

  • Easy to read code. As all the DA is under the hood its code creates the illusion(?) of clearer code.
  • Easy to create Business entities and DA, just drag and drop.
  • Seperation of Business entities from UI

All of this can be done with Code smith, however I thought I would look at this as it is another "string to my bow" so to say. I am currently building a smalll web app from it to see how well it work under light load.

I can see these tools beign great for very basic web sites. Get someone who understands the data requirements to build a DB and AR classes then just palm it off to the UI guys as the model aspect of an MVC set up. Would be great from 3 tier app with basic data structure.

Ghost doc... well it just helps with documenting your code. Its very simple but anything that helps with the mundane is a good thing in my book.

Tuesday, May 22, 2007

Object Builder

Object Builder is a very handy piece of the CAB and software factories, however is sadly not so handy in the real world. I was hoping that it would be a Microsoft implementation of the very useful DI containers that float around like Spring.Net, however I seem to be mistaken. The documentation is sparse and a the PowerPoint I could find wouldn’t run on my current Work PC… hmmm.
After finding blogs like this that seem to be mirroring my own frustrations, I have decided to stick with what I know.
Spring.Net is a fantastic tool that is really, in the scheme of things, bloody easy to use.
Why was I hesitant to use Spring.Net? Firstly we were already using the SCSF, which uses CAB and the OB, so that was obviously my first preference (ie use something already in use!). However as mentioned it implementation fell right into the “taking to long to research and even get started” basket. Secondly, well, some companies are hesitant to use 3rd party tools, especially on critical aspects of business. Having that little “Microsoft” prefix on the assembly tends to give more peace of mind.
However the Spring framework has had such wide testing and I feel that I have given it a pretty good tyre kicking, so I feel happy to use it, hopefully the PM does to.

Monday, May 14, 2007

DB Normalisation and other DB points of view

Over the last couple of months I have heard the commments "its a very normalised database" or various implications that database X is "too" normalised. i often found this odd.
Why?

  1. By looking at a DB schema how do you know how well indexed the DB is?
  2. How do you know how many rows are in it?
  3. How do you know about it performance

I have always been of the opinion that you

  1. Normalise first, create a beautiful piece of art that is a nicely and appropriately normailised database.
  2. Add indexes.
  3. Write your sored procs.
  4. Check the performance on test data.
  5. Denormalise if nessecary, however if there were issues I would go over everything with a fine tooth comb first to ensure keys, indexes, constraints, triggers are all in place where appropriate, working as intended and not adding unessecary overhead. Then I would start denormalising.

Yes i am a fan of stored procs, especially for anything that actaully is DB intensive. As Gumble also points out (frequently) it adheres to a basic concept we use daily, encapsulation. Normal Objects and Layers/Tiers cant see into the next object/layer/tier, why should this be broken at the data access layer. Using SP's also (IMO) aids in security and data control (well it can, anyone can butcher code) ;). The OO coders should not have to know the underlying data structure, they know what they want, they just need a means to get it. The Dba may be adding a whole bunch of stuff that the OO boys dont need to about, inactive flags, triggers, loggin, other extra columns, how the data is retireved etc etc... also this mean performance is left in the DB world and can be easily tested with out any manged code interfering.
One thing i do prefer is isolation of tests, i dont want to not be able to test individual units. A stored proc is a unit, a BusObj --> Repository --> DA--> db --> DA --> Repository --> BusObj is not a very succinct unit. If i want to test that vertical i still can however i want to be able to break it down too.

Then there is the point of ORM's; I'm all for them, anything that gets rid of boring DA code, sweet! But sometime you have some complex resultsets and DB call that do not suit your run of the mill ORM's. I do believe for basic database and when fast turnover of code is of higher importances, then something like NHibernate (perhaps with AR) can be handy... but i think it needs to be reviewed on a case by case basis, unlike some of my peers who believe NHibernate is the silver for all solutions...

no doubt more will come...

Saturday, May 12, 2007

Framework Design Guidelines

have just started reading Framework Design Guidelines i must say that it's a must read for anyone who writes code that other developer may have to read or use. Framewroks designers, class library designers, plug ins, widgets etc... basically anyone who codes in .Net.
Its a VERY fast read, not a lot of overly conspetual stuff and very well written. Hopefully most of it is stuff you already do, fortunately i have worked with and been exposed to some very good coders and thankfully i have picked up their good practices so alot of this is confirmation of ideas.
Read it, you will either pick up lots of good practices or confirm you are doing things right. Either way its a book you can read in a weekend with out too much of a problem.

Monday, May 7, 2007

Online video editor with Silverlight

Check out this demo from Metaliq. The sample app is called "Top Banana" and is a lightweight online video editing application written for Silverlight.

Yay silver light!

(from the must read blog of ScottGu )

Thursday, May 3, 2007

Sandcastle - Documentation

We are coming to the end of the project here at work so needless to say all the documentation has to be handed over, including the API for the code base.
As we using .Net 3.0 Ndoc cant be used so its replacement sandcastle was our obvious option. Sandcastle being still a CTP is pretty clumsy to use, so here is some tips to get you going.

firstly check out the Gui or batch tools out there, some of them are pretty good. Check the codeplex stuff and SandcastleGUI.
Unfortunately this (specifically SandcastleGUI) wouldnt work for me as it tries to find DLLs that may be referenced even if not used (this may point to redundant ref in our code). as time was not on my side i decide to just run with the default console implementation.

...Anyway some tips.
Put all your Dll's in one directory. Even if this means copying them all into a holder directory for the means of the documentation exercise. This includes anything that the dll's may reference. Normally this is the case anyway, however with distributed systems, and gacs, and what not, it isnt always the case.

Assuming you install sandcastle in "C:\Program Files\Sandcastle" the below script will create your help file.

"C:\Program Files\Sandcastle\ProductionTools\MRefBuilder.exe" alpha.dll beta.dll gamma.dll /out:reflection.org

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\ApplyVSDocModel.xsl" reflection.org /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\AddFriendlyFilenames.xsl" /out:reflection.xml

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\ReflectionToManifest.xsl" reflection.xml /out:manifest.xml

call "C:\Program Files\Sandcastle\Presentation\vs2005\copyOutput.bat"

"C:\Program Files\Sandcastle\ProductionTools\BuildAssembler.exe" /config:"C:\Program Files\Sandcastle\Presentation\vs2005\Configuration\sandcastle.config" manifest.xml

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\ReflectionToChmProject.xsl" reflection.xml /out:Output\test.hhp

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\createvstoc.xsl" reflection.xml /out:toc.xml

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\TocToChmContents.xsl" toc.xml /out:Output\test.hhc

"C:\Program Files\Sandcastle\ProductionTools\XslTransform.exe" /xsl:"C:\Program Files\Sandcastle\ProductionTransforms\ReflectionToChmIndex.xsl" reflection.xml /out:Output\test.hhk

"C:\Program Files\HTML Help Workshop\hhc.exe" output\test.hhp
pause


The only change you would then need for this script is to put the names of the DLL's you actually want to document (ie replace alpha.dll beta.dll gamma.dll with your dll(s))... you may want to do this before running the batch file ;)

Copy and paste the script below into a text file make the dll name change on the first line sand save it as a batch file eg "documentation.bat". Save it in the same folder as your dll's and run it (click it).

This will give you an ultra generic help file, ala visual studio 2005 and all the rubbish .net 2.0 help files when it first came out.
I personally played with the xsl file to add in images etc to customise it a bit. i'm sure there are better ways to do it but i'm not spending any more time on some thing that i doubt anyone will ever read.
If you want them all spruced up, you probably want to check out the tools mentioned above.

EDIT: Sorry I fogot to mention that I dont name all of my XML Comment files "comments.xml"!
I usually name them the same as my dll's with an xml extension eg alpha.dll has the comment file alpha.xml. This means I had to make a change in the sandcastle config file ("C:\Program Files\Sandcastle\Presentation\vs2005\configuration\sandcastle.config" in my case) line 63 from
<data files=".\comments.xml" / >
to
< data files=".\*.xml" />
to allow for all of the xml files to be a part of the help (which is what you really want now isn't it!).
Just make sure there are only comment XML files (ie no other data xml files) in the directory or i guess it could go pear shaped. Alternatively perhaps name them *.dll.xml and use that as the data file filter.
EDIT 2:
To change the lines at the top
& bottom of the main pages
[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]
&

Send comments about this topic to Microsoft.

Edit the shared_content.xml file found below.
C:\Program Files\Sandcastle\Presentation\*\Content\shared_content.xml

Wednesday, May 2, 2007

The eternal fight

It seems like there is always the eternal struggle between dev's and the "non Dev's". You know what i am talking about.
BA's who give innaccurate or incredibly loose requirements yet want you to build a something exactly how they or the customer want it...
PM's who want you to do something that will take 5 weeks to do it in 1 and after you pull uber over time to finish it they then think they were right, it did only take 1 week... and it your fault that it hasnt been tested properly or fully completed...
Sales people who promise the earth and have no idea what nightmares they are putting the team into.... etc etc

And poor old us. The developer gets to shoulder the brunt of it... well so we think. A couple of things happened today that got me thinking, if the average Dev could properly comunicate then alot of these issues could be reduced. Firstly if there is a technical person who will be directly involved in the dev at the time of scope to check everything is on the right track... that may help (in the last 12 months I have been gob smacked how often this doesn't happen). Hell, if the techincal person is presentable and articulate, let him/her come to the scope meetings or be involved in the sales process. Gee that sounds good! In my mind this is a double win, if handled properly. Then the major dev issues come up early, and if they dont, then it was missed by the dev anyway who can no longer point the finger.
Also picking your battles is always something we should be aware of. If you bitch and moan about everything, when i comes to a major issue the PM (or whoever) will just roll their eye's as if to say 'not this again'. Help the non devs to understand the business reason behind your arguement (delivery times & budgets are always good), after all you are suposed to be on the same side!
Its not all doom and gloom. I have been lucky enough to work with great teams such as Neotek, where although conversations got heated, they never got personal and it was always with the intent of making the code, product of processes better. Also the team i work with at Change are a very smart bunch for very different backgrounds where i would like to think we asa collective are learning alot from the others in the team (well I am!).
In short, just because you are a developer doesn't mean you have to be a nerd. Getting people on side with you early on is a big help when things get tight at the tail end of projects (or even just iterations!).

sorry just a bunch of random thoughts, but i thought i would throw them out. :)

Rhino Mocks

CDS showed me a cool new tool today called Rhino Mocks. I have never used mocks before so was impressed nonetheless. Its helping make unit test actual unit test and not block of code that hit DB's or file systems or this, that and the next thing (check out Micheal Feathers post re unit test rules here).
One of the coolest thing is it is written by an up and coming software geek who is only 24 and has a healthy list of accomplishments already. Check out the work of Oren Eini (AKA Ayende Rahien) here

Bread crumbs... again

..so i am left felling silly, while SteveE has used his brain and looked at the guts of the the breadcrumb control and sitemap with Reflector and built a system that not only works but hopefully works well and in MOSS 2007. I feel dumb. Oh well.

Tuesday, April 24, 2007

"Catch all the exceptions, ALL OF THEM!!!"

"Catch all the exceptions, ALL OF THEM!!!" were the words that ran thru my head as a saw the dreaded
..catch(Exception)
{}...

WTF??!?!

a)Why would you ever catch all exceptions? You should know what exceptions are coming back at you catch specific ones and deal with them appropriately. The only* time I could ever see this being usefull is for logging purposes...
b)Dont hide exceptions... deal with them. Catch exceptions and doing nothing is pretty rank... at least comment the hell out of why you are doing it.
c)Get FXcop or some tool that tells you when there is rubbish code in your solution!

*OK there is probably a few areas, but not as many as some would think...

Friday, April 20, 2007

MVC and Building User controls (Specifically .Net ASCX files).

MVC and Building User control's (Specifically .Net ASCX files).

User Controls are a common way to develop reusable UI components that use a common layout or have common generic functionality. Unfortunately I so often see these controls being developed, in my mind, incorrectly. User controls should generally be dumb. They should know very little of the out side world (except of course of the namespaces they inherit from and maybe utility classes that perform common public static encapsulated method calls). Think text boxes, drop down lists etc. These don't know about your business objects! You passed in and retrieve properties from them. They may do some basic processing however this is generic. They should certainly never call or run business logic or know about services. So how do we use User Controls to run common logic? On the user control there should be publicly visible properties. This is usually a given. There can also be methods and events. Often I call a PopulateControl(Type type) (which is a public void Method) that takes in a control specific DTO (or collection of DTO's). Usually this merely passes each of the properties in the DTO to the properties in the Control. Right, so data is in the control, how do we do stuff with it? The page load may have some generic code, but avoid adding smarts that are too specific. How about passing data back to the parent? Either retrieve the data from a MyDto read only property the does the exact opposite of the populate control returning a DTO or create a custom event eg Save and pass a delegate into the control. Yes this mean code stays on the page. So?? If it commonly called create a class that does all the leg work for you that all page can call. This then follows the MVC pattern and separates the visual aspect from the Data aspects

Question: why do you use PopulateControl(Type type) and RetrieveDTO() and not properties? Answer: I am of the opinion that a property should never be able to throw an exception or call code that can throw an exception. If you are confident that this can not happen then, sure, use the property approach. However, if there is functionality that may cause an exception, then use the method approach. I wouldn't expect people to strictly follow this, this is just my preference.

Question: When to use Delegates? Answer: When it is obvious that this control does something, like its is a control that has customer details for adding or editing then a save delete and cancel buttons may be appropriate. Control of what is done on the User Control (usually the page) with the event (ie EditCustomer_OnSave()) means that page can pass in the correct logic or call to the manager of logic as a delegate. Obviously this means exposing something to apply the delegate to, such as an event!

I am more than happy for feed back on this. I want to do better code, you may be able to help!