April 2009 - Posts

The S#arp framework: adding support to JSON.Net
Thu, Apr 30 2009 10:06

Today we’re going to keep looking at the internals of the SharpArch.Web assembly and we’ll take a quick peek at the JsonNetResult class. This is  a custom ActionResult class which you can use if you need to return JSON serialized by the  Json.NET serializer to the client.

As you recall, custom ActionResult classes are supposed to override the ExecuteResult method in order to write the response that is sent back to the client. In this case, the code for that method is really simple: it will start by setting the content type (if none is specified on thee ContentType property, then the default “application/json” will be used), then it adjusts the content encoding (again, only if the property ContentEncoding is not null) and finally, it will serialize the contents of the Data property and write it to the output buffer of the response object. And that sums it up…

In the current release, you’ll have to instantiate it directly since there aren’t any helpers for doing that. If you intend to use this custom ActionResult frequently, then you probably should write a couple of methods for helping you out. If all your classes are inheriting form a base controller, then that would be a good place to put those methods…if you not, then probably you could create a couple of static helper methods like these:

public static class JsonNetHelpers    {
  public static JsonNetResult JsonNet(Object data) {
            return JsonNet(data, null );
  }

  public static JsonNetResult JsonNet( Object data, String contentType ) {
            return JsonNet( data, contentType, null );
  }

  public static JsonNetResult JsonNet( Object data, String contentType, Encoding encoding ) {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = encoding
            };
  }
}

Notice two things about this approach:

  • if you want to set the JsonSerializerSettings, then you’ll need to save the returned ActionResult object (notice that I’m returning a JsonNetResult instance and not the base ActionResult) and access its SerializerSettings property before returning that instace from your action method;
  • I’m not using extension methods here…why? well, because there’s really not much point in adding this method to a controller  since it doesn’t interact with it…

And that’s all for today. Keep tuned for more on the S#arp framework.

by luisabreu | with no comments
Filed under:
Opera’s 15th anniversary
Wed, Apr 29 2009 14:59

468x60opera15

Hurray!

by luisabreu | with no comments
Filed under:
Windows 7 on multiple cores
Wed, Apr 29 2009 14:55

I’ve just found this on Daniel Moth’s blog. I’m speechless…

by luisabreu | with no comments
Filed under:
Multithreading: state, atomicity, serializability and linearizability
Wed, Apr 29 2009 13:57

I'm starting to take a close look at multithreading and I thought it would be a good idea to start writing about this topic. This should help me understand the concepts better (I understand things better when I try to explain them to others and that's one of the reasons I'm writing this series) and it might even help me clear some doubts that I'll be having along this long road (yes, I'm counting with the help of the readers of this blog for improving my knowledge on this area). Let's get started, shall we?

State is an important concept for any program. And it's also the reason for most problems that we encounter when we write multithreading programs. In the old days, we had only one thread accessing state and everything was fine. However, with the appearance of multithreading, that is no longer the case; most of the time, you'll end up needing shared state for reading and writing operations. This might lead you to several unwanted scenarios...for instance, a thread might read a variable which hasn't totally been set (ex.: reading a 64bit value on a 32 bit architecture). Due to that, I'm really convinced that the first step in understanding multithreading resides in understanding state and how it influences the way we write code.

In fact, it helps to see state as being one of two types: shared and private. As we'll see, problems generally happen when we deal with shared state. We've been talking about shared state for some time, but what is *shared* state? Since I'll be using C#, then it's discuss this topic in its context. In this case, shared state includes:

  • classes' fields (instance and static);
  • state passed to a thread during creation;
  • all references reached from a top shared reference.

When writing multithreaded code, working with shared state is the main points of pain we'll face. For instance, lets consider the following line of code:

int a = 1; //suppose this is shared
a++;

Take a close look at the code...do you think that the a++ line is thread safe? (suppose that a is shared after being created – for instance, think of it as a field of a class that is shared across several threads) The answer is no because a++ is really a = a + 1 which, in practice, should be translated into assembly that performs the following steps:

  • load a into a register;
  • increment the value of that register;
  • move the value off that register back to the position of memory occupied by variable a.

When you think of that simple instruction as being a set of instructions and once you notice that multiple hardware instructions aren't atomic by default, we can surely agree that things might not go as expected when several threads execute that instruction and variable a is shared between those threads! Ok, let me tell you what I consider to be correct results with two threads t1 and t2:

t1 t2

2 3

3 2

As you can see, if we can ensure that the a++ operation is executed atomicly, then we will end up with the correct results (assuming, of course, that letting the a variable being incremented several times is expected and allowed).

Atomicity is an important concept, especially in the multithread world. An operation or a set of operations are atomic if they happen at once. For instance, loading a value into a register is an atomic operation. However, the operations performed as a result of the a++ instruction, aren’t (at least, not by default).

Besides atomicity, there are two important concepts that might help us understand what's going on. I'm talking about serializability and linearizability. Two operations are serializable when one happens before the other. For instance, if we look at the set of operations that result from the the a++ instruction on a *single* threaded program, we can say that we have achieved serializability because all three operations are executed one after another. With mutithreading programming, that doesn't happen by default (and this is one of the things we need to ensure in order to guarantee that our program works correctly in multithreaded environments).

Linearizability is related with serializability and you can think of it as a point where a set of updates become visible to other threads. Achieving Linearizability is fundamental for ensuring the correctness of  multithreaded applications. In practice, and as we’ll see in the future, you achieve this by wrapping regions of code in critical regions.

And I guess that is all for today. More thoughts about threading in future posts.

by luisabreu | with no comments
Filed under:
Book review: C# 2008 and 2005 Threaded Programming
Wed, Apr 29 2009 13:41

This is the second book I have read in multithreading programming (the first was the exceptional Concurrent Programming in Windows, by Joe Duffy). As I've said in the past, this is a topic which really interests me and that's why I gladly accepted a free copy from Packt for review. As you can see from its title, this is (essentially) a beginners book. It's full of code snippets and instructions of where to put that code (where you’re supposed to build demo projects by following the steps detailed in the book). This kind of organization doesn't really appeals to me... I'd really prefer to see everything together than have code mixed with instructions (this is personal, since I do prefer to read a book away from the PC and, in this case, having instructions detailing what I need to do step by step isn't really something I enjoy).

