0 Comments

I’ve always been a big fan of using the ThreadPool for asynchronous execution, but in ASP.NET it is not the best approach for multi-threading. I’m not writing about when threading is appropriate and the impact of multi-core or dual core machines when doing threading, but point out that the ThreadPool is not the best choice for ASP.NET applications.

ThreadPool is easy

The reason why I like the ThreadPool is because it is managed for me and it is very easy to use and it only takes one line of code to execute a method in a new thread by using the QueueUserWorkItem method.

System.Threading.ThreadPool.QueueUserWorkItem(SomeMethod);

Private void SomeMethod(object stateInfo)
{
    // Execute something...
}

You can also send a parameter easily like so:

System.Threading.ThreadPool.QueueUserWorkItem(SomeMethod, variable);

That variable then gets transferred to the stateInfo parameter of SomeMethod where you can then cast it from object to whatever data type it is.

Private void SomeMethod(object stateInfo)
{
    int number = (int)stateInfo;
    // Execute something...
}

The ThreadPool in ASP.NET

You can use the ThreadPool in exactly the same way in ASP.NET and it works just as you would expect. The problem is not in the ThreadPool itself but in what else ASP.NET uses it for at the same time. ASP.NET is multi-threaded by design and it uses the ThreadPool to serve pages and content mapped to the ASP.NET ISAPI filter.

If you also use the ThreadPool, then ASP.NET has fewer threads to utilize and requests are put on hold until the pool returns a free thread. This might not be a problem for a low traffic site, but more popular sites can get into trouble. Low traffic sites can get into trouble if they use the ThreadPool a lot.

Don’t use it

Whether you work on a low or high traffic site, there really is no reason to use the ThreadPool when you can create new threads almost as easily that doesn’t disturb the pool. Here is an example that uses an anonymous method as a delegate:

System.Threading.ThreadStart threadStart = delegate { SomeMethod(variable); };
System.Threading.Thread thread = new System.Threading.Thread(threadStart);
thread.IsBackground = true;
thread.Start();

That’s four lines instead of one, but that’s a low price to pay. You could always create a helper method to call whenever you want to start a new thread.

public static void StartBackgroundThread(ThreadStart threadStart)
{
  if (threadStart != null)
  {
    Thread thread = new Thread(threadStart);
    thread.IsBackground = true;
    thread.Start();
  }
}

Then just call it in one line like so:

StartBackgroundThread(delegate { SomeMethod(variable); });

Word of caution

The ThreadPool is managed by the CLR, which provide a level of control that a normal thread doesn’t get. By using an un-pooled thread you also have the ability to do much more harm if you don’t know what you are doing.

You have the ability to stop the AppPool from being recycled and the application from being stopped if you aren’t careful. For instance, if you set the IsBackground property to false, it will exist in the foreground and can make it difficult for the application to recycle or restart. However, the example shown above is not doing that, so don’t worry about damaging your application by using it.

0 Comments

Micro formats have existed for some years now, but it hasn’t been useful for anything until now. If you don’t know what micro formats are, then here is an explanation from Wikipedia:

A Microformat (sometimes abbreviated μF or uF) is a way of adding simple semantic meaning to human-readable content which is otherwise, from a machine's point of view, just plain text. They allow data items such as events, contact details or locations, on HTML (or XHTML) web pages, to be meaningfully detected and the information in them to be extracted by software, and indexed, searched for, saved or cross-referenced, so that it can be reused or combined.

The reason why it has become useful is because of browser support. Both Firefox 3 and Internet Explorer 8 will support micro formats natively. If you cannot wait for the next version of Firefox or IE, then you can download the Operator micro format extension for Firefox and start testing your site. I have done that and applied some micro formats to my blog and now I’ll give you some examples on how to do it easily.

The nice thing about micro formats is that you don’t have to change your layout and stylesheet because it is completely invisible to the human eye – it only exist in the (X)HTML for machines to read. Let’s take a look at three micro formats and how to implement them.

hCard

The hCard micro format is a XHTML representation of the vCard format that applications such as Outlook and iCal understands. By using hCard you can give your visitors an easy way to retrieve and store your contact information. Here is a screenshot of the hCard implementation in the Operator extension for Firefox.

It is implemented only by the use of adding classes to HTML tags. Here is one similar to the one I use on this blog.

<div class="vcard">
  <span class="fn">Mads Kristensen</span><br />
  Lead Developer at <span class="org">Traceworks</span>
  and long time <span class="nickname">.NET slave</span>.
 
  <div class="adr">
    I live in <span class="locality">Copenhagen</span>,
    <span class="country-name">Denmark</span>.
  </div> 
