15 janeiro 2010

O meu Avatar em Silver Light: Ajax Bolt

Quem quiser me convidar para umas jogatanas na XBOX 360 fica aqui o meu Gamecard em Silverlight. Experimentem interagir com a imagem abaixo ....

Adesão massiva aos partidos políticos

Para todos aqueles que não se revêem em partidos políticos uma amigo meu, João Nogueira, apresenta um desafio que pode ser interessante. Se não vejamos:
Queremos despertar a geração mais educada que o nosso país alguma vez teve, nós todos, para urgência de tomarmos em mãos a responsabilidade de elevar a qualidade dos nossos partidos, aderindo em massa a estes, e com a nossa participação e voto, iniciar uma mudança radical na qualidade dos partidos, da nossa democracia e da nossa governação. Se não o fizermos, esta geração arrisca-se a entregar aos seus filhos, um país sem esperança, sem oportunidades e provavelmente um dos mais pobres da Europa.
Fonte: Facebook

Parece-me interessante.

Stay cool.

This Blog is Mutating

Hello,

When I decided to create this blog I was bit too ambitious.

The fact is that I had little to no experience in creating Blogs, and no sense of how much time is needed to keep it interesting.

Unfortunately time is a scarse resource. Furthermore I was never very good in writing down my thoughts so I should have known better. I can't remember how many diaries I left filled with blank pages.

So I'm changing the style.

First my posts will be quite short with the understanding that I will be a compromise between valuable content  and sintetizes.

Second it will no longer be only about software development but also my own tastes in tech and culture.

Third, the posts will be by default written in my native language, Portuguese. There will be posts in English for sure but only when I feel that the concept is so new and interesting that deserves global exposure.

Thank you all for the support, check back soon.

Stay cool,
Nuno Lopes

06 fevereiro 2009

Inversion of Control Made Simple

Inversion of control is an architectural technique where instead of directly calling a function, you hand this action to something else.
Sounds confusing?

A simple example:
1: List<int> l = new List<int>();
2: l.Add(5);
3: l.Add(30);
4: l.Add(3);
5: l.Add(41);
6: l.Sort(delegate(int n1, int n2) { return n1.CompareTo(n2); });


The function Sort accepts another function for a parameter. This function is used by the sort algorithm to find which of two numbers is smaller and is implemented explicitly in the code above.
Nevertheless the code above has no idea of how the sorting algorithm is implemented and as such when the function will be called. In other words the code above has no control about when and by whom the function will be called.
This is in contrast with the Add method that is used to populate the list with values. The programmer explicitly controls when the values are added to the list.
Another example:
Most of us already have coded a simple Web Page with ASP.NET. All pages in ASP.NET inherit from the System.Web.UI.Page class.
We are used to overload methods such as OnInit and OnPrerender or attach delegates to events. Nothing calls these functions but the ASP.NET framework, so we have no control over when and how  will be it will be done.
Indeed, the main difference between a class library and a framework is that the second used IoC right into its heart. While the first is usually a collection of classes (Web Control Library for instance) that may or be part of a framework.
If you haven’t done already you should read what Martin Fowler says about it.
Stay cool.

02 fevereiro 2009

#1 Principle of Object Modeling & Design of Domain Models

In OO if you want to execute an action over an object you don’t explicitly execute that action, but you ask an object to execute that action for you. This in contrast with procedural languages.
Well it may not be number one, but I see so many people confused about where to put a business method when building a Domain Model that this post is just a reminder of basic OO principles.
Say we have the following business activity:
“Pay an Order by Credit Card”
Seams easy. So the programmer start coding immediately in C# the activity using practices that I see so often (I’m sure you do to).

Example of a procedure implementing this activity using non OO methods:
1: public void PayOrder(OrderData aOrder, CreditCardData aCreditCard)
2: {
3:     try
4:     {
5:         // start transaction
6:         double ammount = this.CalculateOrderAmmount();
7:         PaymentData aPaymentData = this.MakePayment(ammout, creditCardData);
8:         // commit transaction
9:     }
10:     catch (Exception ex);
11:     {
12:         // perform clean up
13:     }
14: }
The problem here is that you have no objects (OO way) apart from the current object (this), that might be a singleton class exposing business services to an upper layer. Let’s say it is the OrderBC. BC from business component.
Both orderData, creditCardData and PaymentData are just data structures that hold data (a class with properties only and little to now behavior is nothing but a structure like a record was in Pascal. We now call them DTO’s). Some of us implement this data structures using DataTables other using structured Classes. Furthermore business rules for payment are entirely coded both in the function CalculateOrderAmmount and the procedure Pay.
Now take for instance the OO version of this:
1: public void PayOrder(Order aOrder, CreditCard aCreditCard)
2: {
3:     try
4:     {
5:         // start transaction
6:         aOrder.MakePayment(aCreditCard);
7:         // commit transaction
8:     }
9:     catch (Exception ex);
10:     {
11:         // perform clean up
12:     }
13: }
So here we have two first class objects, aOrder and aCreditCard. Remember the definition of this activity?
“Pay an Order by Credit Card”
So instead of having functions calling functions or procedures of some mega component we ask the Order to make the Payment.
I understand that this principle has been forgotten by many not because of them, but because of how we have been evolving around enterprise architectures built to cope with data access and storage in relational databases. Not only that, but with external services also.
But now you lucky ones that are using Object Relational Mappers and can apply OO principles do design the Business Domain are reminded.
Stay cool.

