Dependency Injection Inversion Rejection

January 29th, 2010

In Uncle Bob’s blog on dependency injection, Dependency Injection Inversion, he says that “you should carefully restrict how and where you use [dependency frameworks].” While I don’t necessarily disagree with the statement itself, I do have some concerns about his reasoning and his general view on DI.

The first concern I have is that his general idea and purpose of DI is not accurate, in my opinion. He stated that “the goal of these frameworks is to help you create instances without having to resort to new or factories”. In my opinion, that is not at all what dependency injection is about. Dependency injection is about, as its name suggests, removing dependencies from your code, decoupling your code, making it more maintainable, and testable, among other things. His examples didn’t show why someone would ever use DI. As he stated “My goal is to create an instance of BillingService.” While I agree with his purpose for writing the blog, that you shouldn’t use something just because its new, everyone is talking about it, or without reason, I just really feel like his example missed the point. I can make a really good argument of why you shouldn’t use any particular pattern, such as MVC/MVVM or Decorator, etc, if I show you an example that doesn’t show the pattern’s value or purpose.

Also, I wasn’t sure of the reasoning for suggesting to use instances or factories in his example? I think he was trying to make it so he didn’t have to use “Guice” (which is the DI framework he uses) all over his code.

BillingService.factory = new BillingServiceFactory(injector);

// Deep in the bowels of my code.
BillingService billingService = BillingService.factory.make();

??

As I stated, the goal is NOT to stop or reduce using new (although it is a side effect of the pattern but not the purpose), and you don’t have to use singletons or factories. I extremely dislike that solution because you are changing the way you design/implement your classes based on the fact that you use a DI framework, which I think is wrong. Not only that but it would be really cumbersome to make a factory for each class that you want to use DI with. The point is to reduce dependencies between concrete classes and program to an interface. So if you don’t want that framework all over your code, which i wouldn’t want either because that creates a dependency which is the opposite of what we are trying to do, I would create a wrapper for the DI framework.  That way the application would not depend on the framework and it can be swapped out with another. Now you don’t have factories or instances everywhere and you are not tied to a DI framework. This also brings up another issue. I’m not sure I agree with frameworks that use attributes or annotations inside the classes you are trying to inject on. For example, Guice (Java) requires the @inject annotation and Ninject (.NET) requires the [Inject] attribute on the constructor of your class. This creates a dependency on the framework and besides that you should never have to pollute your code with these kinds of things (those classes should have no knowledge that they are being instantiated by a framework and should not be required to).

His example is in Java, where as I come from the .NET world so i am not familiar with DI frameworks in Java. For .NET, one of the most popular frameworks is Castle Windsor, and you can find an excellent in-depth explanation of DI and Inversion of Control using this framework here.

Author: Shane Kercheval Categories: Uncategorized Tags:

Opening VS2010 gives ‘The Application Cannot Start’ Dialog

December 9th, 2009

So I’ve been using VS2010 beta 2 for the past couple of weeks and this morning i go to start it up and i get this “Application cannot start” BS

No matter how many times I try its the same thing over and over again. Dang. What do i do? Google. Then I’m reading about how these other guys have the same problem and they have tried uninstalling and reinstalling and the problem does not go away. Dang. Rebuild my box? MY WORK BOX?  This is a good way to start out the day. Uhhh. I don’t think so. So i do some investigating because I actually had visual studio freeze the night before and I think i just killed the process and was done for the night. So more then likely something was corrupted. Something that doesn’t get uninstalled if you to to reinstall (based on the fact that reinstall doesn’t work according to the other people). Well, I stumbled across this and also the solution. It appears there are a few ways to get into this state this seems like the most likely for me.

The second way to get in this state is by a corrupted window profile – the file that persists your IDE window state.  If you have floating tool windows (e.g., drag off Solution Explorer to another monitor or show the Find dialog), minimize Visual Studio, and then close Visual Studio from the minimized state, on the next launch you will hit this error.

The Workaround

  1. Start Menu->Run (or Windows Key + R for the keyboard savvy)
  2. Type “devenv /resetuserdata”.  The issue should now be fixed.
  3. If you wish to reimport your old settings, go to Tools->Import and Export Settings, select “Import selected environment settings and browse to the .vssettings file you saved.
Author: Shane Kercheval Categories: Uncategorized Tags:

Part 2: Building The Basics: Silverlight 3, .NET RIA Services, & NHibernate (Fluent)

October 4th, 2009

UPDATE (February 22, 2010) : a newer release of Silverlight and RIA Services broke my code. Shaun was kind enough to make the necessary changes and let me know and you can find his post on the fixes and the code here.

Download the (original) source here.

