May 2008 - Posts

Amy "what a waste" Winehouse
Sat, May 31 2008 23:40

Yesterday I saw one of the worst live performances I can remember. Amy Winehouse has a fantastic voice, but if she keeps doing this she will disappear from scene within the next six months. As if starting the concert 45 minutes after time wasn't bad enough, she appeared completely drunk (and, dare I say it, stoned?).

Her voice was really awful and she even fell on stage. Thank god her band is really amazing (well, if it weren't for the guys on the chorus she would probably be lying on the floor!) and tried to compensate for her unprofessional behavior.

This is one of those things that really makes me mad. There are so many people out there trying to be superstars and they just can't get there (even when they're trying hard). On the other hand, we have people like Amy: they already have everything (man, even with a sour voice, there really isn't any doubts that she really can sing) and it looks like they don't give a crap about it and don't mind simply throwing everything away.

by luisabreu | 1 comment(s)
Filed under:
Using Postsharp for solving the inexisting multi-inheritance problem
Fri, May 30 2008 15:39

Well, not really...

As you surely know, you cannot have mutiple inheritance in .NET. That really sucks. Yes, I agree that multiple inheritance might bring several problems but when applied correctly,  it really helps. Don't believe me? Ok, take a look at WTL.

Back to .NET...Since we can't use multiple inheritance, we end up defining several interfaces and injecting classes that implement the generic boilerplate code for those interfaces. With Windsor (or any other existing container), we're able to reduce the necessary code to instantiante an object but we still need to implement all the members of the interfaces that our base class extends. In practice, implementing this methods means redirecting those calls to instance fields that are initiated through injection.

Today I had some free time and I've decided to play with Postsharp. One of the things you can do with it is replace this manual tedious work and get all those interfaces implemented automatically during compilation. To achieve this, we need to create a new custom (or should I say, derived) CompositionAspect attribute and apply it the class we want to extend.

Since I really didn't had much time, I decided to implement something simple and really chose a bad example: the INotifyPropertyChanged interface. I say unfortunately because, as you'll see, I've ended up firing the event from a field change and this made me develop and additional attribute that is used for intercepting field changes (this was necessary due to the way events work). anyway, let's get started. The first thing we need is a general implementation for the interface. Here's one good enough for demo code:


public class PropertyChangedGeneralNotification : INotifyPropertyChanged
{
        private readonly Object _firingObject;

        public PropertyChangedGeneralNotification(Object firingObject)
        {
            _firingObject = firingObject;
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if( PropertyChanged != null)
            {
                PropertyChanged(_firingObject, e);
            }
        }
}

This interface defines only one member: an event. My initial idea was to really build a simple class that had only the necessary event. Then, the final injected class would simply fire it. Unfortunately, you cannot do that since you can only "use events like delegates" on the class they're defined (I'm sure there really is a good reason on why there is such a strong relationship between events and the classes where they are defined, but I still haven't found a definitive answer for it - btw, if you know, please put it in the comments).

Anyway, that's why I ended up adding the OnPropertyChanged method and added a constructor which receives a reference to the object that is being injected (we need this because when we fire the event we must pass a reference to that class as the first parameter to the method that handles the event).

Ok, Now we need to build the class that is responsible for injecting the previous generic class. To achieve that, we need to create a new CompositionAspect derived class. This class must be serializable and we can override several methods to control the output of the class to which the attribute is going to be applied. Here's the code I've got:

[Serializable]
public class AOPInterfaceInjectionAttribute : CompositionAspect
{
        public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs)
        {
            return new PropertyChangedGeneralNotification(eventArgs.Instance);
        }

        public override Type GetPublicInterface(Type containerType)
        {
            return typeof (INotifyPropertyChanged);
        }

        public override CompositionAspectOptions GetOptions() {
            return CompositionAspectOptions.GenerateImplementationAccessor;
        }
}