The book has a couple of intro chapters which give you some information about the hardware and introduces you to threads and processes. After that, you quickly jump into code examples. You'll jump right into C# windows forms code and you'll start by using a BackgroundWorker object to add asynchronous behavior to your app. In fact, this was really a surprise to me because I never thought a beginners book would jump right into a Windows Forms apps. I'd really prefer to start from a console app because that would let me concentrate on threading itself instead of wasting lots of lines with UI code (I'm not saying that using the BackgroundWorker isn't important; just questioning if that is really the first practical thing you should put in a beginners threading book). I guess that it's fair to say that this is mostly a Windows Forms multithreading book since most (if not all) of its examples are windows forms examples.

Going back to the content, I did like the parts where the author showed how to use some tools (ex.: Process Explorer) for getting info on what's happening and I did found value in chapter 5, where the author presents some tips for debugging multithreaded code. Adding a chapter on Parallel Extensions was also a good idea, though I think that there definitely was a lot more to say about it (though I guess that the size of the book might have limited the author to the stuff that is presented on that chapter).

Now, here are some of the topics I expected to see mentioned on this book (and weren't or weren't well covered):

  • Memory model: no, I didn't expect to find many lines on this (since it's an introductory book). But it should have been mentioned because it explains why a lot of things might go wrong in multithreading programming.
  • Data synchronization: I expected to find info on this topic. It's really important in multithreading scenarios and I guess that it should have at least one chapter on it (I believe that presenting Monitor, Reader/writer locks are far more important than reusing BackgroundWorker across several chapters). I'm not sure why, but I think that there are noo examples of lock usage (which is something that really made me sad). On the other hand, being able to partition your work so that all the parts can run independently is really something which we must all try to achieve (and the author does give a lot of emphasis on that). Just wished that this portioning would be complemented with info on how to synchronize data access since that will be needed in the "real world".
  • APM: the asynchronous programming model based on delegates and the event-based asynchronous pattern deserved to have a chapter about them.

Bottom line: I that think this book could be improved if it had more info in the previous topics and less stories/printed code+instructions. Btw, I didn't really enjoy the stories on the FBI agents or NASA either...if the idea was to mimic the style of the head first series, then it wasn't really achieved. Having said all this, I guess I can't really give it more than 6/10.

by luisabreu | with no comments
Filed under:
The S#arp framework: The SharpArch.Web assembly – part II
Wed, Apr 29 2009 13:26

Today we’ll keep looking at the SharpArch.Web assembly and we’ll take a quick look at the TransactionAttribute. TransactionAttribute is an ActionFilterAttribute which intercepts the ActionExecuting and ActionExecute exceptions for starting and ending a transaction. Here’s the code for that class:

public class TransactionAttribute : ActionFilterAttribute    {
  public override void OnActionExecuting(ActionExecutingContext filterContext) {
            NHibernateSession.Current.BeginTransaction();
  }

  public override void OnActionExecuted(ActionExecutedContext filterContext) {
            if (filterContext.Exception == null && NHibernateSession.Current.Transaction.IsActive) {
                NHibernateSession.Current.Transaction.Commit();
            }
  }
}

As you can see, the code relies (yet again!) on the omnipresent NHibernateSession class we’ve met in a past post. Notice that the transaction is only committed when the action method doesn’t throw an exception and when the current transaction is still active. Combining this attribute with the  WebSessionStorage we’ve met in the last post makes working with transactions (and db related stuff) from an action method a breeze…

If you  don’t believe me, then take a look at the following action method (copied from the CustomersController class in the Northwind sample app):

[Transaction]
public ActionResult Create(string companyName, string assignedId) {
    Customer customer = new Customer(companyName);
    customer.SetAssignedIdTo(assignedId);
    customerRepository.Save(customer);

    return View(customer);
}

As you can see, there’s no evidence of database code  here. This is probably good and it will let you isolate the action method code from any of those concerns. Simple and elegant.

And that’s it for today. Keep tuned for more on the S#arp framework.

by luisabreu | with no comments
Filed under:
MVC Action filter project on Codeplex
Tue, Apr 28 2009 10:46

