2007-07-06

slightly enhanced Higher-Level Abstractions on Enumerations

Andrei has some nice code to work with Enumerations and while showing it to the team today, I tried to chain calls like this:

      


        [Test]
        public void Can_Chain_Select_Collect_and_More() {
            bool satisfying = Enumerating.On(_array)
                .Select(IsEven)
                .Collect<string>(delegate(string input) { return input + "-" + input; })
                .AreAllSatisfying(Satisfies);
            Assert.IsTrue(satisfying);
        }
 
 
        private bool Satisfies(string obj) {
            return obj == "2-2" || obj == "4-4" || obj == "6-6";
        }
 
But this did not work :-( (To much C# 3.0 exposure I guess) because methods like Select and Collect return ICollection<T>. 
So I changed it. 
You can grab it here: Enumerating.Zip. Of course all praise to Andrei, all blame to me.
 
How did I do it?
Well I Just changed 
        ICollection<R> Collect<R>(Converter<T, R> convert);

        ICollection<R> Map<R>(Converter<T, R> convert);
        ICollection<T> Select(Predicate<T> satisfies);
        ICollection<T> FindAll(Predicate<T> satisfies);
        ICollection<T> Filter(Predicate<T> satisfies);
        ICollection<T> Reject(Predicate<T> satisfies);
        ICollection<R> SelectThenCollect<R>(Predicate<T> satisfies, Converter<T, R> converter);
        ICollection<T> Sort(Comparison<T> comparison);
to 
        IEnumerating<R> Collect<R>(Converter<T, R> convert);

        IEnumerating<R> Map<R>(Converter<T, R> convert);
        IEnumerating<T> Select(Predicate<T> satisfies);
        IEnumerating<T> FindAll(Predicate<T> satisfies);
        IEnumerating<T> Filter(Predicate<T> satisfies);
        IEnumerating<T> Reject(Predicate<T> satisfies);
        IEnumerating<R> SelectThenCollect<R>(Predicate<T> satisfies, Converter<T, R> converter);
        IEnumerating<T> Sort(Comparison<T> comparison);
 
So its possible to chain commands that return more than one thing. 
And I added 
        ICollection<T> ToCollection();

to make the tests work.
 
 

2007-06-27

Constructor Injected Dependency vs. Setter Injected Dependeny

Just a thought: I always felt more comfortable with CID than with SID, but that was really just a feeling. While I was reading some code, I realized that with CID there is no chance that a dependency will show up in the interface, because interfaces don't have constructors. So the dependencies of a service are much better hidden from the clients of the service.

Of course one could separate the service interface and dependency interface and I would do just that if I couldn't go with CID.

Which leads to another interesting topic: In what situations is CID not working?

Off the top of my head I can thing of the following situations:

  • Legacy Code: Obvious! You would be lucky if that stuff used Dependency Injection at all, so do not get greedy!
  • Cyclic Dependencies: That should be avoided anyway, right?
  • Optional Dependencies: Not really. I would rather inject a default implementation (e.g. something like a Null Object).

Right now I can't think up any more scenarios.

del.icio.us Tags: , ,

2007-06-20

One more R# shortcut I didn't know about

I do use the R# shortcut Ctrl+Alt+F for reformatting code very often. But the dialog that shows up then asking me to confirm options I have alredy set allways puts me off.

When listing all available shortcuts for my VS 2005 with this very neat script, I found

Ctrl+Shift+Alt+F

which is "SilentReformatCode".

BTW: Does anyone know what the EnableDaemon command is doing? (Ctrl+8)

2007-06-14

When it comes to NHibernate, dates are no fun!

I just stumbled on some nasty behavior. While preparing some presenation on mapping existing schemas with NHibernate, I was using a mapped version of Northwind to do some queries.

I queried all the Customers with all their orders. As usual I was doing this in a transaction and expected that nothing would have changed, so nothing would be written back to the db. Nevertheless an exception of the type Data.SqlTypes.SqlTypeException with the message "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.".

What had happend was this:

The Order contains a nullable column ShippingDate. I didn't map that column as a Nullable<DateTime> but just as DateTime. When NHibernate reads the row from the db, the value is null, and that's what the session remembers. When the Order object is rehydrated by NHibernate the ShippingDate is set to the value DateTime.MinValue. When the Session is synchronized with the db, NHibernate assumes that something has changed, because the currentState and the previousState are different and tries to update the row. Wich in turn fails, because DateTime.MinValue won't fit into a SqlServer datetime column.

I was lucky I could just inject my "StopHereForDebuggingInterceptor" into the session to look at what was happening. Mapping the Field as DateTime? solved the issue. I wonder if the descicion to map DBNull to DateTime.MinValue was a sound one.

Underscores are terible, but_I_still_use_them

I must admit, I get the creeps when I look at some code and see unterscores used all over the place. It's so old school to me. And it has been my (lame) excuse for a while for not digging deeper into the Ruby language.

But there is one place where underscores make sense: Naming your unit test methods! It is just good to write somthing like

When_user_enters_search_term_longer_than_three_characters_Presenter_fetches_matching_products

Unfortunately it is a PITA to type such as thing. Today I came accros a really good idea from Jean-Paul Boodhoo while watching a dnrTV screencast. He has build himself a Visual studio macro that just picks up the current selection and replaces every space with an underscore.

As I was sitting on the train while watching, there was no way of downloading this macro (and I'm not sure if it can be downloaded), so I had to role my own and here it is:

Sub MakeCompileableTestName()
    DTE.Find.FindWhat = " "
    DTE.Find.ReplaceWith = "_"
    DTE.Find.Target =
vsFindTarget.vsFindTargetCurrentDocumentSelection
    DTE.Find.MatchCase = False
    DTE.Find.MatchWholeWord = False
    DTE.Find.MatchInHiddenText = False
    DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
    DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
    DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
    DTE.Find.Execute()
End Sub

It seems to work nicely and I have assigned it to the Ctrl-Shift-Insert Keyboard shortcut.

Patrick Cauldwell's Blog - This I believe... the developer edition

I came just accros this on Scott Hanselman's Computer Zen: Patrick Cauldwell's Blog - This I believe... the developer edition. and I am about to discuss it right now with my team (the ones that are just picking up .NET development). I think that is a really good starting point.

2007-06-12

C# Regions Suck

The more I see of it, the more I firmly believe that C# regions are not a good thing - at least if the code has been written by some human.

I was just listening/watching a screencast about the CSLA Framework on dnrTV and Rocky and the other guy just drool about how cool regions are when looking at one of the CSLA example classes which has around 441 lines of code and 6 regions and 23 methods which do such diverse things like validation authorization, instance creation, data access, existence checking and even some so called business methods, that more or less are just getters and setters for the data behind an object.

Back to my heading: The regions in C# (not sure if there is such a thing for vb.net) are used to give some structure to a class that is doing to much. This seems very much like a GOD OBJECT that should be torn appart along the lines of the SINGLE RESPONSIBILITY PRINCIPLE in the first place. Using regions here is just window dressing.

Btw: The CSLA is doing some interessting things, but I still do not understand why it does those things so clumsily.

The following code shows an example of how CSLA is checking that the current user can read a data value from an object.

public object SomeProperty {
  get   {
    CanReadProperty(true);
    return _someProperty;
  }
}

So there's the security concern intermingled with the rest.

If the member where defined like this

public virtual object SomeProperty {
  get   {
     return _someProperty;
  }
}

it would be easy to have a decorator arround the object that is taking care of the authorization, so the security aspect would be out of the business code. If you used something like DynamicProxy , you could make the security aspect even generic (not like in Generics) by introducing an Interceptor that handles all the property access with the same logic, maybe using Attributes to declare who is allowed to access the data.

2007-06-07

For me its the end of the Gui Architectur Confusion! Presenter First rules

After reading about GUI architectures here and here and after being in a project where the GUI layer has been architected by a real architekt (as in "over 40 and over confident") into an unusable mess, I believe I've finally found the holy grail. For me it is at least. Look for yourself at this and make up your mind.

The even have a notion about what I have called The User as a Service every now and then.

What is the best thing about Presenter First, is that it not only takes into account architecture but also the actual develoment process and it is a perfect fit for TDD. And Presenter First seems to be a very good addition to DDD.

I came accros this by looking at the most unlikely place to find something that is so simple and so elegant and looks so feasible (not to mention that you can do it without software factories, domain specific languages, code generation (well the authors actually use some code generation but it is not needed), visual designers) at ARCast on Channel 9. They have two episodes

My advice
  • Read the papers
  • Listen to the podcasts
  • Look at the examples
  • Try it in your project
  • Be happy!

2007-05-31

Microsoft Surface

Microsoft Surface
Just incredible!
Look at Experiance Surface / The Possibilities
I came across it by way of http://www.sellsbrothers.com/

2007-05-12

Annoying TortoiseSVN Bug while Patching "The file ... was found twice!?!"

I've been fiddling arround with the trunk of with fit.net
(http://sourceforge.net/project/showfiles.php?group_id=167811) lately
and I keep my changes in Tortoise patches, so I can reaply them after an
update -- or at least that's what I planned to do. Yesterday I found an
ugly (and allready known) bug in Tortoise 1.4.3, Build 8645. When files
occure more than once in a patch, the error message "The file ... was
found twice!?!" appears. The only solution I've found is to remove the
duplicate entries from the path.

2007-05-09

Educating the Team II (follow up to >>It's harder than I thought<<)

After laying some groundwork to understand C# and a tiny bit of .NET I would like to go more hands on. As the requirements are not as far as they should be (remember: NO ON SITE CUSTMER YET) I was thinking of picking a playground scenario my self and take it over the hurdles.

Here are the things I would like to do in the order I intent to do them

  • Pick two features.
  • Define Acceptance Tests.
  • Implement Acceptance Tests with FIT (not Fitnesse - I don't see an easy way to manage it in revision control).
  • Set up Continuous Integration running the FIT Tests - which will be all red at that point.
  • Implement the features with automated developer tests.
  • Enhance the CI to do the actual build, test and the packaging.
  • Demo the result to the Management.
I would like to pick two features because the one feature I had in mind which we could use later on was Authentication and Authorization. As this is an infrastructure concern there is nothing to show off to the management later on. So I need to add a showcase scenario as well. For now lets say we manage some goods and only certain people are allowed to view the wholesale price and only some people are allowed to change our retail price .

So we will build some simple app that allows a user to enter, view, change, delete and query the goods. No fancy stuff. A good is described by its number, description, wholesale price, and retail price.

As the application we will build will be running as a SmartClient in a Windows environment, it makes sense to use integrated security. So if some user is logged on we just believe he is who Windows claims him to be. So this takes care of authentication. For authorization we would like to use memberships in Windows groups: You can print that really_secret_report only if you are a member of the ourapplication_ReportingLevel2 group. But there will be situations where integrated security will not work. There might be some customers that do not use a Windows Domain or there might be POS terminals which are used by more than one person without actually logging on as themselves. I've seen systems used in restaurants where the waiters were using some key - either a real key or something like a chip - to identify themselves on the terminal. If our application is running in such an environment we would like to switch our authentication and authorization provider.

And even if we would aim only for integrated security, we would like to keep our software decoupled from the actual implementation of the provider: It would be absolutely impossible to run either our unit tests nor out acceptance tests against a Windows domain providing the auth-info. There is no way we would be able to gain enough direct access to the Windows domain to set it up in the way we need it.

This is an ideal reason to introduce the team to the concepts of IoC and Testability. It pays to be able to switch implementations without affecting the application. It pays while developing because we can work in parallel on both features and can run tests for the app even if the auth-provider is under development. And it pays while in production because we can enhance our application to work in an environment that does not have integrated authentication.

Even if we are able to switch the auth-provider, the first implementation I expect to ship is the one for Windows integrated security. We will start to work on a module that handles the management of users and roles when we face the first environment where we need it. This defers the work on a user management module until some later time. No need to pay interest rates until then, no need to delay other features that are more important for the application and the vast majority of customers.

Please give your feedback...

2007-05-08

It's harder than I thought

So now it's the second day of my new project and there are more things to do that I have exspected.
These are the problems:

  • There no on site customer in sight
  • From the four people assigned to my project three are still working on the old product
People are new to
  • .NET
  • C#
  • Visual Studio 2005 (so they do not know about ReSharper or ViEmu)
  • Design Patterns
  • PoEAA
  • Source control
  • Automated builds
  • Continuous Integration
  • OO programming
  • Refactoring
  • Domain Driven Design (well, I didn't dare to ask)
  • Automated developer tests
  • Automated acceptance tests
  • IoC and containers
  • Layered architectures
  • O/RM
I could extend the list even more. This seems daunting. Every bit of knowledge I took for granted in my old project is just not there. So I have to start from scratch
 
Enough complaints. Here are the things I plan to get the team started.
  • Quick intro into VS 2005
  • Hands on: How to write Hello World in C#
  • Hands on: Hello World 2007: Greeting is comming from a ClassLibrary
  • Wrap up References: Binary, Project, COM, WebServices
  • C# 1 - Types: Classes, Interfaces, Enums, Structs || Value Types -- Reference Types || Build in Value Types
  • C# 2 - Statements: method call, if..else, Nested if statements, switch statment, goto, while loop, do..while loop, for loop, continue and break, block statement.
  • C# 3 - Operators: Assignment, +-*/, %, += -= *= /= %=, Prefix and Postfix ++ --, Relational == < <= > >= !=, Logical && || !, Short Circuit Evaluation, Ternary Operator ? :, Precedence of Operators
to be continued later...

2007-05-02

When the Iron Triangle becomes an Iron Rectangle

We usually speak of the Iron Triangle (aka Time, Resources, Features)
when it comes to software projects. More often than not this triangle
turns into a rectangle when you are working as a freelance consultant.
The people are not only hiring you to produce a certain amount of
features within a given time frame while using a certain amount of
resources, they expect you to train their internal staff on the way.
This can take some work and it will result in less features, or more
time or resources used.
In the past I often forgot to point that out to the people who are
hiring me. Thankfully my new assignment is mostly about knowledge
transfer, even if we will be developing useful software on the way.

Trying to Post via Email - Take 2

I usually write my emails in Outlook in a Text only format. Unfortunately Outlook seems to add line breaks after a fixed number of characters which screws up the layout of my blog posts.

Blogging via Email - Does it really work?

If you are reading this post you're a victim of my attempts to blog via
email.
You're asking why I am doing such nonsense. Well, I exspect to be
commuting for an hour every day by train for my new assignment. And I
will be offline while on the train, I want to be able to write down my
thoughts in my email client and send it off when I am online again.

2007-04-27

New Job

So after more than a month of searching I've found a new project. After having offers by the dozens to work as a coder (or rather a DARL) or even as a product specialist (I mention Sharepoint somewhere in my cv and was flodded with offers), I finally signed the contract for the project of my dreams.
Imagine the setting: There is a software company that is doing a lot of J2EE develoment. The only thing not J2EE is a team of 5 people who are maintaining an application written in VB6 that is out in the market. Now the company has decided that this application needs a rewrite and what is what is even more important: that the company must build some .NET muscle. So the hired me on a contract basis to work as a coach/architect/lead developer (maybe even evangelist) to lead the team in to the brave new world of .NET.
The gig starts in one week so I have some time to figure out how to make this happen.
I'll plan to write down in the blog what I intend to do and how it will turn out.

2007-03-29

Learning by Watching Good People Work

I am just watching Ayende Rahiens screencast Hibernating RhinoMocks and besides learning something about RhinoMocks I can learn how he works with Visual Studio and ReSharper.
Most of the time he is to quick for me to get it the first time I see what he is doing. But in a screencast you just stop the Media Player go back a bit and step through. Thats just a fantistic way to learn.

Update on "Lots of Projects in a Visual Studio 2005 Solution"

We have been using Resharper for quite a while now and for some solutions that are set up like I described earlier, ReSharper marks lots of types as "unknown".

So if you are using ReSharper (and you definitely should use it), the soltion I described is no solution at all.

Whos.amung.us?

whos online

Ralf"s shared items