The GetPublicInterface method is responsible for returning the type of the public interface that the injected class will implement. The CreateImplementationObject method must return an object that implements the referenced interface (in this case, we're returning an instance of the general class we've implemented in the previous snippet). Notice that we're using the InstanceBoundLaosEventArgs to get a reference to the instance that is being injected and passing it to our general class so that the correct reference is passed when the PropertyChanged event is fired.

The final thing you should note is the override of the GetOptions method. We're saying that in this case we should be able to get a reference to the class that is injected. This means that our "injected" class will also implement the IComposed<T> interface, which has methods that will let us get a reference to that object.

Applying this attribute to an existing class is all that is necessary for exposing the interface:

[AOPFieldChangedInjection]
public class Student
{
        public String Name { get; set; }
        public Int32 Age { get; set; }
}

Now, the only thing that is missing is generating the event. In this case, I though it would be fun to go ahead and create an attribute that intercepts field calls (ok, I know that this is not really the best approach, but at least I can have some more fun and learn more about the platform). When we need to intercept field calls, we can extend the OnFieldAccessAspect class. Here's what I've done:

[Serializable]
public class AOPFieldChangedInjectionAttribute : OnFieldAccessAspect
{
       public override void OnSetValue(FieldAccessEventArgs eventArgs)
       {
           var shouldFireChangedEvent = !eventArgs.ExposedFieldValue.Equals(
                                             eventArgs.StoredFieldValue);
           //call base to change the value of the field
           base.OnSetValue(eventArgs);
           //check if event should be fired
           if (shouldFireChangedEvent)
           {
               InstanceCredentials credentials = eventArgs.InstanceCredentials;
               var composedInteface = (IComposed<INotifyPropertyChanged>) (eventArgs.Instance);
               var evtHandler = (PropertyChangedGeneralNotification) composedInteface.GetImplementation(credentials);

               if (evtHandler != null)
               {
                   evtHandler.OnPropertyChanged(new PropertyChangedEventArgs(eventArgs.FieldInfo.Name));
               }
           }
       }
}

Overriding the OnSetValue is necessary if you want to intercept a write operation. I start by comparing the old value with the new value that is being saved to the field before callilng the base's method. The interesting part is the code necessary for firing the event. We start by getting the credentials. This is a nice concept that is used to prevent access from any code to the implementation code; only code that knows the credentials can access the implementation of the interface.

Notice that in this case we end up casting the interface to the class so that we can call the method that ends up generating the event (no, I can't say that I like the previous code but I can live with it since I'm writing testing exploratory code). As you can see, we end up passing the name of the field instead of passing the name of the property (again, I said that my example was poor, right?)

What matters is that now it's really easy to reuse our generic code, as you can see from the next class (which should really be in a different assembly from the one that showed the previous code):

[AOPInterfaceInjection]
[AOPFieldChangedInjection]
public class Student
{
        public String Name { get; set; }
        public Int32 Age { get; set; }
}

After compiling, the previous class will implement interfaces INotifyPropertyChanged and IComposed<INotifyPropertyChanged> and you'll get events fired when you change any of its properties.

There are still lots of stuff you can do with Postsharp. My first impressions are good: with this platform it's really easy to apply AOP to our projects. I'm still not convinced that this is best thing in thw world, but I'll keep playing with it and see how it reduces the code that I need to write on my day-to-day scenarios.

by luisabreu | 5 comment(s)
Filed under: , ,
F# first impressions
Thu, May 29 2008 21:06

Well, I should really say: first and last impressions! I've read about 200-230 pages of the Expert F# book and I think I've had enough. Ok, functional languages have really cool concepts like patterns, asynchronous workflows, first class support for functions, etc, BUT...the damn thing is simply unreadable! Just look at this sample:

let rec last l =

   match l with

   | [] -> invalid_arg "last"

   | Cool -> h

   | h::t -> last t

so, be honest: can you really read this and understand what it does? Well, now I can, but I think I've seen enough indentations for a lifetime...seeing all these F# snippets just made me want to go back to C++...

by luisabreu | with no comments
Filed under:
ASP.NET MVC Preview 3 is out
Tue, May 27 2008 22:27