Silverlight is a web application framework that provides a very solid foundation for building Rich Internet Applications (RIA) that are cross-browser compatible, and can run on Mac OS, Windows, and Linux. In general, any Line of Business (LoB) type application should have multiple tiers to separate the different business and development aspects of the project.  “Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. The RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.” – Microsoft Marketing Blurb. So with Silverlight and .NET RIA Services we have set up a very solid foundation for creating a LoB Web Application. However, what about the database? Any large or even medium size application (web or standalone) more then likely needs a database. The problem is that relational databases and object-oriented programming (OOP) have very different views on data. Data in OOP is represented by objects, and those objects can contain scalar values (such as integers and strings) as well as other objects. Databases, however, typically only store scalar values. There is no direct way to map objects to databases. The solution: we use a Object-Relational Mapping (ORM) framework (in my case NHibernate) to bridge this gap and allow the database schema to be defined based off the software’s business entities. NHibernate lets you build up the database as you go, because, in my opinion, in a large-scale application, it is not possible to have a solid database implementation based on the requirements alone. Requirements change, design ideas change, perspectives change. Why would you spend so much time up front on the database when it is at the beginning of development that requirements are more likely to change. Also, to me, it doesn’t make sense to have to wait for the database to start development. Start developing, and let the database get built up based on your development. To make minor changes you make them once in code and your DB schema automatically (in a sense) adapts to what you are doing in code. So this way your not working around your database, you are making your database work around you. Makes sense to me. But what do i know? So bring Silverlight, .NET RIA Services and NHibernate together we have set up an environment that i believe will help the application become very stable, maintainable, and a joy to work in. So lets see what i have done so far. I have attempted to put together a “skeleton” of what I think a Silverlight project should look like. Keep in mind that I’m new to Silverlight, .NET RIA Services, and NHibernate so my views might not be the best ways of doing things. But i definitely appreciate feedback and any ideas on improvement.

LoB applications have data that needs to flow from the database (data layer) to the user interface (UI layer) and back. Ideally, data validation should be done in two places, at both the UI layer and at the data layer. The UI should warn users if they are entering invalid data (but should not have to go to the database to know what constitutes valid) and the database should not trust that the UI is giving it valid data. So a (terribly) common practice is to write your validation in two different places, two different ways. What RIA does is it allows the user to write validation and “server” logic in ONE place, and exposes it to both the client and server components in a way that all components can take advantage of it. This makes the application more stable and maintainable then an application that has code that does the same thing written twice. It also keeps your data access logic out of your client, which is the way it should be.

NHibernate

Originally, when setting up NHibernate the user would create the entity classes and then configure everything (mapping fields, relationships, etc) via XML files. Fluent NHibernate provides a framework for writing the mapping information in strongly typed C# code using the fluent interface. Lets look at the Contact entity and its corresponding mapping class.

ContactEntity

Figure 1- Contact Class

The first thing you will probably notice is that Contact derives from Entity. Entity is just an object that has an EntityId property as well as overridden Equals and GetHashCode methods. Contact is a simple class that has various properties. No big deal. You will notice, however, that there is one or more attributes with all of the properties. This is not a requirement, but one of the powerful tools to take advantage of.  This automatically applies client side and server side validation as we look at later.

The corresponding Fluent NHibernate class map is shown in Figure 2.  ContactMap maps each property and tells NHibernate that the corresponding property is to be mapped to a certain property in the database (which NHibernate will build for you). Mapping is done by passing in lambda expressions to the Fluent NHibernate’s mapping methods.                                        Map(System.Linq.Expressions.Expression<System.Func<T,object>>) maps a simple property. There are different methods used for different mapping situations. For example, Contact has a list of Addresses. In a database we would have a table that represents all Contact properties/fields, and a table that represents an Address. In the object-oriented world we say that a Contact “has many” Addresses and we represent that by making Contact keep a list of all of its own Addresses. However, on the other side of the fence, in the relational database world, we represent a Contact relationship by having a foreign key in the Address table. So each address points back to the contact that is associated with that address. So in the database it is the address’s responsibility to keep track of which contact it belongs to. Quite a difference between the two data models (which is why, obviously, one reason why we need an Object-Relational-Mapping Framework). In order to transparently handle this difference, we use the HasMany method. This allows NHibernate to automatically set up a foreign key column in the Address table for the Contact it is associated with. We are also telling NHibernate to not use lazy loading, and to set cascading to all. Lazy Loading is when the object, or its members are not initialized/retrieved (via hitting the database) until the point of which it is necessary. This is useful for large structures that might take a significant amount of time to load, but whose class members aren’t necessarily needed right away. It provides a quicker way to get necessary data without loading EVERYTHING at once. Cascading refers to the idea that every object, or entity, has associations with other entities, (one to many, many to one, etc) and when updating [to the database] one object, for example, Contact, you may or may not want to update all the associated entities. Cascade.All() tells NHibernate that when an operation is done against an object (save/update/delete), check the associations and save/update/delete all the objects found that belong to or are encapsulated within Contact. So in this case, deleting a Contact object will result in deleting all the Addresses associated with that object, which makes sense because an Address has a Contact as a foreign key, and does not make sense to keep if it has no associated Contact.

ContactMappings

Figure 2- ContactMap Class

DomainMap

Figure 3- DomainMap Class

Conventions

A “convention” in the way that I am about to talk about it is NHibernate’s way of setting options on database fields (unique, not null, length requirements, etc).  NHibernate provides the means to define conventions via a series of interfaces of varying degrees of granularity; any classes implementing any of the interfaces will be hooked into the mapping generation cycle via a method call. Because each convention is an interface, it means you can implement multiples of them in a single class, which allows the grouping of common conventions into a single class if desired. Lets look at a simple example. UniquePropertyConvention inherits from the AttributePropertyConvention class which is the base class for attribute based conventions. As you can see you simply override the Apply method. The first parameter is the attribute class that was passed in as a generic parameter and the second is a reference to the current instance that the convention is being applied to. It exposes many methods and properties that one can set to configure any property (or field in the database) that is marked with the corresponding attribute. So in our example, in Figure 4 below, UniquePropertyConvention is linked with the UniqueAttribute, so any property that contains this attribute is marked as “Unique” by NHibernate and enforced in the database schema.

conventions

Figure – 4

If we look at Figure – 1, we see that there is a “Required” attribute applied to all properties, as well as a “StringLength” property applied to FirstName and LastName. Here is the generated table definition.

create table [Contact] (
Id  integer,
Gender TEXT not null,
FirstName TEXT not null,
LastName TEXT not null,
BirthDate DATETIME not null,
primary key (Id)
)

As you can see there is a “not null” option applied to each field. This comes from one of the custom NHibernate’s conventions defined in the project. You will also notice that there is no string length option for FirstName or LastName. This is because the TEXT data type in SQLite has no length option.  If we were to use SQL Server we would have seen this applied. However, we still want to apply this attribute because it will still be recognized and enforced on the client side, as you will see.

NHibernate Sessions

ISession is the primary interface used by NHibernate applications for database operations. It exposes methods for finding, saving, updating, and deleting entities. A session can be thought of as something between a connection and a transaction. Think of a session as a cache or collection of loaded objects related to a single unit of work. It is very inexpensive to create or destroy and is usually created and then discarded when needed.

An ISessionFactory, on the other hand, is not lightweight, and is intended to be shared among the entire app as a single (typically static) instance. It caches generated SQL statements and other mapping metadata for NHibernate and is what creates sessions via the OpenSession() method. Figure 5 shows the implementation of the NHibernateSessionFactory, which encapsulates the ISessionFactory.

NHibernateSessionFactory

Figure 5 – NHibernateSessionFactory Outline

As you can see, there is a static (readonly) property that contains the ISessionFactory object. This property checks to see if the _sessionFactory member is null, and if it is, it creates a new one using the CreateSessionFactory method shown in Figure 6.

CreateSessionFactory

Figure 6 – CreateSessionFactory Method

This method takes a single Boolean parameter, needToBuildDatabase, which, as the name suggests, specifies whether or not we need to build the database (for testing). So my solution calls this in two places, once in a test, where I build up the database and populate it with default values (and therefore, pass in true to this method), and the other is described above in the SessionFactory property where it is passed a value of false. Both BuildDatabase() and the last return statement in CreateSessionFactory() use the Fluently.Configure() method to start fluently configuring NHibernate and eventually build the ISessionFactory using … can anyone guess… that’s right.. the BuildSessionFactory() method. From Figure 7, you can see the implementation of the BuildDatabase() method.

builddatabase

Figure 7 – BuildDatabase Method

As stated before, Fluently.Configure() fluently starts the configuring of NHibernate and this is where the user specifies the mappings, conventions, etc. This is also how we export the end result NHibernate configuration xml files (using ExportTo(string pathToExportTo)) and the building up of the database (using Export() method that is apart of the NHibernateSessionFactory class). So basically how I have set this up to work is when you are running tests, it wipes out the database and builds it up from scratch, inserts dummy data, and then I test to verify that the data i expect to be there is, in fact, there. If you are simply running the application, it will only build the ISessionFactory, it will not rebuild the database.

Domain Service

A DomainService is basically a class that encapsulates server side logic and database services that is eventually projected to the client side, allowing the user to centralize server (or service) logic and keep that logic out of the client side code. Lets look at my custom DomainService class in Figure 8.

BusinessAppDomainService

Figure 8 – BusinessAppDomainService

This domain service contains all the logic necessary to communicate with the database and perform the CRUD (Create, Read, Update, Delete) operations. There are naming conventions and requirements but that is out of the scope of this blog and can be read in the RIA documentation (RIA Services Overview). This class uses the current NHibernate session object (which is created by NHbernateSessionFactory) for these operations. As you can see NHibernate provides a simple interface for reading/updating from the database. You can perform Linq operations on the data as well.

As I described in the previous post, when the project is built, a DomainContext class is created, which is basically a client side proxy to the DomainService class. Please examine this file (\Generated_Code\BusinessApp.Web.g.cs) in the BusinessApp project to see the code generated. It is pretty self explanatory. RIA services also adds quite a bit of code for you. Check it out.

DataGrid

datagriddddddd

Figure 9 – DataGrid Example

This is pretty straightforward. We define a DataGrid and set some of its properties. We explicitly define each column (this isn’t a requirement but the column automatically takes the database field name if not, so instead of displaying “FirstName” we want it to display “First Name”, etc). We bind each column to a field in the database table we are binding to. At the last minute i stuck in another field, BirthDate because i wanted to demonstrate how to define and use “Converters”, which allows the programmer to define how to represent the data. So for example, the DataGrid displays a DateTime object by calling the ToString() method on it, which is probably not what we want. So how do we take any object and tell the DataGrid how to display it? We use an IValueConverter, seen in Figure 10.

ivalueconverter

Figure 10 – DateConverter

The IValueConverter interface defines two methods: Convert and ConvertBack. So we are basically creating an object that defines a way to convert an object from one specific type (DateTime) to another that the control is expecting (String) and back. So to convert it to a String I simply build up the format that i want the user to see in the DataGrid. To convert it back to the a DateTime object i use a regular expression to extract the data from the format that I defined and am expecting and then use that data to build the original DateTime object. I’m sure there is a better implementation (and feel free to share), this was just thrown together.

So going back to Figure 9 we see that I used DataGridTemplateColumn.CellTemplate object to bind the column to the BirthDate field (which is a DateTime object) and use the custom converter to display the DateTime string how I wanted.

You will also see from Figure 9 that I defined a simple DataPager and hooked it into our DataGrid. This does all the work for us and if you run the app you will see that we get a DataGrid that displays ten Contacts at a time. In the DomainDataSource, whose definition is not shown, but can be viewed in the Contacts.xaml file, you can see that I specify the LoadSize property to be 20, which tells RIA to only pull 20 Contacts at a time from the database. This improves performance significantly, and is a must when working with large databases. So if you run the app, go to the “Contacts” page, let the data load (we are hitting the database here), and then go to the next page, it will not hit the database again, but will instantly load the next ten Contacts. However, going to the next page (3) forces the service to go back out and grab the next 20 contacts.

.NET RIA Services also provide the hookups for automatic client side validation via the attributes that we set in our Entity classes. So applying the RequiredAttribute on a property not only applied the validation against the database, but also on the UI. See Figure 11.

watever

Figure 11 – Client Side Validation

This is extremely awesome.  I didn’t write anything else to make this message pop up. You can change the error message by specifying within the attribute you are using with the ErrorMessage property. For example, (see Figure 12)  if i wanted to use a regular expression for error validation, I could define my regular expression and then use the ErrorMessage property to explicitly define what the DataGrid will display if that particular validation fails. The same thing applies for the RequiredAttribute and many others.

regex

Figure 12 – Using Regex for validation

How is all of this done? Lets turn on all exceptions in Visual Studio (Debug –> Exceptions) and then type more then 30 characters into one of the FirstName fields in the DataGrid and then try to click away or press enter. We can see that the FirstName property (seen in Figure 13) of the Contact class DEFINED IN THE BusinessApp.Web.g.cs file (via projection from server) has an exception thrown when validating the property. The exception says “The field FirstName must be a string with a maximum length of 30”. So when I hit enter or try to click away from the DataGrid, the binding of the FirstName property kicks in and it tries to set this property. The first thing the setter does is validate that the value passed in doesn’t break any rules that I have applied (Required,StringLength).  This is all RIA generated code that we get for free.

validationexception

Figure 13 – ValidationException within FirstName

Conclusion

I believe we know have a solid foundation to start with in our Silverlight, .NET RIA, and NHibernate application. I started with the with the backend and showed how to build up the SQLite database from within the code, letting your database work around you, instead of you working around your database. I then showed how all this was configured and how it tied into the RIA Services, and finally, how it was all automagically projected to the client side.

Thanks to Jason Morse who helped me get going on a lot of this and whose code some of my code is based on :)   Also thanks to Brad Abrams and his post whose code was also the basis of some of mine as well.

Author: Shane Kercheval Categories: Uncategorized Tags:

Silverlight Tutorial: Part 1- Getting Started

August 25th, 2009

Download Code By Clicking Here

Techs Currently Used

Windows 7

Visual Studio 08

Silverlight 3 SDK, Silverlight Web Platform, Silverlight Toolkit, .NET RIA Services (http://silverlight.net/GetStarted/)
NHibernate

 

We’ll start off pretty basic by just creating a Silverlight project and adding a new page to the application. Visual Studio makes it extremely easy to create a Silverlight project and get it up and running. Start off by creating a new Silverlight Business Application project.

Picture 1

Figure 1 – Creating a Silverlight Business Application

 

The difference between a Silverlight Business Application and a Silverlight Navigation Application is that the Business Application provides login/logout and authentication support. Clicking “login” will show a clean login screen with a link to a  “new user” template. Both projects give the same clean look and feel and default pages.

At this point, we have created our “BusinessApp” solution with two projects within that solution: BusinessApp and BusinessApp.Web). BusinessApp contains the Silverlight code and i will refer to at as the client project. It is the client tier. BusinessApp.Web contains the ASP.NET web application code that will be responsible for running the Silverlight application. It’s referred to as the server project and is the mid-tier. I like to think of it as the service layer because that is where we will be getting all of our services from. 

Lets build the solution, click on the client project, and then click the “Show All Files” button. You will notice that there is a file named BusinessApp.Web.g.cs. (See Figure 2) This file is generated by the server project (specially the .NET RIA Services) and projected to the client so that the client and server work with the same data and objects.  We will discuss the .NET RIA Services in depth in a later post, but basically (from a Microsoft marketing blurb) the “Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. The RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.”  So in order for the Silverlight client to absorb the projected code generated by the server project, we need to include it into the client project by right clicking on the generated code file and including into the project.

Picture 2

Figure 2 – Generated Code

 

This will be important later on when we use RIA Services to create domain services (which i will discuss in a following post) in the server project which are then generated into its equivalent client side domain “context” classes. One of the great benefits of Silverlight and RIA is that it makes validation at both the client and server sides possible with writing the code only once. This code is centralized in the server project and then projected into the client project via the generated code file. You will see more uses of the generated code file throughout the series. Basically everything that is projected from the server will be found in this file.

The application should build and run successfully. As you can see in Figure 3, the default Silverlight template provides a very clean and professional look and feel. The look and feel can be easily changed by modifying the Styles.xaml page which can be seen in Figure 2. Users will be able download pre-defined Styles and easily swap them in and out to change the look and feel. This means that you can have several style xaml files and switch between them as necessary.

Picture 3

Figure 3 – Sexy Default Style

 

Lets add a page to our application so we can see how easily this is done. First, right click on the “Views” folder in the client project, which is where all of the Silverlight pages are stored by default.

Picture 4

Figure 4 – Creating a new Silverlight Page

Name your page to whatever you want (I named mine “Contacts” because…. well i don’t really know actually) and click “Add”. In Figure 5 you can see that I added a TextBlock to the Contacts.xaml file and if you run the application (after the next step that is) you can see that show up on the Contacts page.

 

Picture 5

Figure 5 – Adding content to the “Contacts” page

 

To add a page to the navigation panel along with Home and About pages, open up the MainPage.xaml file and add a HyperlinkButton in the place you would like the tab to appear. By default, Silverlight separates the tabs with a Rectangle object defined by the LinkStyle static resource in the Style.xaml.

Picture 7

Figure 6 – Adding a link to the Contacts page

 

If we build and run the web application you will see that there is now a “Contacts” tab in between the “Home” and “About” pages. Clicking that should take you to the Contacts page.

 

Let’s talk a little about what’s going on behind the scenes. If you look in the server project you will notice there is a .xap file in the ClientBin folder.

Picture 6

Figure 7 – xap File

A .xap file is essentially a compiled Silverlight application that is actually a .zip file. This zip file contains all the files necessary for the application. You can rename the .xap file to have a .zip extension and then extract it to view the contents. The .xap file contains an application manifest (AppManifest.xaml) file and all the necessary DLL’s that are required by the application. Web pages like .aspx files use the Silverlight components by loading the .xap files using the <asp:Silverlight> tag in the ASP.NET pages. In Figure 7 you will see the BusinessApplicationTestPage.aspx file that was created by Visual Studio. This is page that gets started by the server project. In Figure 8, you see that the aspx file is responsible for wiring the xap file to the server project.

Picture 8

Figure 8 – BusinessApplicationTestPage.aspx

The last thing I personally was wondering about was the Silverlight.js file in the server project. I was a little curious what this was for and I’m sure others are as well. According to MSDN, “the Silverlight.js file provides JavaScript helper functions for embedding the Silverlight plug-in in a Web page and for customizing the Silverlight installation experience.” Sweet. Not critical for me at this point but definitely a nice to know.

 

Well i think that’s the basics of a Silverlight application.

Author: Shane Kercheval Categories: Silverlight Tutorial Tags:

Silverlight 3, .Net RIA Services, MVVM, NHibernate + more

August 22nd, 2009

Recently I started working on a side project with a fellow colleague. This is a line of business web application for an awning manufacturer called The Awning Factory. We are using Silverlight 3 with .Net RIA Services, the Model-View-ViewModel pattern (MVVM), NHibernate, along with other testing and development technologies. Jason, who started the project and has invited me to come on board, is blogging about this project (click here to go to his blog). He is discussing the overall business rules and structure of the project, as well as the software development architecture, including programming patterns and models used. I have chosen to blog (through a step-by-step demonstration) about the implementation aspect and how the patterns and technologies can be used together to form a line of business application. I have chosen to create a separate demo app rather then use examples from our application. I want to do this for a couple of reasons. First, the reason for this series is for my own investigation; so i can have a deep understanding and make sure i know how everything fits together. In order accomplish that i need to build something from scratch and really dive into the details as i go, as opposed to trying to get it together and running and not caring about the details. Next, i want something that myself and others can look at without having unnecessary details get in the way of seeing what i am trying to show and explain. I also need to develop something that can be downloaded, built, and ran successfully without any setup besides the installations of necessary components (like the .Net RIA Services). Since most of my development effort will be directed towards the main project, this will be a small project,which will allow the user to see the different aspects that Silverlight brings to the table. Game On.

Author: Shane Kercheval Categories: Silverlight Tutorial Tags:

Logging with Aspect-Oriented Programming (AOP) & PostSharp

May 13th, 2009

Download Source Here: loggingwithaop (You must install PostSharp, which adds the PostSharp dll’s to the .Net reference list. PostSharp is free and easy to install)

One thing that has always bothered me is seeing logging statements all over in code, making the code less readable, and adding lines of unnecessary and repetitive code.  I’ve always wondered how to get around this, because in order to log what you want, you have to have code there to do it, right? At least that is what I thought until I stumbled across Aspect-Oriented Programming (AOP) with PostSharp.

AOP is a new technology or paradigm for separating crosscutting concerns (such as logging), that are usually difficult to implement in object-oriented programming.  Logging would be considered a “crosscutting concern” because, even though it is not the main concern of the program, it still affects many parts of the system. With Aspect-Oriented Programming, you implement your project using your OO language (c# for me) just like you would do normally, and then you deal separately with your crosscutting concerns in the code by implementing “aspects”. (One aspect could be logging, or security).  Finally, both the code and aspects are combined into a final executable form using an aspect weaver. So your objects go unchanged and uncluttered while adding in the aspect you want. If you are like me this is a little hard to picture without an example. Stay tuned.

PostSharp is a library for the .Net Framework that allows programmers to easily apply AOP techniques via class and method attributes. It transparently inserts itself in the build process and post-processes the compiled assembly. Since PostSharp works at MSIL level, it supports virtually all static languages targeting the .NET Framework.

In my example, each class adds a class attribute (the aspect) that will resolve the log level and encapsulate all of the logging logic that is executed. In the event that the user wants to have specific log statements, this is also possible by using the logging class directly. This logging example is implemented in such a way that log levels are dynamic, meaning you can create any combination of levels, and change any class level without having to recompile the program.

Lets begin with a simple class. Money.

public class Money
{
public Money() : this(0,0){}
public Money(int dollars, int cents)
{
if(dollars < 0 || cents < 0 || cents > 99)
{
throw new ArgumentOutOfRangeException();
}
Dollars = dollars;
Cents = (byte) cents;
}
public int Dollars { get; private set; }
public byte Cents { get; private set; }
public static Money operator +(Money a, Money b)
{
return new Money(a.Dollars+b.Dollars,a.Cents+b.Cents);//if the cents add up to more then 99 this will throw an exception
}
}

If we wanted to add trace or debug statements to this code we would have log statements at the beginning and end of each function/property, and also before the ArgumentOutOfRangeException, which should indicate some sort of error. Our properties would no longer be one line and the entire class would be less readable and convoluted with irrelevant code.  All this can be accomplished with a simple class attribute:

[Log("Money")]

.

The PostSharp.Laos namespace contains the OnMethodBoundaryAspect class that can be derived from. This contains the “OnEntry”, “OnSuccess”, “OnException” and “OnExit” methods that are overridden to implement behavior that fires when execution enters a method, returns from a method (OnSuccess only fires if the method has returned normally, i.e. not by an exception. OnExit executes regardless of an exception or not), or if a method returns because of an unhandled exception.   The following is an example of how to implement a custom logging attribute using the PostSharp library.

[Serializable]
public sealed class LogAttribute : OnMethodBoundaryAspect
{
public LogAttribute(string className)
{
_className = className;
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
LogLevel level = Logging.ResolveLogLevel(_className);
if (level <= Logging.SystemLogLevel)
{
string argumentString = BuildArgumentString(eventArgs);
Logging.Write(level,string.Format("Entering {0}.{1}({2})",
eventArgs.Method.DeclaringType.Name,
eventArgs.Method.Name,
argumentString));
}
}

This class is pretty straight forward. It overrides the OnEntry method, among others, so that any class that has the Log attribute will automatically have this method execute on any method, property or constructor that exists in the class. That is all the log code that is required. There is no need for logging statements anywhere in the code, although this is still possible if the user wants. The OnSuccess and OnException implementations are included in source code. The class simply adds the

[Log("ClassName")]

attribute. The name of the associated class is passed into the Log attribute constructor and when the OnEntry method executes, it resolves the log level that is registered with the associated class, which it grabs from an xml file. All classes simply have to pass in the name of class into the Log attribute and the Logging class resolves the level of the logging for the class. One advantage of this is that you can change the log level of any class or the log level of the system without having to recompile. This means if you have a problem in a particular part of the system you can easily turn the logging all the way up in that part of the system without slowing down the entire application.  I have even built a generic tool (which i have included in the source) that provides a GUI interface to change the log levels. This is generic enough to use with any program that follows a few simple rules. So you can use the same tool to control the log levels of any application.

The PostSharp library allows users to add attributes to not only classes, but also individual methods to allow different methods within each class to have different logging levels. My implementation of having each class register is own level does not as easily support this, because all logging is dynamic. The code does not know about the different levels, what they’re called, or the order of magnitude. This means you can’t programmatically call logging statements and specify the log level. However, I think the abstraction that is created has a much greater advantage then being able to label individual methods, which realistically wouldn’t be used. I’ve seen that throughout most classes, the level will be exactly the same for each method. There are exceptions however. You might want to log a specific error (one that is handled by the user because the OnException method will only log any unhandled exception. Or you might want to log a specific calculation or important value. This can be easily done using the Logging.Write(string customLevel, string message) method.  You can pass in a string to represent the level, but since logging is dynamic, technically, the code should not know which levels are valid. For this reason, in my example, every time i want to specifically write to the log file, i pass in a hard coded GUID for the customLevel parameter. This means that you can simply do a quick search for the GUID within the code and find it easily. This rule also makes it so if there are duplicate generic log messages, you can determine which one was logged.

When i run the application, i get output that is similar to the following:

<EXCEPTION>
<TIME>05/14/2009(mm/dd/yy)- 03:16:05 (utc)</TIME>
<MESSAGE>EXCEPTION: Money..ctor(System.Int32 dollars=="4",System.Int32 cents=="100",): Exception: Specified argument was out of the range of valid values.
Stack Trace:   at PostSharpTest.Money..ctor(Int32 dollars, Int32 cents) in C:DevelopmentPostSharpTestPostSharpTestMoney.cs:line 14</MESSAGE>
</EXCEPTION>
<EXCEPTION>
<TIME>05/14/2009(mm/dd/yy)- 03:16:05 (utc)</TIME>
<MESSAGE>EXCEPTION: Money.op_Addition(PostSharpTest.Money a=="PostSharpTest.Money",PostSharpTest.Money b=="PostSharpTest.Money",): Exception: Specified argument was out of the range of valid values.
Stack Trace:   at PostSharpTest.Money..ctor(Int32 dollars, Int32 cents) in C:DevelopmentPostSharpTestPostSharpTestMoney.cs:line 18
at PostSharpTest.Money.op_Addition(Money a, Money b) in C:DevelopmentPostSharpTestPostSharpTestMoney.cs:line 24</MESSAGE>
</EXCEPTION>
<A88D2E1F-8C36-4ac1-B7CC-DDE356847B1D>
<TIME>05/14/2009(mm/dd/yy)- 03:16:05 (utc)</TIME>
<MESSAGE>Invalid Money Value</MESSAGE>
</A88D2E1F-8C36-4ac1-B7CC-DDE356847B1D>

This gives you very accurate and relevant information: Date/Time (of course), the name of the method, the values passed into the method, the values returned from the method, and the stack trace on an exception. If you turn trace all the way up (“TRACE”) in the application (via “PostSharpTestApplication” setting in the “LogLevels.xml”, you will see that this happens for each method, property (get and set), and constructor. All this information is given back and the user doesn’t have to do anything for it.

In summary, application classes simply add the “Log” attribute to the class that the logging will be done in and pass in the name of the class to the attribute constructor. The log level gets resolved in the LogAttribute class. If necessary, the application classes can also use the Logging class to directory write to the log file, although this should be very infrequent.

In my opinion, post sharp offers a very clean way of performing very accurate and complete logging without cluttering up code. My solution offers logging that is abstracted from the user, and is dynamic in the sense that any log level can be added, deleted, or modified, and any class can change levels, without having to recompile.  Please post questions and comments for further discussion on Logging with Aspect-Oriented Programming.

Author: Shane Kercheval Categories: Development Ideas Tags:

Don’t Use Failure Names.. You’ll See What I Mean

May 1st, 2009

Listen, this my first blog, and its not going to be that deep of a conversation, but its something that i see all the time, and in my personal and semi-professional opinion it’s incredibly annoying, and even more important, pretty stupid.

Do not, under any circumstances, give “Failure” names to boolean values. This is what i mean:

bool unsuccessful = true; //stupid
bool successful = true; //smart

You might be thinking, “this isn’t a big deal Kercheval.. why are you writing about this.” But it is a big deal, and this is why. This is something I’ve seen in industry, and has caused me headaches.  When communicating with hardware, you often send and receive information/data in raw bytes, and each bit is some sort of flag. So say we have a byte that we get back from the hardware, and one of the bits represent an error. Say a communication error. Do you see the problem? It might be obvious to me because the problem punched me right in the face… So lets say its the right most bit that is the “Communication Error” bit. The code to see if there was an error would be:

byte result = getInformationFromHardware(); //so we went out to the hardware and communicated and it returned a byte of information
bool failure = result &amp;amp;amp; 0x01; //we bitwise and the result with 1 to get the right bit and if the bit is set, this represents a communication error

Ok.. this isn’t too bad. Seems reasonable.. But wait.. what are the default values for bytes, and shorts, and ints. 0. So if getInformationFromHardware() is really a c++ function and it doesn’t throw exceptions on failures (because it has the failure bits to tell you if there is an exception), but if there is an error and the return value never gets set then you have a good chance that you get the default value, 0, back. But since you named your variable “communication error”, or “failure”, then the bit has to be set to indicate a failure, but it never got set because there was a failure. So i assume success. Do you see why this is stupid now? You’re setting a value to indicate failure, but if there is a failure where you are not expecting it, the failure might cause the failure bit to not get set. Wow. Now i know this isn’t going to happen often, because usually (i develop in c# by the way) your managed code will call other managed code that will throw exceptions on errors, but if you’re calling unmanaged code, as is the case when you work with hardware, (from what I’ve seen) the code tends not to throw exceptions, because it tends to rely on return codes. (Although you can catch native exceptions use the Win32Exception class, and probably should have unmanaged code always wrapped in some sort of try/catch block. )

So while this probably isn’t the case most of the time, it was a headache for me because someone decided to name their variable a “Failure” name.

Ok. This wasn’t the most exciting or mind blowing post.  But i felt i needed to share why you should never do such a thing.

Blogging? Why?

April 26th, 2009

I must admit i never thought i would be a “blogger”. I’m reminded of the quote: “Never Before Have So Many with So Little to Say Said So Much to So Few.” (www.despair.com) Ain’t that the truth… So I imagine that I will be “Rambling” on about random topics and very few people will ever read my thoughts. But that’s ok. My goal is not to have a lot of people read my Ramblings. And now that I think about it I’m not sure what my goals are? Let me think… Lets make a list of my initial thoughts of why I decided to write so much to so few…

  1. I feel like I get so frustrated at the stupid things that i see in development (I’m sure people probably get frustrated at the stupid things i do in development too :) ) and sometimes it would just feel great to release my thoughts and frustration… even if nobody is listening.. :) so instead of talking to myself and feeling crazy i decided to write my thoughts down and pretend people are interested, which is debatably more crazier.
  2. To develop my writing skills. I’m not that great of a writer. I have always been a math/science guy and not that interested in English skills. So this is a good opportunity to improve. 
  3. To keep a record of my thoughts…. I think I will not only learn from what i write, but it will also be interesting to look back and either realize how smart i was at so young… :) … or how ignorant i was… either way I will enjoy looking back.
  4. My actual hope is that I find some people that like my Ramblings and offer feedback or a discussion and that I will actually LEARN, and not just Ramble.
    So…. lets blog.