Archive for the 'C#' Category

14MayIronRuby just got a mocking framework – kind of

As I mentioned in a previous post.  I started working on a small mocking framework. It has now progressed far enough to handle the most common mocking tasks.

Below I pasted the output of the integration tests for CLR interop.

when isolating CLR interfaces
- should work without expectations
- should work with an expectation with any arguments
- should work with an expectation getting different method call result
- should work for an assertion on a specific argument

when isolating CLR classes
- should work without expectations
- should work with an expectation for any arguments
- should work with an assertion for specific arguments
- should fail for an assertion with wrong arguments

when isolating CLR instances
- should work without expectations
- should work with an expectation for any arguments
- should fail for an assertion for specific arguments
- should allow to delegate the method call to the real instance (partial mock)

you will need bacon installed to run the specs. you should issue the command igem install bacon for that.

you can then install the caricature gem in ironruby by issueing

igem install caricature

To use it there are some examples in the file spec/integration_spec.rb


require 'rubygems'
require 'bacon'
require 'caricature'

ninja.when_told_to(:survive_attack_with).return(5) 

weapon.attack(ninja).should.equal 5 

ninja.was_told_to?(:survive_attack_with).with(:any).should.be.successful

There is a gotcha though, when you use it in a CLR class you’re bound to CLR rules and it only overrides the methods that are marked as virtual. We also can’t isolate static or sealed types at the moment.

I took the approach of doing away with the terminology of mocking and subbing and instead chose the much clearer Isolation. By default any method returns null or the default value of a value type. You can tell an isolation to return a specific value or raise an error etc.  Later on you can then assert if the method was actually called. 

This fits in better with the way you probably structure your tests.

I hope you like it.

You can find the source in my github account.

http://github.com/casualjim/caricature

15MarNinject knows a new trick

Earlier this week Nate already said that I was doing some work on Ninject, now I have it working :) .  Everything I’m about to talk about is currently in the master tree of the ninject github repository.  Getting IronRuby to play nice with Ninject was surprisingly easy :) ,

Continue reading ‘Ninject knows a new trick’

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’

22OctIf you ever wanted to play fur elise in the console

At work today we were playing around with the console.. here’s one of our experiments whilst creating a stoplight workflow (WF).

private static void FurElise()
        {
            Console.Beep(420, 200);
            Console.Beep(400, 200);
            Console.Beep(420, 200);
            Console.Beep(400, 200);
            Console.Beep(420, 200);
            Console.Beep(315, 200);
            Console.Beep(370, 200);
            Console.Beep(335, 200);
            Console.Beep(282, 600);
            Console.Beep(180, 200);
            Console.Beep(215, 200);
            Console.Beep(282, 200);
            Console.Beep(315, 600);
            Console.Beep(213, 200);
            Console.Beep(262, 200);
            Console.Beep(315, 200);
            Console.Beep(335, 600);
            Console.Beep(213, 200);
            Console.Beep(420, 200);
            Console.Beep(400, 200);
            Console.Beep(420, 200);
            Console.Beep(400, 200);
            Console.Beep(420, 200);
            Console.Beep(315, 200);
            Console.Beep(370, 200);
            Console.Beep(335, 200);
            Console.Beep(282, 600);
            Console.Beep(180, 200);
            Console.Beep(215, 200);
            Console.Beep(282, 200);
            Console.Beep(315, 600);
            Console.Beep(213, 200);
            Console.Beep(330, 200);
            Console.Beep(315, 200);
            Console.Beep(282, 600);
        }

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

12JunDynamic Script Control

Both Silverlight and WPF use XAML markup to describe their user interface.  As I’m currently writing my chapter on WPF for my book IronRuby In Action and I want to use some xaml that has been generated before for a different project but with an IronRuby class to load the xaml I’m in trouble. This is because you can declare assembly references in the xml namespace declarations so you can use the types in that assembly from xaml. 

The DLR based languages don’t compile into static assemblies and this means that you can’t use those xml namespace definitons to reference your assemblies.  I wrote a fairly trivial control that acts like a hook for DLR based controls in the XAML tree.

You can check it out at codeplex.
http://codeplex.com/dynamicscriptcontrol

The idea behind this control is that you can "hook" your DLR based control into the visual tree by setting some properties.  You can set properties on the DLR based control by setting the Attributes property on the DynamicScriptControl

Let’s look at a quick example:

1. The ruby file defining a custom TextBox. But you can do whatever  you want in that ruby file of course.

dynamic_script_control_rubyscript

All this textbox does is preset it’s text property to "I’m prefilled"

2. The xaml for the window

dynamic_script_control_window_xaml 

You first declare a namespace for the assembly that has the DynamicScriptControl. Next I have a StackPanel that contains 2 DynamicScriptControls. The first just contains the 2 mandatory properties. We need to know which class you want to instantiate in the file you provide by setting the ScriptFile property. This script file property is a path to your ruby file in my case prefilled_text_box.rb.
The second DynamicScriptControl is one where I want to initialize the control with my own text property. To declare those properties you have to add them to the Attributes collection of the DynamicScriptControl. At this moment it’s not smart enough to know which datatype you give it so you can specify a format string which was necessary in this case because text is a string.

3. The result

dynamic_script_control_window

Michael Foord the author of IronPython In Action will provide the python integration in this control.

There was a release of the Dynamic Silverlight SDK earlier this week which contained the necessary source code files to compile a common DLR for both IronRuby and IronPython.  That is what makes it possible to support multiple scripting languages from the start. 

I’ve hosted the source code on google and you can find that at:

http://code.google.com/p/dynamic-script-control

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: ,

26DecNew view engines in the MvcContrib project for asp.net mvc

When I got back from visiting my parents over the christmas holiday I checked the MvcContrib project to find out that both Andrew Peter’s NHAML view engine and my XSLT view engine have been accepted in the trunk of those projects.

What’s left to do for me is provide a sample site that shows usage of the view engine.  This has been a very rewarding experience so far :) . I found out about IViewSourceLoader to get the path to the current view file for example.

I also learnt a new trick to increase my test coverage and be able to test the content of the rendered view.

To get the mvc contrib project you can either download it from the releases section on the codeplex site.

Or you can check out the source code and build it yourself from the subversion repository

del.icio.us Tags: ,

Technorati Tags:


Recent Flickrs

    Blogroll

    Recent Listening

    Scrobbler