</div>

Remember that the vcard class name must be set in the surrounding container. There are many other class names that is supported by the hCard specifications and you can find a list of them here.

xFolk

The xFolk micro format is for social bookmarking and can be used to let people add your posts and articles to services like del.icio.us, digg and dotnetkicks. That means you no longer need the social bookmarking links and icons on each blog post, because the browser can take care of it for the user. This is how my blog looks in the Operator extension.

 

xFolk is also one of the simplest micro format to apply to a website and it also just uses classes. Before I added xFolk to my blog, each post looked liked this in the HTML:

<div class="post">
  <h1><a href="/page.aspx">Title of the post</a></h1>
  <p>The content of the post</p>
</div>

And here it is after.

<div class="post xfolkentry">
  <h1><a href="/page.aspx" class="taggedlink">Title of the post</a></h1>
  <p>The content of the post</p>
</div>

As you can see, I only added two additional classes – xfolkentry and taggedlink – to the existing mark-up. The xFolk format does support additional classes to be used, but I think these two are enough for most websites. You can find the specifications here.

Rel-Tag

The Rel-Tag micro format is used to provide keywords to content in order to categorize it. If you have a blog post called “Why dogs are better than cats”, then you could provide two tags to that post – one called dog and one called cat. They should then point to a page of all your blog posts that has been tagged with the dog and cat tag respectively. It’s very similar to categories, but much more granular.

To make the dog and cat link into a tag, you simple add the rel-attribute to the link:

<a href=”/tag/dog.aspx” rel="tag">Dog</a>.

The rel attribute is supported by the HTML and XHTML specifications so don’t worry about breaking your standards compliant webpage.

Where the hCard and xFolk micro format can be applied to existing mark-up easily, you might have to change more to add tags. That’s because the Rel-Tag does not use the text in the link tag but the href instead. It sees a tag as everything that is to the right of the last forward slash. That means that the link above has a tag called dog.aspx instead of Dog.

If you have control over your webserver and can setup the IIS to map all extensions to the ASP.NET engine, you can rewrite the URL so that the link can point to /tag/dog/ and thereby avoid the .aspx in the URL. However, if your website is hosted you probably don’t have that option before IIS 7 will be released with Longhorn Server.

If you have to use the .aspx extension you still have a way to make it work. The prettiest is to use the PathInfo part of the URL which looks like this /tag.aspx/dog. The only problem is that when you use the PathInfo you also break the relative root of your website. You can no longer use a link like “~/” to return to your home page because it will send you to /tag.aspx/ instead. That’s why I have implemented the other way on my blog. I use a URL parameter instead which isn’t very pretty, but it does the trick. Now my tags have this URL /tag.aspx?tag=/dog. The important part is to remember to add a forward slash before the name of the tag.

Here is how the Operator extension sees my tags:

 

This was only an introduction to three of the many micro formats you can use. Other important micro formats are XFN, hCalendar and rel-nofollow along with a few more. As a side note I can inform you that BlogEngine.NET 1.1 will fully support hCard, xFolk, Rel-Tag, XFN and rel-nofollow.

0 Comments

A lot of people have asked me why we don't use third-party assemblies in BlogEngine.NET, so I thought it was about time to explain why. 

One of the most important rules that I laid down before starting on the BlogEngine.NET project, was that no third-party assemblies were allowed. This rule was forged out of the assumption that most of these assemblies did a whole lot when only a little bit was needed for BlogEngine.NET, and that little bit was easy to write our selves.

It’s obvious that it would take longer to write the code instead of just referencing the assemblies, but it was worth the extra effort. BlogEngine.NET is build for .NET developers so my initial thought was that they wanted to be able to change every little thing they wanted to suit their needs. Third-party, precompiled assemblies doesn’t allow for easy customization so that would counter the .NET developers needs. That has a big part in why BlogEngine.NET is so open and simple to customize

If you look at most other .NET blog and CMS platforms in existence today, you’ll see that they make heavy use of various third-party assemblies. All of the assemblies and libraries are open source or at least free of charge and they are all very powerful and easy to use. However, the decision has been made so we had to come up with alternatives to the libraries and that proved surprisingly effortless for our simple needs.

What we didn’t use

Web control libraries
There are many web control libraries that offer date-time pickers, special grids etc. that we could have used, but let’s face it. A date-time picker is just a JavaScript representation of the already existing ASP.NET Calendar control with some AJAX functionality. Other controls can be much harder to write yourself but we didn’t need them.