Roni Schuetz informed me of a new Codeplex project he created for building a common library of ASP.NET MVC action filters. If you’re into MVC and you’d like to contribute, then check it out.

by luisabreu | with no comments
Filed under: ,
The S#arp framework: the SharpArch.Web – part I
Mon, Apr 27 2009 20:36

In this post we’re going to start looking at the goodies available on the SharpArch.Web assembly introduced by the S#arp framework. This assembly contains several helpers which you can reuse in your ASP.NET MVC projects. In this post, we’re concentrating on the WebSessionStorage class.

I’m not sure if you remember it, but we talked about the ISessionStorage a few days ago. As we saw, this interface is used for managing the storage of a session along a specific time. Here’s the interface again, for those that missed the post or don’t remember it:

public interface ISessionStorage {
        ISession Session { get; set; }
}

The WebSessionStorage implements this interface and guarantees that for each request you’ll reuse the same ISession instance across all stages of the ASP.NET pipeline. In other words, it ensures that the recommended session-per-request pattern is applied to all the web requests. As you might expect, the class uses the HttpContext.Items collection for saving the ISession instance that will be reused across the request. It handles the HttpApplication.EndRequest for ensuring proper cleanup of the current session.

Using this class is simple, as you can see from the following snippet copied from the Northwind demo that accompanies the framework:

NHibernateSession.Init(new WebSessionStorage(this),
                           new string[] { Server.MapPath("~/bin/Northwind.Data.dll") },
                           new AutoPersistenceModelGenerator().Generate(),
                           Server.MapPath("~/NHibernate.config"));

As you can see, this type is passed to the NHIbernateSession’s Init method so that it gets used by the other classes that rely on the NHibernateSession.Current property for getting a valid instance of an ISession. Do keep in mind that this code isn’t thread safe and should be called only once during the lifetime of the application.

And that’s it. I guess that there’s not much more we can say about this class. Keep tuned for more on the S#arp framework.

by luisabreu | with no comments
Filed under:
The S#arp framework: the duplicate entity validator
Mon, Apr 27 2009 14:44

In the last post I promise that we’d talk about the EntityDuplicateChecker and that’s what we’re going to look at today. As we’ll see, this  class is used by the custom NH validators  that you can find in the SharpArch.Core.NHibernateValidator. The EntityDuplicateChecker implements the IEntityDuplicateChecker, which looks like this:

public interface IEntityDuplicateChecker    {
        bool DoesDuplicateExistWithTypedIdOf<IdT>(IEntityWithTypedId<IdT> entity);
}

The EntityDuplicateChecker’s responsibility is to search for an entity with the same business signature as the IEntityWithTypedId instance that was passed in and that has a different Id.The current implementation of this interface is not really complicated since it relies on getting all the properties used in the business signature (which you can get by calling EntityWithTypedId’s GetSignatureProperties method) and adding a restriction for each to the ISession that is used for interacting with the database.

As you might expect (if you’ve been following along), the ISession is obtained by using the NHibernateSession.Current property which we’ve met in one of the latest posts. Now, even though you can use this class directly in your code, the truth is that you’ll probably end up using the custom HasUniqueDomainSignatureAttribute (if you’re using NH Validator for your domain validation, that is). Whenever you need to add a custom NH Validation rule, you need to add (at least) two classes: one new custom attribute and  a new validator class. Let’s start with the custom attribute…

The S#arp framework introduces the HasUniqueDomainSignatureAttribute, which is really simple and looks like this:

[AttributeUsage(AttributeTargets.Class)]
[ValidatorClass(typeof(HasUniqueDomainSignatureValidator))]
public class HasUniqueDomainSignatureAttribute : Attribute, IRuleArgs    {
        public string Message {
            get { return message; }
            set { message = value; }
        }

        private string message = "Provided values matched an existing, duplicate entity";
}

As you can see, the attribute implements the IRuleArgs:

public interface IRuleArgs    {
   string Message { get; set; }
}

This interface’s only objective is to let you get or set the error message that should be shown when there’s an error. Another interesting thing (from the previous snippet) is the use of the ValidatorClassAttribute. This is used to indicate the type of the validator class that is really responsible for performing the validation of that value. In this case, validation is performed by the HasUniqueDomainSignatureValidator class, which implements the mandatory IValidator interface. Here’s the current code for this class:

public class HasUniqueDomainSignatureValidator : NHibernate.Validator.Engine.IValidator    {
        public bool IsValid(object value) {
            IEntityWithTypedId<int> entityToValidate = value as IEntityWithTypedId<int>;
            Check.Require(entityToValidate != null,
                "This validator must be used at the class level of an " +
                "IdomainWithTypedId<int>. The type you provided was " + value.GetType().ToString());

            IEntityDuplicateChecker duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService();
            return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf<int>(entityToValidate);
        }
}

As you can see, the class has only one method which relies on the service locator for getting a  valid instance of the IEntityDuplicateChecker that is responsible for validation. If you look at the source code, you’ll see that there are other pairs attribute/validator for validating specific types of database keys (you have one pair for strings and another for Guids, so use those instead of the general one I’ve shown if you’re using a strings or a Guids for keys).