29 janeiro 2009

Dynamic Queries using LINQ – Part 1

A Dynamic SQL Query is one built at runtime. This is often used to generalize a simple query to cope with parameters that change the way data is filtered and ordered while some rules are fixed.
Take for instance this method:
1: public IList<Entry> Load(long blogId, int lastN, string sortBy, string sortOrder)
It returns a list of entries in a Blog where:
  • lastN – list the last N entries in the Blog. If 0, then return all values.
  • sortBy – sorts the entries by some field. If null return values unsorted.
  • sortOrder – sets the order by which the list returned is sorted (ascending/descending)
  • None of these arguments are mandatory. That is one can simply want a list of the last 10 entries without any kind of sorting or order.
Clearly a static query cannot cope with this, so we need to dynamically generate one.

With LINQ we can do the following:
1: public IList<Entry> Load(long blogId, int lastN, string sortBy, string sortOrder)
2: {
3:  
4:     var q = from entry in OB.Entities<Entry>() where entry.Blog.ID == blogId select entry;
5:  
6:     if (!StringUtils.IsNullOrEmpty(sortBy))
7:     {
8:         switch (sortBy)
9:         {
10:             case "Date":
11:                 if (StringUtils.IsNullOrEmpty(sortOrder))
12:                 {
13:                     q = q.OrderBy(entry => entry.Date); break;
14:                 }
15:                 else
16:                 {
17:                     switch (sortOrder)
18:                     {
19:                         case "asc": q =  q.OrderBy(entry => entry.Date); break;
20:                         case "desc": q = q.OrderByDescending(entry => entry.Date); break;
21:                     }
22:                 }
23:                 break;
24:             // more cases ...
25:         }
26:     }
27:  
28:     if (lastN >= 0) q = q.Take(lastN);
29:  
30:     return OB.Execute<IList<Entry>>(() =>
31:     {
32:         return q.ToList();
33:     });
34: }
Bellow is SQL generated by NHibernate when we call it with: blogId=1, sorBy=null and sortOrder=null.
1: SELECT top 10 this_._ID              as column1_1_1_,
2:               this_._Title           as column2_1_1_,
3:               this_._Body            as column3_1_1_,
4:               this_._PostDate        as column4_1_1_,
5:               this_._PublicationDate as column5_1_1_,
6:               this_._BlogID          as column6_1_1_,
7:               blog1_._ID             as column1_0_0_,
8:               blog1_._Name           as column2_0_0_,
9:               blog1_._Owner          as column3_0_0_,
10:               blog1_._PostDate       as column4_0_0_
11: FROM   BlogPost this_
12:        left outer join Blog blog1_
13:          on this_._BlogID = blog1_._ID
14: WHERE  blog1_._ID = 1 /* @p0 */
Naturally ORDER BY SQL keyword is not included in the query, neither is the sort order.
Bellow is SQL generated by NHibernate when we call it with: blogId=1, sorBy=”Date” and sortOrder=“asc”.
1: SELECT   top 10 this_._ID              as column1_1_1_,
2:                 this_._Title           as column2_1_1_,
3:                 this_._Body            as column3_1_1_,
4:                 this_._PostDate        as column4_1_1_,
5:                 this_._PublicationDate as column5_1_1_,
6:                 this_._BlogID          as column6_1_1_,
7:                 blog1_._ID             as column1_0_0_,
8:                 blog1_._Name           as column2_0_0_,
9:                 blog1_._Owner          as column3_0_0_,
10:                 blog1_._PostDate       as column4_0_0_
11: FROM     BlogPost this_
12:          left outer join Blog blog1_
13:            on this_._BlogID = blog1_._ID
14: WHERE    blog1_._ID = 1 /* @p0 */
15: ORDER BY this_._PostDate asc
Now the ORDER BY and the sort order keywords are there.
Next time I’ll explore ways build dynamically the where clause. Until then …
Stay cool.