Archive for the '.NET 3.5' Category

05FebRuby <3 .NET – Alt.NET Italy presentation

2 weeks ago I had the chance to [talk to the Italian Alt.NET community about IronRuby](http://flanders.co.nz/2009/01/25/participating-in-the-italian-altnet-user-group/). I’m pretty excited about the Ruby language and I try to convey that enthusiasm onto my victims. From the talks I had afterwards it looks like I was able to infect at least one or two enough to make them go home and download IronRuby to have a play. It is the very first time that I get to see one of my presentations myself because this one got taped and put online.

Continue reading ‘Ruby <3 .NET – Alt.NET Italy presentation’

25JanCreated a basic integration for IronRuby and Asp.NET MVC

As I can see the end of the chapter on Rails and I’m looking ahead to see what will be next. I decided to start working on the chapter that talks about using IronRuby with Asp.NET MVC next. [Jimmy Schementi](http://blog.jimmy.schementi.com/) and [Phil Haack](http://haacked.com/) created a proof of concept implementation a couple of months ago that actually did work.
The past weekend I’ve been looking to build on the excellent work they did and to build a more complete integration. In this post I’ll try to explain what I did to make it work. The integration work is far from complete, so if you’ve got some free time on your hands and you happen to be looking for an Open Source project to help with then this could be a candidate for you :) .

Continue reading ‘Created a basic integration for IronRuby and Asp.NET MVC’

25JanParticipating in the Italian Alt.NET user group

I just finished my talk at the Italian [Alt.NET conference](http://ugialt.net).
There were the following topics of discussion:

  • Domain Driven Design
  • User stories & planning game
  • Advanced Unit Testing in the real world
  • Acceptance testing (Fitness)

And of course my topic was [IronRuby](http://ironruby.net)

Continue reading ‘Participating in the Italian Alt.NET user group’

23OctBeating a dead horse: Stored Procedures

I seem to be having the same conversations with the dev teams whenever I switch clients. The topic of this post is one that many people have written about before. I’m just going to put my opinion on my blog so I can refer people to it in the future instead of having to repeat myself every time.
What prompted this post is that since I’ve moved to Belgium I’ve had to take a step back from living on the bleeding edge and using open source projects. Most of the work is concentrated in Brussels and is at big corporates or banks not exactly what you’d see as the progressive thinkers (with reason).
I guess it would be safe to say that I’ve been immersed in “enterprise” development. In short I still haven’t seen anything that is more complicated than a web app like [Xero](http://www.xero.com). But perhaps more about that in another post. This one is about stored procedures and their valid uses.

Continue reading ‘Beating a dead horse: Stored Procedures’

01OctCommon mistakes in software development (part 2): Mixing up the tiers

In my [previous post](http://flanders.co.nz/2008/09/24/common-mistakes-in-software-development/) I explained some very quick wins to make your code a little bit cleaner. As I’ve been appointed an [asp.net](http://www.asp.net) project at work at the moment I have the chance to get more ammunition for blogging :) .
This time I’d like to talk about properly separating your tiers so that the next person doesn’t have to go through the complete application and make changes everywhere just to make a minor change to the application.

One of the problems; one of the most time consuming that is; I’ve seen is that people are confused on what they have to put in the data logic layer and what is business logic. In my case this is fairly extreme because there isn’t an ORM tool but rather every entity gets populated by calling a stored procedure and then in the code the graph objects get set. Whether this is a good approach for fetching your data or not is not within the scope of this blog post, but I’m guessing there are more people who are facing this type of situation.

Anyway let’s start with the beginning and explain the typical [n-tier architecture](http://en.wikipedia.org/wiki/N-tier) people seem to follow. This is not a particular pattern like [MVC](http://en.wikipedia.org/wiki/Model-view-controller) or [MVP](http://en.wikipedia.org/wiki/Model-view-presenter) that people are talking about so much lately. This goes back to the guidance that can be found on the [msdn website](http://msdn.microsoft.com). This type of architecture is often used in combination with data sets but not in my example for this post. This architecture is generally divided in 3 parts that can, but don’t have to, run on different machines if needs be. When talking about this type of architecture people mostly talk about an n-tier application.

##The first part is the data layer (tier).
The golden rule for this one: this is the gateway between the rest of your application and the database. **NONE** of the other layers should be talking directly to the database but instead should be doing their talking through this layer. That means if you have stored procedures you provide wrappers for them in this layer. You populate your entities in this layer too.
Other functions you can perform in this layer is setting the graph members (populating relationships). IMHO if you’re talking to the database (open/close connection) you’re doing stuff that belongs in the data layer which includes populating relationships.

Encapsulating this logic in it’s own layer, which could potentially be walled off through only exposing it with remoting or WCF, allows you to reuse the code in different places of your applications or sharing this data access assembly with multiple applications.

##The second part is the business logic layer (tier).
This layer encapsulates all the operations you do on entities to express the business rules. That means you would probably do most of your work in this layer. Basically **all** of the programming you will be doing for the business rules should be done here. Business logic doesn’t live in stored procedures, it doesn’t live in the UI or the data layer. Nope this layer is where it lives and nowhere else. This statement may raise some eyebrows but only and only when you find that a certain routine is a bottleneck and it is really data intensive you can put it in a stored procedure but more on that subject in another blog post.
If you find yourself transforming data so you can display it in your GUI then you’re probably expressing business rules that aren’t explicitly stated as a business rule.
When you find yourself to be concatenating strings or writing logic to translate your pages in your GUI layer then you’re probably expressing business logic (business logic doesn’t have to come from business ;) in case that wasn’t clear).
Another common find in business logic is validation for example because this generally expresses some kind of strict rule that comes from the business domain your application deals with. Validation is a tricky one but the rule is you should do **all** validation in your business logic. To provide a better user experience you can maybe reuse that validation on the client side. In the case of web development you probably will have to duplicate that validation in javascript if you really need it.

Separating these rules into their own layer allows you to reuse the methods and classes you create in the business logic layer, in different parts of your UI or even reuse it in different applications.
By separating this logic it should be easier for you to do some automated testing like unit testing and/or integration testing of that code.

##The third and last layer (tier)
This is typically the UI layer but you could easily use web/WCF services as an interface to your logic. The UI doesn’t have to be a GUI it can also be a CLI (Command-Line Interface) or something. But that is how you interact with the user or external application. The idea is that in this layer you have virtually no logic except for what’s on the screen **everything** else should be handled by your business logic. To clarify this statement: you can show/hide UI elements or add/remove elements to the UI and respond to events triggered by user actions but the data of that response and the processing really belongs in the business logic layer.

The UI layer can talk to both the business logic and data logic layers. If for example you’re getting a category list with just an id and name from the database chances are you won’t need to transform that data so your UI can bind directly to the entities returned by your data layer. But more complex items like an invoice for example will probably need some processing and then it should probably pass through the business logic layer.

This is typically a somewhat harder part of your application to provide tests for although there are some libraries out there that make it easier but still there are easier parts to test in your application.

So that was a quick refresher on what the classic n-tier architecture is about an how it should be structured. I hope you will agree with me into stating that its not that hard and pretty straight-forward to implement, but what I find in the “enterprise” is far from the points mentioned above.
It is a bloody mix of everything everywhere, leaving me thinking -come on guys it’s not that hard-:
*talking to the database => datalayer*
*showing windows/adding UI elements,… => UI layer*
*everything else => business logic*

Failing to abide by the previous simple rules will result in hell freezing over, entire plagues will be released upon the world; to cut a long story short: the world as you know it will seize to exist and turn into complete chaos.
Following the rules should result in less code duplication, an instantaneously easier to maintain codebase and probably more happy successors for when you move on to the next project. It should also give you a higher degree of code reuse.
If there is one thing you should take away from this article then it should be:
**Don’t mix your tiers**

Of course there are a couple of situations when you can diverge from the ideas presented in this post but you should always be able to justify why you break the rule. So you need a good reason to break the proposed architecture and that would probably also warrant a comment so the next guy also knows what’s going on.
The most important part is to separate all non-UI logic out from the UI layer and put it in one of the lower layers.

Thanks for reading
Ivan – writing for more maintainable software -

24SepCommon mistakes in software development

***** Rant Alert ******

<rant>

At my current client I’ve got to do mainly maintenance on existing applications. This gives me the chance to look into codebases that have been created by other people and that don’t really reflect how I would write things. That is all good though it gives me a chance to learn new ways of doing things and when I think their way is better I’ll surely adopt.

Anyway when I’m browsing these codebases I do find a lot of things that could have been done better or more correctly and that’s what I’ll be writing about a little today.

The first one is returning bools:

I’ve found this in just about every project I’ve been in:

public bool IsNull(){
  if(obj == null)
    return true;
  else
    return false;
}

The snippet above is a very long winded way of writing. IMHO this hurts readability and you’re saying the same thing twice. obj == null already returns a bool it makes no sense writing it again.

public bool IsNull() { return obj == null; }

Another thing I keep seeing is very liberal use of try..catch blocks that catch all exceptions. Admittedly try..catch is cool but it should be used at times you are actually interested in the exception that is thrown. But it shouldn’t be used as a safeguard to swallow exceptions you don’t want to fix at this moment.  I keep seeing this code in projects:

try{
  myBLObject.FindSomething(someId).SomeMethod();
}
catch(Exception){
// Nothing to be done but error stops
}

Now that can be easily written so that it won’t throw an exeption and then the try catch isn’t necessary anymore at all. Try..catch blocks most certainly have their use but throwing and catching exceptions definitely hurts performance because the system has to generate a complete stack trace etc. for every exception that is being thrown.

var result = myBLObject.FindSomething(someId);
if(result != null) result.SomeMethod();

The code becomes a lot more readable, not to mention faster. I’ve seen this being used in OnRowDataBound events etc on grids with 500+ rows, removing the try catch blocks more than doubles the speed of that page.

The next one on the list is using if,else and switch statements. They are sometimes a cause of code bloat. To put it in the words of Scott Hanselman:

I think that using only if, for and switch is the Computer Programmer equivalent of using “like” in every sentence.

Scott does a great job explaining why they can be pretty evil so I’ll just leave you with a link to his post

I have another couple of posts in the making on this subject but I had to get this out of my system. These are also very quick wins the other things I’m going to talk about are application architecture and stored procs….
</rant>

07AugIronNails : Rails like development for IronRuby with WPF/Silverlight

For my book IronRuby I’m working on chapter 4. That chapter is about doing WPF development with IronRuby. I started out with a straight port of Witty to IronRuby. As I was doing that the cogs started turning and I came up with a way to bring the rails style of development to WPF.   I decided to investigate that route a little bit further and now I have a small framework that enables you to write WPF applications with the MVC paradigm. I decided to open that code up as open source and host it on github. 

At first I used the name Sails for my framework but it turns out there is java clone of rails that is called opensails. So to avoid confusion David M. Peterson proposed the name IronNails.

On Sat, 02 Aug 2008 08:00:44 -0600, Charles Oliver Nutter wrote:

    FYI, there’s already a framework named "Sails" for Java:
http://www.opensails.org/

For the sake of sticking to the "Iron" theme, why not replace the ‘S’ with an ‘N’ and go with IronNails. ;-)   Maybed it’s just me, but if given the choice, I’d much rather nail it than sail it any day of the week. :D


/M:D

M. David Peterson

You can find the project here: http://github.com/casualjim/ironnails

At this moment it’s definitely not finished at all, but it does work. The remainder of the week I’ll move my previous demo code onto this framework, update the code samples in my chapter and finish the content. I hope I will have all of this done by the end of next week.

Back to the IronNails project:

Because DLR objects cannot be used to bind to in WPF you have to define a skeleton of the ViewModel in C#, but this will change in the future. When that changes I’ll look at extending the framework to make use of some other WPF patterns like defining a DependencyObject and Behaviors. Once those are defined you get a very clean separation between design and behavior.

This is abstracted away from you but in the background the framework works with the View – ViewModel – Model – Controller pattern although I’ve tried to keep your exposure to the view model to a minimum. The framework follows naming conventions per language. So in C# and XAML you camel case stuff and in IronRuby you underscore stuff.

The very core of the framework is defined in C# but most of the code is IronRuby, depending on how hard it will be after the DLR RTM’s I may look at adding support for all the DLR languages.

IronNails
=========

IronNails is a framework inspired by the Rails and rucola frameworks. It offers a rails-like way of developing
applications with IronRuby and Windows Presentation Foundation (WPF).
This framework uses the pattern Model – ViewModel – View – Controller (M-VM-V-C). It should be able to run on both WPF
and Silverlight.
The idea is that the views can be created using a design tool like Blend for example and just save that xaml as is. The
designer should not need to use anything else than drag and drop to create a GUI design. The behaviors are then added to
the view by using predefined behaviors in the framework or by defining your own behavior.
The framework then generates a proxy for the view which will be used to transparently wire up the commands in the
behaviors to controller actions.

You are now able to write the following code for a controller:

class MyController < IronNails::Controller::Base

  view_action :show_message, :triggers => :my_button do
    MessageBox.show "This is the great message from a block"
  end

  view_action :change_color, :triggers => { :element => :my_text_block, :event => :mouse_enter }
  view_action :reset_color, :triggers => { :element => :my_text_block, :event => :mouse_leave } do |view|
    view.my_text_block.foreground = :black.to_brush
  end

  view_object :people, Person.find_all

  def change_color(view)
    view.my_text_block.foreground = :red.to_brush
  end

end

At this moment the project has 0 unit tests, it has below minimal documentation and it still needs a work like defining the behaviors. I have to move on with my book but intend to continue developing this framework after my book is finished and IronRuby RTM’s.  There are some more workarounds in the project that will all disappear as IronRuby progresses.

kick it on DotNetKicks.com

17AprNinject: Getting all the stuff you’ll need

I have a new project I started and I could reevaluate my toolset :) I decided to take a closer look at Ninject, Moq and NSpecifyMoq has been talked about enough I think, a really nice way of mocking and I will definitely be using more of it. My original plan was to write one big blog post.. but it is going to be far too long, so I’m breaking it up in smaller bite size pieces.

What I did was download the code, have it rest on my pc for about a week, updated again when I really got round to using it. I read the wiki which gives a short introduction on what’s what in Ninject and everybodies jobs. Decided that the wiki was cool for some more theoretical knowledge but I really needed to see more code.

I opened the project and something rare happened: I was actually very happy with the code I found, not always the case I can tell you ;) .  Anyway the gold is in the unit tests, it’s got great test coverage and it shows lots of the possibilities of Ninject. It’s like a great big manual for you to get really advanced with it really quickly.  I was slightly disappointed to see that there was no NLog support for Ninject, that disappointment quickly turned in to joy when I figured out it only took me 20 minutes to plug NLog in. And it was added to the trunk the same day.

Now I don’t want to make this post about which DI framework is better Windsor, Spring, Structuremap or Ninject. I just know that Ninject and I will become good friends over the next couple of months I like it. Ninject outsources its proxy generation to either Castle’s DynamicProxy2 or to LinFu DynamicProxy.  LinFu seemed like an interesting choice after reading this codeproject article. It’s supposedly faster than castle’s dynamic proxy. Luckily Ayende is there to put this in perspective. And I can confirm that the error messages etc castle’s dynamic proxy generates are a lot more useful than LinFu.

Screenshot - LinFuGraph.png

Anyway I’m using LinFu at the moment as the proxy generator for Ninject. I will walk you through a sample application I built that will deal with the following subjects of Ninject, Lightspeed and NLog. For Ninject we will use the dependency injection and it’s interceptor possibilities to implement AOP style logging. For Lightspeed we will create our own logger to plug into the context so that we can log what Lightspeed does too. And we want NLog to log through Lightspeed to our database so we’ll be creating a custom target for NLog as well.

But let’s start at the beginning doing DI with Ninject :) .

The most important thing to remember: MAKE YOUR METHODS VIRTUAL. Once again make your methods virtual otherwise Ninject has a hard time generating proxies for your classes.

Ninject is different from most other DI Containers in that it doesn’t have XML-configuration, its configuration is done through code (wouldn’t be hard to add an XML configuration for it tho but what’s the point). No XML ?? Suits me fine, everybody that ever worked with me will agree : Ivan no like XML editing.  Ninject takes a modular approach by using modules that you pass to a kernel. This is pretty nice that means that an assembly can have a couple of different sets of Modules and all the caller of that assembly needs to do is add the module with the appropriate configuration to their kernel.

Ninject supports DI on constructors, properties, methods and fields: http://dojo.ninject.org/wiki/display/NINJECT/Injection+Patterns.
It basically boils down to decorating the item you want to inject with the attribute [Inject]

Ninject allows you to do a lot of configuration through the use of attributes. But I think I’ll leave it at that for today and continue this tomorrow.
Let’s look at a concrete class from what we’ve seen so far. The class below is the Logger implementation to plug into the LightSpeedContext. We will finish this later on but for now this will be enough to summarize today’s post.

using Ninject.Core;
using Ninject.Core.Logging;

using ILightSpeedLogger = Mindscape.LightSpeed.Logging.ILogger;
using INinjectLogger = Ninject.Core.Logging.ILogger;

namespace LoggingDemo.UI.Integration
{
///
/// This class intercepts logging messages from the LightSpeed context and
/// sends them to our NLog logger.
///
public class LightSpeedLogger : ILightSpeedLogger
{
private readonly INinjectLogger logger = NullLogger.Instance;

public LightSpeedLogger()
{
}

[Inject]
public LightSpeedLogger(INinjectLogger logger)
{
this.logger = logger;
}

#region ILogger Members

public virtual void LogSql(object sql)
{
logger.Info(sql.ToString());
}

public virtual void LogDebug(object text)
{
logger.Debug(text.ToString());
}

#endregion
}
}

Let me know what you think :)

