Archive for the ‘Tips’ Category
Hello Open Rasta
So Ryan, the apostle of everything on the web, has been spreading the gospel of Open Rasta for months. Tonight I decided that finally, I should download and give this fantastical framework a shot.
For an explanation on what OpenRasta is and is not, I shall direct you to their sites:
What I am going to do is just describe my experience trying their framework for the first time.
I am a person that likes to learn by trying so I immediately jumped to the ‘creating your first OpenRasta website’ (here). I have looked at some of Ryan’s code and have survived several conversations with Ryan over the framework.
I believe that is enough preparation for at least a simple tutorial.
Well I go to the modifying the web.config section and was left with a broken solution. Apparently from the time the tutorial was written and the time I downloaded the version 2.0.2039.312, the handlers and modules all moved to another assembly. I had a gut feeling it moved and when I talked to Ryan, he confirmed my suspicions. Supposedly he is going to try and update the tutorial.
In the meantime, just change …."OpenRasta.Web.OpenRastaHandler, OpenRasta"
to… "OpenRasta.Hosting.AspNet.OpenRastaHandler, OpenRasta.Hosting.AspNet"
So change the assembly reference from the OpenRasta.dll to the OpenRasta.Hosting.AspNet.dll
I assume if you are reading this you have the skill set to modify said correction for the other references.
After that I breezed through the creation of the ‘Home’ resource and the ‘Home’ handler. No duh? Any programmer can make a couple of classes.
I’m at the configuration section and I have to say, I love the fluent interface. Anyone who has talked to me in the past 6 months knows I love the pattern. It instantly makes any framework extremely approachable.
The tutorial has you making a manual configuration. I tried to find an auto configuration just using some intellisense with no luck. I will investigate this further. If I was going to use OpenRasta I would definitely want a convention based solution. Even with a nice fluent interface, I really don’t want to manually create all my mappings by hand.
But there is something to be said for simply creating a mapping like :
ResourceSpace.Has
.ResourcesOfType<Home>()
.AtUri("/home")
.HandledBy<HomeHandler>();
I ran the app expecting the 405 method error as the tutorial predicts.. and got an empty page. I was using FireFox, so I jumped over to IE and was then greeted by the 405 error. I assume FireFox is either handling the problem gracefully or I don’t have some settings setup to display these errors. /shrug
So then I created my ‘Get’ method on my HomeHandler. One of the things that did attract me to OpenRasta was the POCO handlers. I’ve grown to appreciate very clean code with some acceptable conventions. Just makes life easier. I can focus on the domain problem and not the intricacies of any given framework.
Most of this seemingly new re-invention of HTTP as ESB, REST, Atom.. etc is interesting in that its a reexamining of a technology we use all the time. I haven’t done web development in roughly 3 years. The majority of my experience is in smart client apps. That is just the way my career and projects played out for me. The websites I created were always very basic and probably crap if judged by web developer gurus.
Anyway.
We click links and magically we get a web page. We don’t really think much about it. Sort of like turning on a light switch or starting your car. We just expect things to work and don’t really worry about it. How many drivers can actually explain a combustion engine?
There is a lot going on in the background to make the web work. This new (new to me at least) area of development is leveraging the tech the way it was supposed to be used (if I am to believe the pioneers in this arena). A lot of this is a change of perspective. And with any change of perspective it can take awhile to make the transition.
After that side trip down my ramblings, we come back to me having a handler with a Get method. Now I have graduated to a 406 error (as expected by the tutorial).
I then created my view as the tutorial suggested. Now upon trying to fluently configure.. I ran into a snag. Again the tutorial is out dated (which is fine for an open source and still growing framework).
I had to add the “OpenRasta.Codecs.WebForms.dll” to the solution.
Also the fluent configuration suggested is…
ResourceSpace.Has.ResourcesOfType<Home>()
.AtUri("/home")
.HandledBy<HomeHandler>()
.AndRendededByAspx("~/Views/HomeView.aspx");
But since the AndRendededByAspx is obselete, the code should now be:
ResourceSpace.Has.ResourcesOfType<Home>()
.AtUri("/home")
.HandledBy<HomeHandler>()
.RenderedByAspx("~/Views/HomeView.aspx");
I then continued the tutorial until I had my Home View that displayed my lovely welcome message.
Yay! I got my first Open Rasta page to work.
Feel free to investigate my project at my Git Hub repository:
http://github.com/RookieOne/OpenRastaExperiment/tree/TutorialCompletion
I’m going to be continuing to change the master branch but the TutorialCompletion branch should remain unchanged.
SO check out OpenRasta and their (and my) tutorial. Its short and is a great window into viewing the web in a slightly different manner.
Thanks for your time!
YAGNI–Whose Definition of Simple?
I have read a lot about YAGNI lately, especially regarding TDD. The thing that keeps bugging me is the definition of “simple.” Who defines simple? For instance, wouldn’t static methods be simpler than building objects? You could then write more functionally. Or is that not simpler to you? If you follow command-query separation, wouldn’t building everything as either pure functions or commands be simplest? JB and I have found this set of patterns immensely easy to create and test of late, especially in comparison to the ever-increasing-in-complexity procedural/OO code in place before.
So I guess my question is this: Is it really so bad to start with some basic patterns that will let you refactor more easily? I think the desire to make things as simple as possible–especially when you know you will need it–can be a waste of time and a good way of getting bad code into your source.
I know I will hear it from the Agile community that I just don’t get it, but I think I do. I really like starting simple and keeping things in nice, bite-sized testable chunks. And yes, I’m still learning. However, without a consistent and meaningful definition of “simple,” we’re likely to end up with a follow-up movement of making things complex for the sake of extensibility again.
So what do you think: is CQS too complex a starting point, or is it a nice, “simple,” and testable approach for YAGNI?