As always, Scott Guthrie has announced it on his blog (let's see if I can keep up with all the work the ASP.NET team has been releasing and if I can finally start looking at these new platforms...)

by luisabreu | with no comments
Filed under:
SVN strategies
Mon, May 26 2008 14:17

I've been using SVN as my source control provider for some time now. I've been trying several approaches with it on these last months and to me, the best approach is to use a sheme based on trunk + branches + tags. I've been writing down several notes while trying to put a post about this. Today, I've noticed that I won't be needing to write about it because Bil Simser has done a great job on describing this approach.

by luisabreu | with no comments
Filed under:
Postsharp RC 3.0 released
Mon, May 26 2008 10:48

Just a quick post to remind everyone that uses it that Postsharp RC 3.0 is out.

by luisabreu | with no comments
Filed under:
New Envy Code R preview available
Mon, May 26 2008 10:43

If like me you're a programmer, I'm sure that we both agree when I say that having a decent font for working is a must!  Damien Guard has released another preview of his Envy Code R monospaced font. I'm already using it and I think that you should at least check it out.

by luisabreu | with no comments
Filed under:
xobni: improving your Outlook usage
Sat, May 24 2008 23:22

After reading Paulo's post on xobni, I've decided to give it a go. And guess what? It's really amazing! Go get it here!

by luisabreu | 2 comment(s)
Filed under:
Resharper 4.0 goes beta
Thu, May 22 2008 13:52

Check it out on the Jetbrain's Resharper page.

by luisabreu | with no comments
Filed under:
Steve Ballmer and eggs
Tue, May 20 2008 23:44

Well, see it for yourself :)

by luisabreu | with no comments
Filed under:
S#arp Architecture: first impressions
Tue, May 20 2008 23:16

Today I've finally got some time to take a look at Billy McCafferty's S#arp Architecture. Comparing with the old NHibernate best practices project, I think it's fair to say that there are several important improvements. For instance, there's no longer a Load method that takes an instance and a property list which was used to pass an instance that would be used in filtering the entities loaded from the database. On the other hand, I'd still prefer to use Get instead of Load because I think that getting null when you try to load a non-existing entity is ok.

The base persistence classes have been modified, improving the integration with NHibernate. I'm still not sure on the GetDomainObjectSignature method (used to let you provide the business key), but I do think that the Equals method implementation is better than it used to be (again, it's really complicated to implement Equals when you're thinking in NHibernate, but it's fair to say that Billy's implementation looks good).

So, my first impressions are really positive and I'm officially recommending it to anyone working with NHibernate and ASP.NET (MVC).

by luisabreu | with no comments
Filed under: ,
Jon Skeet on the Mandelbrot benchmark
Mon, May 19 2008 22:23

Man, you gotta love Jon Skeet! Just read this post on a benchmark he performed on the generation of the Mandelbrot set between several single threaded and multithreaded approaches. Cool stuff!

by luisabreu | with no comments
Filed under:
Is EF really the best thing that happened in these last years?
Mon, May 19 2008 22:11

Well, I'm still skeptic about it...and it seems like Frans Bouma decided to comment Danny Simmons post. I believe this is my favorite quote:

"I'm sure the Entity Framework is build by competent people, who are very smart and know what O/R mapping is. What I'm not sure about is if these competent people actually have windows in their building, if they have an internet connection and that someone has told them it's no longer 1994 but that times changed and that there are numerous people out there who have solved the same problem they've tried to solve for so long (...)"

well, what can I say? the man is on fire!

S#arp Architecture
Sun, May 18 2008 0:24

I've just noticed that Billy McCafferty has (well known for his great NHibernate ASP.NET best practice article) published a new project on codeplex called S#arp Architecture which, as he says, is

"(...) a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC Preview 2 framework with NHibernate 1.2 and Spring.NET 1.1.1"

I admit it: I still haven't really looked at the new MVC approach, but when I do, I'll surely start with Billy's work

Book review: The Mythical Man-Month
Sun, May 18 2008 0:20