Don’t forget that to use this custom validation attribute, you need to register the EntityDuplicateChecker with the ServiceLocator. If you don’t, validation won’t work!

And that’s all for today. Keep tuned for more about the S#arp framework.

by luisabreu | with no comments
Filed under:
The S#arp framework: understanding the data assembly
Sun, Apr 26 2009 17:25

After a small detour into the NH Validator framework (and yes, it was really a small detour since we didn’t see how it integrates really well with NH and other frameworks nor how we can create custom validation rules), in this post we’re going back to our study of the S#arp framework. Today, we’re going to take a deep dive into some of the helper classes that are baked into the SharpArch.Data assembly.

We’ll start by looking at the Repository.cs file. This file contains two classes: RepositoryWithTypedId<T, IdT> and Repository<T>. Repository extends RepositoryWithTypedId, specifying IdT as int. As you might expect, RepositoryWithTypedId contains the code that implements IRepositoryWithTypedId interface.

The RepositoryWithTypedId adds a new property to the API implemented from the interface: the Session property. This (read only) property returns a reference to the ISession instance that the remaining methods use to perform their work. The implementation of this property is really simple: it just delegates to the static NHibernateSession.Current property, which is responsible for doing all the work and getting a valid reference to the “current” ISession (we’ll come back to this class in the future).

Once we get a reference to a valid ISession instance (which, as we’ve seen, relies on the NHibernateSession class), implementing the interface methods are fairly simple . The only note I’d like to make here is that the FindOne method will throw (NotUniqueResultException) if it gets more than one hit.

Now let’s proceed and take a look into the (way more interesting) NHibernateSession class. This is a static class which encapsulates everything you need in order to:

  • load the object/table mappings and build a Configuration object (you can do this through the traditional XML files or by using a fluent interface approach)
  • register eventual interceptors (though you probably shouldn’t go this way because listeners are the way to go with NH 2);
  • get a valid ISession instance from a ISessionFactory previously obtained.

In practice, you’re supposed to initialize the NHibernateSession by calling one of the overloads of the Init method (which you should only once, at startup). Then, you can get a valid session by invoking the Current property:

public static ISession Current {
   get {
      ISession session = Storage.Session;
      if (session == null) {
        if (RegisteredInterceptor != null) {
          session = SessionFactory.OpenSession(RegisteredInterceptor);
        }
        else {
                        session = SessionFactory.OpenSession();
        }

        Storage.Session = session;
      }

      return session;
   }
}

As you can see, the class relies on some sort of storage for keeping the created session (notice the use of the Storage static field). Before creating a new ISession instance, the class will always check for a valid instance of that type in that static field. If it finds one, then it will simply reuse it as the “current” ISession instance. This storage is represented by the ISessionStorage interface:

public interface ISessionStorage {
        ISession Session { get; set; }
}

As we’ll see in the future, the S#arp framework introduces one implementation of this interface that lets you use the session-per-request pattern.

The NHibernateRepositoryWithTypedId and NHibernateRepository generic classes expand the previous repository classes and give you much more control over the ISession usage. Before ending, there’s still time to talk about the DbContext class. This class implements the IDbContext interface and relies on the NHibernateSession in order to get a valid ISession instance.

There’s still one important class to cover (EntityDuplicateChecker), but I’ll leave it for another day!

by luisabreu | with no comments
Filed under:
NHibernate validator: improving the code with external rules
Sun, Apr 26 2009 11:15

One of the nice things you can do to improve the code we’ve seen in the previous post is define the validation rules in an external assembly. By doing this, you can change your rules without having to recompile the assembly that contains the domain objects. To illustrate this, we’ll change the example presented in the last post.

The first thing we’ll do is create a new class library assembly to host our Student class. I’m calling it OO and changing the default namespace of the Student class:

namespace OO {
    public class Student     {
        public Student(Int32 studentId) {
            StudentId = studentId;
        } 
        public Int32 StudentId { get; private set; }
        public String Name { get; set; }
        public String Email { get; set; }
    }
}

Then, we need another (class library) assembly which references NHibernate.Validator and our OO assemblies. This is where we’ll put our validation rules. In this case, I’ve called the assembly OO.Rules and I’ve decided to go with the fluent interface approach. Here is the code of the StudentRules class (which has all the validation rules for the Student class):

namespace OO.Rules {
    public class StudentRules: ValidationDef<Student>    {
        public StudentRules()        {
            Define(st => st.StudentId).GreaterThanOrEqualTo(1)
                                                     .WithMessage("StudenId must be positive");
            Define(st => st.Name).NotEmpty()
                                              .WithMessage("Name cannot be empty")
                                              .And.NotNullable()
                                              .WithMessage("Name cannot be null");
            Define(st => st.Email).IsEmail().WithMessage("Email is not correct");

        }
    }
}

Finally, I’m building a console app for testing the code. After adding all the necessary references (don’t forget to reference our 2 custom assemblies and the NH validator assembly), you’ll only need this code for getting the same results we had with the previous posts:

var fluentConfig = new FluentConfiguration();
((IMappingLoader)fluentConfig).AddAssembly("OO.Rules");
fluentConfig.SetDefaultValidatorMode(ValidatorMode.UseExternal);
var validator = new ValidatorEngine();
validator.Configure(fluentConfig);

var student = new Student(-1) {
                Name = "Luis",
                Email = "labreu"
};

var invalidValues = validator.Validate(student);
//same code as before

As you can see, the main difference (when compared with the previous example) happens in the setup of the FluentConfiguration instance. Instead of registering each validated type, we’re simply passing the name of the assembly and letting the framework pick all the types and their validation rules.

In my opinion, this approach (of separating rules from validated objects) has two advantages:

  • you can easily change the rules without needing to recompile the assembly that contains your objects;
  • the OO assembly no longer needs to reference the NH validator assembly.

And that’s it for today.

by luisabreu | 1 comment(s)
Filed under:
Looking at the NHibernate Validator
Fri, Apr 24 2009 15:30

After started looking at the S#arp framework, I was almost obliged to take a look at NHibernate Validator framework .To see if it was really that good, I decide to pick a small example and apply some validation rules. This post contains some notes on my incursion into this framework.

The first thing you need to do is to download the library and add a reference to in your project. Then, you can start adding validation rules to the properties of your objects. Currently, you have three options: you can use attributes and decorate your fields/properties with the available attributes, or you can use an XML file to define those rules or you can define those rules by using a fluent interface approach. We’ll start by exemplifying attribute usage. Take a look at the following snippet:

namespace TestApp {
    public class Student    {
        public Student( Int32 studentId ) {
            StudentId = studentId;
        }

        [Min(1, Message="StudenId must be positive")]
        public int StudentId { get; private set; }
        [NotEmpty (Message="Name cannot be empty"), NotNull(Message="Name cannot be null")]
        public String Name { get; set; }
        [Email(Message="Email is not correct")]
        public String Email { get; set; }
    }
}

As you can see, we’re using several of the validation attributes and we’re also specifying an error message for all of them. You are now in a position to validate an instance of Student by using the ValidatorEngine class:

var invalidId = -1;
var student = new Student( invalidId ) {
           Name = "Luis",
           Email = "labreu@"
};

var validator = new ValidatorEngine( );
var invalidValues = validator.Validate( student );
foreach ( var invalidValue in invalidValues ) {
    Console.WriteLine( "Property: {0} ---- PropertyPath:{1} ----- Message: {2}\n",
                    invalidValue.PropertyName,
                    invalidValue.PropertyPath,
                    invalidValue.Message );
}

If you run the previous snippet, you should get errors for the Student’s Id and email properties!

As I said, you can also specify the validation rules by using XML files. Here are the validation rules written on a xml file:

<?xml version="1.0" encoding="utf-8" ?>
<nhv-mapping xmlns="urn:nhibernate-validator-1.0" namespace="TestApp" assembly="TestApp">
  <class name="Student">
    <property name="StudentId">
      <min value="0" message="StudenId must be positive" />
    </property>
    <property name="Name">
      <not-empty message="Name cannot be empty" />
      <not-null message="Name cannot be null" /> 
    </property>
    <property name="Email">
      <email message="Email is not correct" />
    </property>
  </class>
</nhv-mapping>

Now, you have two options: you can embed the XML file or just copy it to same place on the disk (generally, you’ll put them on the same folder as the app). In both cases, you’ll need to pass a config options to the ValidatorEngine object. Here’s the code you might use when you’re using an external config file (do notice that if the config file is embedded, you’ll still need to set the ValidatorMode property):

using Environment = NHibernate.Validator.Cfg;

//more code

var configOptions = new NHVConfigurationBase( );
configOptions.Mappings.Add( new MappingConfiguration( "Student.nhv.xml" ) );
configOptions.Properties[Environment.Environment.ValidatorMode] = ValidatorMode.UseExternal.ToString( );
var validator = new ValidatorEngine( );
validator.Configure( configOptions );
var invalidValues = validator.Validate( student );
//same code as before for showing error msgs

You should also keep one more thing in mind (if you decide to go with the embedded resource approach): if you want to get automatic loadding, then you should give the file the same name that you gave to the class.

Before ending, there’s still time for showing one last option for setting up the rules: using a fluent configuration style. If you prefer this approach, the first thing you need to do is create a class for the  definition. Here’s how it looks:

public class StudentRules : ValidationDef<Student> {
   public StudentRules( ) {
                Define( st => st.StudentId ).GreaterThanOrEqualTo( 1 ).WithMessage( "StudenId must be positive" );
                Define( st => st.Name ).NotEmpty( ).WithMessage( "Name cannot be empty" )
                    .And.NotNullable( ).WithMessage( "Name cannot be null" );
                Define( st => st.Email ).IsEmail( ).WithMessage( "Email is not correct" );
    }
}

And then, you can load your rules like this:

FluentConfiguration fluentConfig = new FluentConfiguration( );                                 
fluentConfig.Register<StudentRules, Student>( )
                                    .SetDefaultValidatorMode( ValidatorMode.UseExternal );

var validator = new ValidatorEngine( );
validator.Configure( fluentConfig );
//the rest remains the same