kick it on DotNetKicks.com

27FebConsuming YouTube using XLinq

I had to implement an integration with youtube for a client yesterday. Google provides API’s but they are for Java and PHP. I’m using C# for this project. So I decided to use XLinq to fetch the feeds and parse them into classes for what I needed.

I only need titles, movies and a thumbnail for each item. So I haven’t implemented all of the properties. And I am impressed. From having no exposure to XLinq whatsoever to having it parse feeds and being able to use those feeds in my monorail application took me about an hour. Since this is the very first time I use XLinq I imagine there is room for improvement, please tell me so when I’m wrong.

The classes I show here can be used as follows:

YouTubePlayList.LoadForUser("<>").ForEach(pl => Response.Write("" + pl.Id + ""));

var url = http://gdata.youtube.com/feeds/api/playlists/<
;
YouTubeCollection.LoadFrom(url).ForEach(yt => Response.Write(yt.Title + ", " + yt.MovieUrl + ""));

public class YouTubeCollection : List
    {
        public YouTubeCollection()
        {
        }

        public YouTubeCollection(IEnumerable collection)
            : base(collection)
        {
        }

        public static YouTubeCollection LoadFrom(string uri)
        {
            var feed = XElement.Load(uri);

            XNamespace ns = "http://www.w3.org/2005/Atom";
            XNamespace media = "http://search.yahoo.com/mrss/";

            var list = new YouTubeCollection(from item in feed.Elements(ns + "entry").Elements(media + "group")
                        select new YouTubeItem
                        {
                            Title = item.Element(media + "title").Value,
                            MovieUrl = (from el in item.Elements(media + "content")
                                     where el.Attribute("type").Value == "application/x-shockwave-flash"
                                     select el.Attribute("url").Value).First(),
                             ThumbnailUrl = (from el in item.Elements(media + "thumbnail")
                                             select el.Attribute("url").Value).First()
                        });

            return list;
        }

    }

    public class YouTubePlayList : List
    {
        public YouTubePlayList()
        {
        }

        public YouTubePlayList(IEnumerable collection) : base(collection)
        {
        }

        public static YouTubePlayList LoadForUser(string user)
        {
            var url = string.Format("http://gdata.youtube.com/feeds/api/users/{0}/playlists", user);

            var feed = XElement.Load(url);

            XNamespace ns = "http://www.w3.org/2005/Atom";
            XNamespace gd = "http://schemas.google.com/g/2005";

            var list = new YouTubePlayList(from item in feed.Elements(ns + "entry")
                                           select new YouTubePlayListItem
                                             {
                                                 Name = item.Element(ns + "title").Value,
                                                 Id = item.Element(gd + "feedLink").Attribute("href").Value
                                             });

            return list;
        }
    }

    [DataContract]
    public class YouTubePlayListItem
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Id { get; set; }
    }

    [DataContract]
    public class YouTubeItem
    {
        private string _id;
        [DataMember]
        public string Id
        {
            get
            {
                return MovieUrl.Split('/').Last();
            }
            set
            {
                _id = value;
            }
        }

        [DataMember]
        public string Title { get; set; }

        [DataMember]
        public string MovieUrl { get; set; }

        [DataMember]
        public string ThumbnailUrl { get; set; }
    }

 

Technorati Tags: ,

05FebCompiling Mono and IronRuby on OSX Leopard

I tried to compile IronRuby on OS X (leopard) with the dmg I downloaded from the mono website, and that didn’t work.

I then uninstalled that mono version by running monoUninstall.sh and proceeded to get mono from subversion. I’m putting these steps on my blog more for future reference when I decide to reinstall my box for some reason.

Download gettext, pkgconfig and glib2.0

extract the archives and build them in the following order gettext, pkgconfig, glib2.0

./configure –prefix=/opt/local
make
sudo make install

At this point it would be wise to set the PKG_CONFIG_PATH environment variable. I added the following line to ~/.bash_profile

export PKG_CONFIG_PATH=”/usr/local/lib/pkgconfig:/opt/local/lib/pkgconfig”

next it’s time to check out the mono sources from their repositories

cd ~/
mkdir tools
mkdir mono
svn co svn://anonsvn.mono-project.com/source/trunk/mono
svn co svn://anonsvn.mono-project.com/source/trunk/mcs
svn co svn://anonsvn.mono-project.com/source/trunk/libgdiplus
svn co svn://anonsvn.mono-project.com/source/trunk/moon
svn co svn://anonsvn.mono-project.com/source/trunk/olive
svn co svn://anonsvn.mono-project.com/source/trunk/gtk-sharp

checking those out will take a while

now go into the mono directory and build mono

cd mono
./autogen.sh –prefix=/opt/local/mono –with-preview=yes –with-moonlight=yes

–with-preview enables the .NET 3.5 features that have been implemented so far
–with-moonlight enables support for moonlight

make
sudo make install

This will also take some time and when it completes you can check if mono is installed by typing mono -V

That’s it for mono, now onto IronRuby

cd ~/tools

svn co http://ironruby.rubyforge.org/svn/trunk ironruby

sudo gem install pathname2

rake compile mono=1

And that should be all :)

UPDATE: I’ve got new instructions for building IronRuby


Recent Flickrs

    Blogroll

    Recent Listening

    Scrobbler