This book is a classic! It's one of those books that simply doesn't get outdated! I'm not sure if this is such a good thing. After all, the book has more than 20 years now and if we still keep doing the same mistakes, then something is really wrong with us :)

Anyway, the book is great, has several cool stories that show you how hard it is to produce good quality software in a tight schedule. If you're thinking that you simply don't have time to go through all the +300 pages, then don't worry: the 20th anniversary edition has a new chapter which resumes all the previous one with a list of concise topics. I'm glad that the author has emended some of his previous positions (for instance, when he said that hiding implementation details was not a good thing) and I think that overall, I'm giving it a 8/10.

by luisabreu | 1 comment(s)
Filed under:
LINQ To XML resume
Sun, May 18 2008 0:07

I've thought it would be good to post an  entry which aggregates all my LINQ To XML entries for future reference:

  1. LINQ To XML: I'm hooked!
  2. LINQ To XML: building documents with a functional approach
  3. LINQ To XML: working with documents
  4. LINQ To XML: navigating through the axis
  5. LINQ To XML: using XPath expressions
  6. LINQ To XML: changing an existing XML tree
  7. LINQ To XML: applying LINQ expressions
by luisabreu | with no comments
Filed under:
LINQ To XML: applying LINQ expressions
Sun, May 18 2008 0:01

Now that we know the basics, it's time to see how we can use this new API with LINQ. In this post, we'll start by seeing how we can filter an XML document and then we'll how easy it is to transform an existing XML tree into a different one.

Lets start by defining an existing XML tree (we'll simply reuse the tree from the previous example):

 

var xml = new XElement( "clients",
                    new XElement("client",
                        new XAttribute("id",1),
                        new XElement( "name", "Luis"),
                        new XElement( "country", "Portugal")
                    ),
                    new XElement("client",
                        new XAttribute("id",2),
                        new XElement( "name", "John"),
                        new XElement( "country", "England")
                    ),new XElement("client",
                        new XAttribute("id",3),
                        new XElement( "name", "Paulo"),
                        new XElement( "country", "Portugal")
                    )
                );

 

This will produce XML similar to the next snippet:

<clients>
  <client id="1">
    <name>Luis</name>
    <country>Portugal</country>
  </client>
  <client id="2">
    <name>John</name>
    <country>England</country>
  </client>
  <client id="3">
    <name>Paulo</name>
    <country>Portugal</country>
  </client>
</clients>

Ok, now we're ready to start playing with LINQ. Lets start by getting only the portuguese clients:

var transformed = from client in xml.Elements()
                where client.Element("country").Value.CompareTo("Portugal") == 0
                select client;

The previous code returns an IEnumerable<XElement> collection. If you're using a console app and you want to confirm that everything is working, you can simply wrap that collection on an XElement and pass it to the console.WriteLine method:

Console.WriteLine(new XElement("portugueseClients", transformed));

That should print the following XML:

<orders>
  <order id="1" clientId="1">
    <item id="1" quantity="10" />
    <item id="2" quantity="5" />
  </order>
  <order id="2" clientId="1">
    <item id="1" quantity="10" />
  </order>
</orders>

Even though I'm just filtering the results, you could also all the other cool LINQ operatores over an existing XML tree!

One of the most common things you need to do when you work with XML is to transform an existing tree into another one (for instance, you'll need doing this when you're trying to integrate two applications which understand different XML messages). In this case, lets suppose that you need to transform the previous XML tree in another where all the info is represented through attributes. Here's how that would look like:

<compatClients>
  <compatClientElement id="1" name="Luis" country="Portugal" />
  <compatClientElement id="2" name="John" country="England" />
  <compatClientElement id="3" name="Paulo" country="Portugal" />
</compatClients>

Here's one LINQ query that will give you the previous results:

var transformed = new XElement("compatClients",
    ( from client in xml.Elements()
           select new XElement("compatClientElement",
                 new XAttribute("id", client.Attribute("id").Value),
                  new XAttribute("name", client.Element("name").Value),
                  new XAttribute("country", client.Element("country").Value)) )
       );

Well, not really that hard, right? btw, lets also assume that you've got several XML elements (instead of just two) and that all of them should be transformed in attributes. Does that mean that you need to create all those attributes manually? Hell, no! You can simply use another LINQ query to achieve that. here's a variation of the previous snippet that produces similar results:

var transformed = new XElement("compatClients",
                           ( from client in xml.Elements()
                           select new XElement("compatClientElement",
                               new XAttribute("id", client.Attribute("id").Value),
                               (from elem in client.Elements()
                                    select new XAttribute(elem.Name, elem.Value)
                                ) ) ) );

You've got love LINQ To XML!

Another common scenario is transforming an object graph into an XML message. For instance, suppose you have the several orders represented by the following object graph (I'm just using anonymous types to represent them. You'll probably have a predefined type on a real scenario):

var orders = new[] {
                new{ Id = 1,
                    ClientID = 1,
                    OrderItems =  new[]{ new {ItemId = 1, Quantity = 10}, new {ItemId = 2, Quantity = 5} }
                    },
                new{ Id = 2,
                    ClientID = 1,
                    OrderItems =  new[]{ new {ItemId = 1, Quantity = 10} }
                    }
            };

 

Now, we need to build a new XML message that looks like this:

<orders>
  <order id="1" clientId="1">
    <item id="1" quantity="10" />
    <item id="2" quantity="5" />
  </order>
  <order id="2" clientId="1">
    <item id="1" quantity="10" />
  </order>
</orders>

Which, as you must be expecting, is easily doable with the next snippet:

var transformed = new XElement("orders",
                               from order in orders
                               select new XElement("order",
                                   new XAttribute("id", order.Id),
                                   new XAttribute("clientId", order.ClientID),
                                   from item in order.OrderItems
                                   select new XElement("item",
                                           new XAttribute("id", item.ItemId),
                                           new XAttribute("quantity", item.Quantity))
                                           )
                                           );

I've just showed one or two things that are easily achieved with this API. I hope that by now I've already convinced on how flexible and powerful this new API is. I was actually able to build all the demo code presented in this post in about 2 minutes (including the queries). If I was using the old DOM API, I'd took at least thrice as long to get the some results (and I'm assuming that I know the API well enough).