I won’t say anything more about this framework today. The only thing I’ll add is that I did enjoy it and I‘ll come back to it in the future (especially because it does integrate really well with NH and I’ll be talking about that and S#arp framework in a near future).

by luisabreu | 1 comment(s)
Filed under:
Bullfighting: the good, the bad and the ugly
Thu, Apr 23 2009 22:18

Ok, so today I was watching a TV Portuguese program on animals and, as you might guess, bullfighting was one of the discussed topics. For starters, you should know that I’m against it. I’m not sure why some think that we have the right to create animals and them make them suffer for our pleasure (I guess that if we have that right, then we should go back to ancient Rome and throw those into the pits with lions. how about that?).

I’m not going into a discussion about its cultural aspects (don’t we need to evolve?)…I do accept that you say that you like it and that it’s your argument for watching it. Just don’t try to convince me that they don’t hurt while they’re in the arena like one guy did in the program I was watching…I mean, can anyone really believe that the bull doesn’t hurt and enjoys being stabbed? (please don’t anwer…this was rhetorical…)

oh well, I guess that it’s one of those topics where you won’t be able to reach a consensus, right? so back to coding again…

by luisabreu | with no comments
Filed under:
Code Contracts…are cool again!
Wed, Apr 22 2009 21:49

Why, you ask?

Simply because now they’re usable from within any version of Visual Studio (though you’ll only have static checking if you’re using VSTS). I’m not sure on how I missed that announcement (ok, I missed it because I got really “depressed” after the initial requisites for using it and never looked back!), but now I’m really excited and will start migrating all my existing code for using this new platform…

by luisabreu | with no comments
Filed under:
Spb Mobile Shell 3.0
Wed, Apr 22 2009 21:34

In the past, I had a license for Spb Mobile Shell 2.0 and I really liked it. However, I stopped using it when i got my HTC Pro since the Touch Flow interface is easy to use. However, I think I’ll be going back to Spb Shell 3.0. My friend JPC sent me a link to the newest version and I’m really enjoying the demo period. If you have a windows mobile phone, then you should give it a try (you can also read this complete review)…

by luisabreu | with no comments
Filed under:
The S#arp framework: repository interfaces
Wed, Apr 22 2009 9:51

Today we’re going to keep looking at the SharpArch.Core assembly and try to understand its default support for repositories. Before going on, I guess that it’s a good idea to take a detour and talk a little bit about repositories. One of the problems we (developers) face in most applications is that most of the time we’re so worried with infrastructure code that we loose the so needed domain perspective. As we’ve seen in previous posts, we’ll have two basic type of objects: entities and value objects.

I believe that we all agree in that we have two ways of getting a reference to an object (entity or value object): we can create a new instance by invoking its constructor or we can get a reference to an existing one by traversing an association. In this second case, you start by getting a reference to a know object and then you ask it for a reference to the object you’re interested in. Now, this is all good and simple when we think about OO code, but, again, when we start mixing these concepts with database persistency, things become a lot more interesting (or should I say, difficult?).

I guess that we could always let the database leak into our domain and let users execute a queries over it. Unfortunately, this is nor really a good idea since it tends to lead to a shift on focus from domain to data based design (where the database is king). There are also other  problems…for instance, if you have a model where a customer has lots of addresses and these objects are persisted on a database, then what should you do when:

  • a customer is loaded…should you get the customer and his addresses? only the customer?
  • Should we allow isolated loading of address?

As always, the answer to the previous questions depends on the *context*. DDD answers them by introducing aggregates and repositories for giving you access to objects (aggregates) that been persisted in a database (and are in the “middle” of their life cycle).

Today I’m not going to spend a lot  of time talking about aggregates. I’ll just define them as being a cluster of entities and value objects which have a single access point (also known as aggregate root). You should only hold references to this top level entity, though you can pass “transient” references to the inner entities or value objects. By using aggregates, you can easily maintain the consistency between a group of objects (which is one of the problems we face when working with complex domains).

If you understand the concepts presented in the previous paragraph, then it should be obvious that repositories should only work over aggregates! A repository abstracts the database and gives the developer the illusion of working with a collection of aggregates. As you might expect, you can add and remove aggregates from this “pseudo in-memory” collection. They should also give you references to existing objects (that is, objects that are stored in the database). In this case, you’ll probably have several methods which allow you to specify different filters (or you can even use something like Fowler’s Query Object pattern).

After all this, you shouldn’t be surprised to hear that S#arp framework introduces an interface for representing repositories. It’s called IRepositoryWithTypedId<T> and it looks like this:

public interface IRepositoryWithTypedId<T, IdT> {
        T Get(IdT id); 
        IList<T> GetAll(); 
        IList<T> FindAll(IDictionary<string, object> propertyValuePairs); 
        T FindOne(IDictionary<string, object> propertyValuePairs); 
        T SaveOrUpdate(T entity); 
        void Delete(T entity); 
        IDbContext DbContext { get; }
}

As you can see, in this case we need two generic type arguments: one for representing the type of element the repository works with (T) and the other to set the type of the ID field (IdT). Besides the expected methods (Get, GetAll, SaveOrUpdate and Delete, which are self explanatory), there’s also a couple of members which deserve special attention:

  • FindAll receives a dictionary which contains several entries that filter the returned result set. You’re supposed to use the name of a property as the key and its value for specifying the desired values of that property. The method will return all the elements that have those values in the specified properties;
  • FindOne: similar to the previous method, but in this case, it will return a single instance;
  • DbContext gives you a reference to an object that lets you have access to the general database context associated with the current call.

Since you might be a little confused with DbContext (of type IDbContext), here’s the current API of that type:

public interface IDbContext {
        void CommitChanges();
        void BeginTransaction();
        void CommitTransaction();
        void RollbackTransaction();
}

As you can see, this interface encapsulates all the things you generally need to do in order to work with transactions.

There’s also a specific IRepository interface which uses an int for the ID’s type:

public interface IRepository<T> : IRepositoryWithTypedId<T, int> { }

As we’ve seen in a previous post, S#arp is heavily influenced by NHibernate. So, it shouldn’t surprise you to see that there’s a specific interface that gives you access to all the things you’re used to when working with NHibernate:

public interface INHibernateRepositoryWithTypedId<T, IdT> : IRepositoryWithTypedId<T, IdT>    {
        T Get(IdT id, Enums.LockMode lockMode); 
        T Load(IdT id); 
        T Load(IdT id, Enums.LockMode lockMode); 
        IList<T> FindAll(T exampleInstance, params string[] propertiesToExclude); 
        T FindOne(T exampleInstance, params string[] propertiesToExclude); 
        T Save(T entity); 
        T Update(T entity); 
        void Evict(T entity);
}

public interface INHibernateRepository<T> : INHibernateRepositoryWithTypedId<T, int>, IRepository<T> { }

As you can see, the previous repository interface is augmented to give you full control over the things you’re used to setting when working directly over ISession instances.INHibernateRepository is there for the most used scenario: when the Id property is stored as an integer in the database (just like we had with Entity vs EntityWithTypedId for entities).

And that’s it. Keep tuned for more in S#arp

by luisabreu | 2 comment(s)
Filed under:
Browsing through Stackoverflow
Tue, Apr 21 2009 9:48

Today I took 10 minutes of my time and I’ve decided to use them in browsing through Stackoverflow. It completely blew me away…They have done a fantastic job in building a great software developer community which is open to anyone. This is going to be a great place to visit regularly. From now on I’ll surely dedicate 10 minutes each day to browse through the discussions (I’m sure I’ll learn something and, who knows…I’ll probably might even answer one or two questions)

by luisabreu | 1 comment(s)
Filed under:
The S#arp framework: working with entities
Mon, Apr 20 2009 22:07

Today we’re going to keep looking at the S#arp architecture and we’re going to talk about the existing interfaces and base classes that let you work with entities. Before going on, I guess that we should define the concept of entity. According to Eric EvansDDD book, you’ll find that “Some objects are not defined primarily by their attributes. They represent a thread of identity that runs through time and often across distinct representations. Sometimes such an object must be matched with another object even though attributes differ. An object must be distinguished from other objects even though they might have the same attributes. Mistaken identity can lead to data corruption.”

As you can see, an entity has a very different behavior from a value object (already presented in earlier posts about this framework). With an entity, you must have some way to follow its life cycle and guarantee that every entity is uniquely identified on your system. We already have good  identity management in the OO world in .NET (whenever you create a new object, you get a reference and you can use that to manage an object’s lifetime and identity). 

Unfortunately, things might start to go awry when you need to mix OO life time management with persistency (generally, this means using a database, though it’s not mandatory). In this case, the default object identity you get for free from the base class is no longer enough for guaranteeing  the identity of an object. If you think about persisting an object in the database, it should be fairly obvious that if you save an object and load it several times then those objects “should” be equal. You don’t get this by default in .NET because you’ll end up with different instance references on different memory positions.

The S#arp framework introduces several interfaces  and base classes that you might use to help you solve these problems (as you can see from the following figure)

b

Lets start with the IEntityWithTypeId<T> interface:

public interface IEntityWithTypedId<IdT> {
   IdT Id { get; }
   bool IsTransient();
   IEnumerable<PropertyInfo> GetSignatureProperties();
}

As you can see, it’s really a simple interface which lets you:

  • get a value that uniquely identifies an instance (Id property). This is generally the key that uniquely identifies a persisted element in a database;
  • check if an object is transient or if it has already been persisted (that’s the job of the Transient method);
  • get the list of properties used for the business signature of an instance.

As you can see, this is  a generic interface where the type argument identifies the type of key you’re using (I’m under the impression that most guys will go with int (System.Int32) and identity fields on the database – even though identity is broken in SQL Server).

The framework introduces a base class that implements this interface: it’s called EntityWithTypeId<T>.  Besides implementing the interface, the class also extends the ValidatableObject class. Implementing the IsTransient method is really simple: you just compare the value of the private field (used for persisting the value of the Id property) with the default value of its type (ie, you check if the current value in that field equals the default(T) value).

The implementation of the GetSignatureProperties is inherited from the ValidatableObject base class, which ends up inheriting the BaseObject’s implementation. I’m sure you recall that BaseObject introduce this method in order for a class to return a collection of PropertyInfo objects which represent its business signature and relies on the template method pattern for delegating the obtaining step in a more derived class. In practice, this means that a derived class should only override the GetTypeSpecificSignatureProperties method. Let’s see the current implementation of that method in this class:

protected override IEnumerable<PropertyInfo> GetTypeSpecificSignatureProperties() {
   return GetType().GetProperties()
                .Where(p => Attribute.IsDefined(p, typeof(DomainSignatureAttribute), true));
}

As you can see, we use some LINQ in order to get all the properties annotated with the DomainSignatureAttribute attribute. This is just a simple marker attribute which looks like this:

[Serializable]
public class DomainSignatureAttribute : Attribute { }

The idea is that all classes that derive from EntityWithTypedId can just annotate its business signature properties with this attribute instead of overriding the GetTypeSpecificSignatureProperties method (like we did in a previous post).

The class performs one final step in order to ensure that everything works well: it overrides the Equals method. This is probably the most important thing this class does. Lets take a close look at its implementation:

public override bool Equals(object obj) {
    EntityWithTypedId<IdT> compareTo = obj as EntityWithTypedId<IdT>; 
    if (ReferenceEquals(this, compareTo))
               return true;

    if (compareTo == null || !GetType().Equals(compareTo.GetTypeUnproxied()))
               return false;

    if (HasSameNonDefaultIdAs(compareTo))
               return true;

    return IsTransient() && compareTo.IsTransient() &&
               HasSameObjectSignatureAs(compareTo);
}

The first lines should be self explanatory: if both elements are of the same type and point to the the same reference, then they must be equal. Now, if that isn’t the case, then several things might be happening here…

The first test that is made ensures that two objects are equal if they have the same non default ID. This means that if we have two objects that have already been persisted, then they are equal if their IDs are equal. Here’s the code for the HasSameNonDefaultIdAs method:

private bool HasSameNonDefaultIdAs(EntityWithTypedId<IdT> compareTo) {
  return !IsTransient() &&
             !compareTo.IsTransient() &&
             Id.Equals(compareTo.Id);
}

If that test fails, then we rely on the business signature comparison inherited from the base class but only if both objects are transient!

Let’s have a quick recap on this important class:

  • it has a property (Id) which is generic and is used to identify the ID you’re using to identify your object in a persistence medium;
  • derived classes can use the DomainSignatureAttribute to annotate the properties that should be used in the business signature of the object;
  • Equality implies doing these three tests in order: 1) do both objects point to the same reference? 2)have they been persisted and if that is the case, do they have the same signature? 3) are both objects transient and, if so, do they have the same *business* signature? whenever one of these tests returns true, the others won’t run; if none returns true, then Equals returns false;
  • Since this object expands the ValidatableObject, then all EntityWithTypedId<T> instances are capable of performing validation.