Acase().for(patternType.FluentInterfaces).create()
When I was first exposed to the idea of fluent interfaces my response was… big flipping deal.
It wasn’t until I actively started using fluent interfaces in my code did I begin to see their power and elegance.
What is a fluent interface? Here is the obligatory link to wikipedia
In simple terms, its returning a type instead of void in order to achieve method chaining.
The end goal of the method chaining is to provide a more readable interface and code.
First, does it break the Law of Demeter?
Law of Demeter doesn’t equal the number of periods. I am of the opinion fluent interfaces do not violate the Law of Demeter.
What is LoD? Another link to wiki and here is a link to a stack overflow on this very subject!
To me, Law of Demeter is about restricting communication between objects.
A common violation of LoD (imho) is the exposure of a list property on an object. I believe this serves as a good example of LoD as well as being an example on how to make a fluent interface.
A Person object has a name and a list of friends.
1: public class Person
2: {
3: public string Name { get; set; }
4: public List<Person> Friends { get; set; }
5:
6: public Person()
7: {
8: Friends = new List<Person>();
9: }
10: }
I could then add friends by…
1: var roger = new Person{ Name="Roger" };
2: roger.Friends.Add(new Person { Name = "Eddie" });
3: roger.Friends.Add(new Person { Name = "Freddie" });
4: roger.Friends.Add(new Person { Name = "Gordie" });
Now this is pretty typical, so what’s the problem?
Well my code knows WAY too much about Person. I know it has a list of friends and if they change that list to say a dictionary, I am hosed.
Not only that, but poor Person class… people can add friends to his collection without him every knowing. What if some additional logic needs to be done when adding a friend?
What if the person wants to record the birth date of every friend so they can send out birthday cards? Person is SOL.
As for Law of Demeter, my code is using the Person object to communicate through to the List<Person>. I am exposing my code to changes in Person.
Let’s change Person to eliminate this problem.
1: public class Person2
2: {
3: public string Name { get; set; }
4: private readonly List<Person2> _friends;
5:
6: public Person2()
7: {
8: _friends = new List<Person2>();
9: }
10:
11: public void AddFriend(Person2 friend)
12: {
13: _friends.Add(friend);
14: }
15: }
Now the only way to add a friend is through Person. Yippie!
1: var roger2 = new Person2 {Name = "Roger"};
2: roger2.AddFriend(new Person2 { Name = "Eddie" });
3: roger2.AddFriend(new Person2 { Name = "Freddie" });
4: roger2.AddFriend(new Person2 { Name = "Gordie" });
If I wanted to make this a fluent interface all I would need to do is instead of returning void, return the Person class.
1: public class Person3
2: {
3: public string Name { get; set; }
4: private readonly List<Person3> _friends;
5:
6: public Person3()
7: {
8: _friends = new List<Person3>();
9: }
10:
11: public Person3 AddFriend(Person3 friend)
12: {
13: _friends.Add(friend);
14: return this;
15: }
16: }
Now I can do the same logic like…
1: var roger3 = new Person3 { Name = "Roger" }
2: .AddFriend(new Person3 { Name = "Eddie" })
3: .AddFriend(new Person3 { Name = "Freddie" })
4: .AddFriend(new Person3 { Name = "Gordie" });
That is pretty cool, but fluent interfaces really shine with the builder pattern.
This time around I want to force construction of a person through a builder and have the builder use a fluent interface. Notice my Person’s constructor and fields are private. I embed the builder class within the Person class so the builder has access to the constructor and fields. In this manner only my builder class has access to constructing a person. My builder can now act as an anti-corruption layer for Person.
1: public class Person4
2: {
3: private string _name;
4: private List<Person4> _friends;
5:
6: private Person4()
7: {
8: _friends = new List<Person4>();
9: }
10:
11: public Person4 AddFriend(Person4 friend)
12: {
13: _friends.Add(friend);
14: return this;
15: }
16:
17: public static PersonBuilder createAPerson()
18: {
19: return new PersonBuilder();
20: }
21:
22: public class PersonBuilder
23: {
24: private Person4 _person;
25: public PersonBuilder()
26: {
27: _person = new Person4();
28: }
29:
30: public PersonBuilder named(string name)
31: {
32: _person._name = name;
33: return this;
34: }
35:
36: public PersonBuilder withFriend(Person4 friend)
37: {
38: _person.AddFriend(friend);
39: return this;
40: }
41:
42: public PersonBuilder withaFriendNamed(string name)
43: {
44: var friend = createAPerson().named(name).finish();
45: _person.AddFriend(friend);
46: return this;
47: }
48:
49: public Person4 finish()
50: {
51: return _person;
52: }
53: }
54: }
Now to create Roger and his friends I do..
1: var roger4 = Person4.createAPerson()
2: .named("Roger")
3: .withaFriendNamed("Eddie")
4: .withaFriendNamed("Freddie")
5: .withaFriendNamed("Gordie")
6: .finish();
It’s a simple example but maybe it sparked some ideas on how to use fluent interfaces to chain methods and make your code more approachable to people without Computer Science degrees.
JB
Batch Updates and Deletes with LINQ to SQL
If you haven’t seen this already, you need to check it out. Terry Aney did an amazing job.
Repositories and Presentation
I recently came upon a question in the Domain Driven Design Yahoo! Groups asking whether or not the presentation layer should interact directly with repositories or through a method on the entity (domain model). Having just finished Nilsson’s Applying Domain Driven Design Patterns and (finally) getting my head around LINQ to SQL on my current project, I decided to weigh in on the matter.
As always, it depends. You can indeed allow the presentation layer to use the repository directly, just as you can allow the presentation layer to use a factory to create your entities. Your current implementation is something I started off with when I started trying to do DDD, and follows more of the Active Record pattern, as mentioned by another responder, thought Active Record, by definition, matches the database table field for field.
You have several options:
- Use your current approach. You’ll probably need to merge your repository and entity by using static methods and properties, though, which can make it messy, and I wouldn’t recommend it. That’s why I stopped using this approach, anyway.
- Add a validation mechanism to your repository to validate your entities or, if your entities validate themselves, report the entities’ validation before you save.
- If you really like the Save method on your entity and you use .NET or a dynamic language (not sure about other platforms), you can use extension methods to “add” a Save method that wraps a call to your repository. This is really option 2 with some syntactic sugar.
- BEST PRACTICE (?): Use a Unit of Work, such as LINQ to SQL’s DataContext, Entity Framework’s ObjectContext, or NHibernate’s / SubSonic 3′s ISession to manage transactions and repsoitories, then call SubmitChanges() through the unit of work.
The Unit of Work pattern can be a little hard to understand at first, but it is quite powerful and great for managing rollbacks (which are extremely difficult if you always wrap your unit of work/repositories in the entity methods).
For reference, try these links:
http://iridescence.no/post/ASPNET-MVC-DataContext-and-The-Unit-of-Work-Pattern.aspx
http://www.west-wind.com/weblog/posts/246222.aspx
For keeping LINQ to SQL and Entity Framework persistence ignorant (PI), see:
http://iancooper.spaces.live.com/blog/cns!844BD2811F9ABE9C!397.entry
http://code.msdn.microsoft.com/EFPocoAdapter
WPF DataBinding: Nullable Value Types
We recently ran into what appeared to be an inconsistency in WPF’s data binding. When you attempt to data bind to a nullable value type with a value of null, WPF appears to drop the binding. Using an identity converter and several other methods only told us what we already knew, so I did a little research this morning.
hortha posted a solution with examples to the MSDN Code Gallery that we tried this morning. His solution works beautifully. Several commenters noted that VS2008 SP1 is supposed to fix this without converters, but no one seems to have tried it.
WPF DataBinding: Refreshing from Source
WPF DataBinding is terrific and allows for very passive views and easy source object updates. However, triggering updates in the view based on changes in the source object can be a little tricky.
If you want to make sure changes to your source object are reflected in your view, your source object will need to implement INotifyPropertyChanged (see example). Yet just implementing this property will not necessarily update your bindings. If your source object includes collections, and you bind to properties in those collections, you can update the source property but will not get updates from the source property, even if it is of a type that implements INotifyPropertyChanged.
The above scenario is common with Linq to Sql when the entities are generated for you. Even tables with one-to-one mappings will be generated with lists–as SQL doesn’t have a way of representing one-to-one relationships–so be sure to edit your dbml accordingly in order to take advantage of binding to your source object’s properties. (You might also consider removing some relationships to remove issues with DataContext collisions when trying to set properties of one Linq entity to another.)
If you can’t fix the problem this way or want to display the collection and changes to the collection, you can always add an ObservableCollection to your PresentationModel or wrap the source object with another object that does use the ObservableCollection to display your collection.
Find a First/Last Row of Data Without Sub-Queries
Simple but effective–just follow the guidelines in this post. Performance is great, much better by far than using sub-queries. I found a marginal performance dip using this method versus the nine-fold performance hit using a sub-query.