XML-RPC.NET
It’s a very cool library for handling trackbacks and pingbacks and pinging Technorati, Feedburner etc. when new posts are created. It does much more than that, but these features were the ones we needed. XML-RPC is standard XML that can be parsed and XPath’ed so why did we need a third-party library for handling XML?

Rich text editor
I’m a big fan of both FreeTextBox and FCKeditor which I’ve used in many projects over the years. They each have their advantages and can be extended and modified fairly easy. So can tinyMCE and it is purely JavaScript, so that’s what we decided to use. There were other reasons as well, such as almost perfect XHTML generation and other minor factors. Well, and of course the fact that it’s JavaScript so we can change whatever we want.

HTTP compression
There are quite a few compression libraries that can gzip or deflate the HTTP response stream. Instead we used the build in compression classes in the CLR and wrote a single HttpModule to do the job.

CAPTCHA controls
There exists hundreds of CAPTCHA control libraries for ASP.NET both visible and invisible ones. However, a CAPTCHA is one of the simplest things to write – it takes only 20 lines of code to create a rock solid invisible one – so that’s what we did.

As you can see, we did a lot of reinventing for BlogEngine.NET, but it actually wasn’t that big a deal.

In the enterprise

For enterprise projects where third-party dependencies can be costly, it would be beneficial to be sure what the needs are and if they can be built instead of bought. You should also weigh the value of owning the code instead of using third-parties. It various from project to project and from library to library, but one thing remain the same: third-party dependencies is not as flexible as building your own implementations.

The hobby project

Most hobby projects start when you get an idea and want to realize it real quick. Then you don’t want to do much reinventing because that would just slow you down and your code is probably not essential either. In those cases I would use as many third-party libraries as possible to get the code running and my project realized.

Think twice

There are many factors to consider before using third-party libraries and some demands real thought. You have to be real careful about using third-party libraries for essential components, because then you loose control of the most important parts of your application. For BlogEngine.NET we also had to consider our target group - the developers.

If you base your business/application on a component provided by third-party, you might want to think twice.

0 Comments

The planning phase of most projects no matter the size result in some kind of documentation or manuals for coding. It could be a rough sketch of the data flow, a UML diagram, feature specifications etc. Some big enterprise projects probably also have a detailed explanation of the individual classes, so that the developers knows exactly what the class has to do and why.

Then again, most projects do not undergo such an elaborate planning phase for various reasons. It might be a one-man hobby application or a simple little website. We all do them from time to time so here is a little trick for adding a planning phase while coding.

Create a new class

Because you haven’t done any real planning, you go ahead and creates a new class with a vague idea about what it has to do and why it has to do it. Instead of just adding properties and methods right away, you can force yourself to think about it and thereby do a little planning. That will help you to keep the class more focused and refactored as you write it and you might find that you need another class instead of just the one.

Comment it

With only the class declaration written in your editor, try to comment the class as thorough as possible. At least answer the three questions what, why and how. This will force you to think about the responsibilities, interface, cohesion and a lot of other things that probably saves you a lot of coding time and effort in the end.

The best thing about this approach is that you get right into the code without doing pre-planning, which most of the smaller hobby projects don’t have. You get the benefits of the planning with the pleasure of just diving into the code right away. It can never remove the need for proper planning for more important projects, but it will get your home project running smoother and better architected with little to no effort.

0 Comments

Coming from the Visual Basic world, I used to find many examples throughout the web written in VB and VB.NET. Then I got hired by Traceworks which was a VB.NET company, but they decided to move to C# because they couldn’t find employees that wanted to code VB.NET. So, I made the switch and haven’t looked back since. I haven’t written one line of VB.NET code for 2½ years.

In the beginning when I searched Google for some CLR specific stuff, it was very often that the code examples were in VB.NET. I had no problem translating them to C# so I didn’t care. As the time passed, more and more I saw that C# code was taking over the VB.NET examples throughout the web. Today, they do almost not exist unless you deliberately go to specific VB.NET sites like VB.NET Heaven.

Also, when you look at the job sections they are all about C#. It seems that VB has been replaced in the enterprises since companies are only looking for C# developers. There could be some differences from country to country – I haven’t checked them all…

If we are to believe that VB.NET is leaving the enterprises, where does it exist then? I keep seeing Channel 9 shows about the next releases of VB.NET and read some Microsoft blogs about it, but there really is no big hype in the blogosphere. No one writes about it on the web except for the Microsoft folk.

Do you know what became of VB.NET?