We’re still missing one class: Entity. It’s objective is to set the type argument of the “open” base class to int since ints tend to be the most used types for keys in databases. Now that we’ve presented the class, it’s time for a quick example. We’re going to build in previous example, and we’re going to transform SimpleAddress into an entity:

public class SimpleAddress:Entity, IHasAssignedId<Int32> {
    public SimpleAddress(String street, String zipCode ) {
        Street = street;
        ZipCode = zipCode;
    }
    [DomainSignature]
    public String Street { get; private set; }
    [DomainSignature]
    public String ZipCode { get; private set; }
    public void SetAssignedIdTo( int assignedId ) {
        Id = assignedId;
    }
}

Notice that we’re passing the street and zip code values through parameters to the constructor. As we’ve said before, it’s important to guarantee that business signatures don’t change and that’s why we’ve made the setters private (if those properties did change, we’d be in deep trouble if we also relied on hashes generated by the base class)

Yes, there’s also something new here: SimpleAddress implements the IHasAssignedId<T> interface. This  interface has only one method (SetAssignedIdTo) which can be used for an external entity to set the Id property of the entity (notice that Id is implemented with a public getter and a protected setter on the base EntityWithTypedId<T> class). Now, if you run the next snippet:

static void Main(string[] args)
{
    var address1 = new SimpleAddress(  "Street X", "SomethingElse");
    var address2 = new SimpleAddress("Street X","SomethingElse");
    Console.WriteLine( "address1 == address2 : {0}", address1.Equals(address2));
    Console.WriteLine( "address1 is transient {0}", address1.IsTransient()  );
    Console.WriteLine( "address1 is transient {0}", address2.IsTransient()  );
    //make address 1 non transient (fake it)
    address1.SetAssignedIdTo( 1 );
    Console.WriteLine("address1 == address2 : {0}", address1.Equals(address2));
}

You should get something like this:

a

And that’s it for today. Keep tuned for more on the S#arp framework.

by luisabreu | 4 comment(s)
Filed under:
Fog Creek guided tour
Mon, Apr 20 2009 14:39

I guess that by now everyone has heard about Joel Spolsky and his company (Fog Creek), right? Ok, if you’ve got a minute, then watch this guided tour around their offices…the only thing I can say is that they do have excellent work conditions and that I’d love to work in a place like that one day!

by luisabreu | with no comments
Filed under:
2009 Lang.NET Symposium
Sun, Apr 19 2009 19:10

Videos available.

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