Archive for the 'ASP.NET' Category

How to actually use trigonometry in web applications

Disclaimer: my teammate Dellanoce actually coded this, but is too cool to blog, so I am blogging for him.

Mailtrust has many different customers, some of which like to have their own branded control panel or webmail interface. We allow them to customize many different facets of the user interface, including colors. This has some unintended consequences though. Sometimes, a user might select a white font color on top of a white background. This in turns causes support to get involved in fixing the problem, which wastes time on such a trivial problem.

But there is a better way. Use trigonometry, or more specifically the Pythagorean theorem! I had no idea how this worked, but Dellanoce coded up a few lines of C# to compare two colors. It returns a distance value which can be compared to a threshold value you can set.

1
2
3
4
5
6
7
8
9
10
11
        private static double ColorDifference(string htmlColor1, string htmlColor2)
        {
            Color color1 = ColorTranslator.FromHtml(htmlColor1);
            Color color2 = ColorTranslator.FromHtml(htmlColor2);
 
            double rDiff = Convert.ToDouble(color1.R) - Convert.ToDouble(color2.R);
            double gDiff = Convert.ToDouble(color1.G) - Convert.ToDouble(color2.G);
            double bDiff = Convert.ToDouble(color1.B) - Convert.ToDouble(color2.B);
 
            return Math.Sqrt((rDiff * rDiff) + (gDiff * gDiff) + (bDiff * bDiff));
        }

I was quite impressed with the simplicity and elegance this solution provided. I should probably go give my, or his, trig teacher a hug.

If you want to learn more about how powerful Pythagorean theorem is to compare distance values of really any type of object, check this article out.

CallContext isn’t the greatest thing since sliced bread

In ASP.NET, it is quite common to need to store information in the context of a single web request. For example, a NHibernate session should usually exist for one web request. HttpContext is the tool for accomplishing this.

But what happens when you have code embedded in business logic that might not always be running in an ASP.NET web application? HttpContext isn’t valid, so you can’t use it. Why not use CallContext, since HttpContext uses this anyways?

I was starting to convert some of my code to use this, when I found this article. Apparently doing this works most of the time but can cause some nasty bugs since ASP.NET can switch HttpContext’s without switching CallContext’s.

Instead, code that could be called from ASP.NET and other applications should first check for context.

1
2
3
4
5
6
7
8
9
10
11
12
if(HttpContext.Current == null)
{
     //Using CallContext example since not in ASP.NET
     CallContext.SetData("blah", new object());
     object contextData = CallContext.GetData("blah");
}
else
{
     //Using HttpContext example since in ASP.NET
     HttpContext.Current.Items.Add("blah", new object());
     object contextData = HttpContext.Current.Items["blah"];
}

In fact, I will probably end up writing a static class to implement this so code doesn’t have to constantly check whether or not in an ASP.NET session.

Policy Inject Me

I just started using the Policy Injection Application Block from Microsoft’s Enterprise library. At first, I thought it was worthless and overly complex. I was wrong. It is a very powerful programming tool that allows me to develop a lot faster and cleaner.

Policy Injection is similar to aspect-oriented programming in that it helps to break away cross-cutting concerns (authorization, logging) from the actual business logic. And yes, I basically copied that from the documentation.

Here is what policy injection means for me. I can build business logic, which performs only what I want it to. So I can have a function called AddUser and all that is done is the actual operation of adding that user. I can then attach policies to that function, which specify how to authorize and log it. This has a couple effects. One, it reduces the amount of code which in turn cleans up the code. Second, it allows me to customize cross-cutting concerns for different projects. If I have an administrative application, I need to authorize differently than a user application. Policy injection makes this possible without dirtying up the code.

After the initial few hours of getting used to using it, I am a huge proponent. I definitely recommend checking it out.

NHibernate O/R Mapper: Part 2

In a previous post I talked about my first impressions of NHibernate. Not a whole lot has changed since then, except I have learned a lot more. But, I said I would discuss what I didn’t like about NHibernate so here it goes.

Session Management

The biggest thing that I don’t like is the session management aspect. Although I have come to understand why NHibernate sessions are so valuable and critical to its functionality, it doesn’t stop the fact that persistent objects are tied to a single database. For a project that follows the patterns and practices set forth in ivory towers, this works great. All business entities are stored in a database in 6th normal form and everyone is happy. Well, when working with legacy and enterprise systems, that usually isn’t the case. There are many different databases that are used and objects are stored across a variety of them.

In order to get my system to use NHibernate, the first challenge was incorporating multiple sessions. A session is basically a connection to a single database that manages persistent objects. This article describes a really complex way to accomplish it, but all you really need to pay attention to is the NHibernateSessionModule and NHibernateSessionManager. Using the outline described in the article, I successfully got multiple sessions to work fairly painlessly.

The second challenge was storing a persistent object in multiple database. Since persistent objects in NHibernate can’t span multiple sessions, some data massaging has to be performed. As I see it, there are two possibilities for storing an object in multiple database.

  1. Different objects for each database with type conversion operators
  2. The same object for all databases with extra session logic

The latter is obviously easier from a domain model perspective, but not from an implementation perspective. For a persistent object from one session to be stored in another session, all references must be removed from the session. This means unproxying the object and unpersisting any collections contained within the object. Looking through the NHibernate source code, I was able to accomplish this with only a few lines of code.

Setup & Documentation

Most of the getting started guides for NHibernate are no where near complete or up-to-date. It took a couple days to get my environment up and running. This isn’t really a problem with the library itself, but is still a problem for first time users. In all reality, there seems to be a lack of documentation in general. Three example mappings in the documentation is no where near enough for what is marketed as an enterprise ORM solution.

Conclusion

NHibernate is awesome. Even with these minor issues, it is one of the greatest tools for web development I have ever used. I hope that the development of this library continues to improve, and hopefully some of these issues will be resolved.

NHibernate O/R Mapper: Part 1

As most of you know, the data access layer is my favorite application layer to work with. For a while, I worked on my own active record implementation in PHP. After switching to .NET, my outlook has strayed away from the active record pattern though. I like using business entity objects that have no coupling to a database. Instead, I use an object/relational mapper to translate from business entity to persisted database object.

At first, I started working on my own implementation again, which provided a simple, in code, mapping technique. I quickly realized that mapping business entity relationships wasn’t easy though. After a couple hours of staring at my monitor hoping I could come up with an elegant solution, I decided to look at some 3rd party mappers. I had heard about NHibernate before and decided to give it a shot.

I spent about two days prototyping part of my database in NHibernate and my first impression is wow. Everything I could think of adding in an o/r mapper exists in NHibernate. Lazy loading, relationships, inheritance, component mapping, and so much more is possible. Over the past few weeks, my entire data access layer has been converted to NHibernate with overwhelming success. Like any library, it has its own quarks, but for the most part it speeds up development time while adding lots of power to my applications. I would recommend it to anyone.

NHibernate uses XML documents or .NET attributes to map an entity class to a database. I never thought I would use XML again after painful VB6 experiences, but I decided to give it another shot. To my surprise, I loved it. It allows for really clean separation of the database and code, which basically means cleaner code and a happier Brian. The only really annoying part of NHibernate is session management, but I’ll save that for part 2.