As I've said in one of the previous posts, I'm really enjoying working with this new API. Since I've started using it, I've noticed an improvement in my productivity, which is good, because it means that now I have more free time to see what's happening on the Euro 2008 :)

by luisabreu | with no comments
Filed under:
HTC has done it again
Thu, May 15 2008 22:56

For some time now, I've been a proud owner of an HTC touch and I'm really happy with it. Anyway, I've just noticed that they've just released a new model: HTC Touch Diamond. It looks just great! Well, I guess that now I can say that I regret having bought an HTC touch...

.NET 3.5 and VS SP beta1 goodies
Mon, May 12 2008 20:58

You can get them from here (VS) and here (.NET). I'm reading what's new on Brad Abrams post and I'm really digging the new features:) For instance, having the format option working with JS code is simply cool! Another cool thing: the ScriptManager is able to combine scripts so there's really no need for using the ToolkitScriptManager for that:)

Btw, i'm still going through the complete list but it really looks like we're gonna gave lots of new stuff :)

by luisabreu | 1 comment(s)
Filed under: , , , , , ,
Book review: Release it!
Sat, May 10 2008 22:57

After seeing several positive reviews about Release it!, I've finally decided to buy it and read it. Wow! what a great book! Even though most of the stories happen in the "Java World", the main ideas presented by the book are applicable if you're in software developer and you do want to deliver successful products.

The book presents several important aspects related with creating and releasing stable software systems that tend to evolve along the years. In fact, you'll see that the book presents lots of stuff on how to solve capacity and stability issues. I can tell you that I did enjoy the way these topics were presented with several examples of patterns and anti-patterns on each of those areas.

This is one of those books that you must read if you're serious about software development. At the end of the day, I'm giving it 9/10.

by luisabreu | with no comments
Filed under:
More Posts Next page »

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover