Recent posts

Help prioritizing Enterprise Library 5.0

Patterns & Practices has just finished compiling a list of candidate features and improvements for the next installment of the Enterprise Library. Grigori Melnik, the Enterprise Library's product manager has opened an online survey and invites the .NET community to share their priorities and, if needed, add any additional requests. Make sure you add your vote over here.


Published: 01-04-2009 by Dennis Doomen | 0 Comments | 0 Links to this post
 

The Query Command Separation principle, who was right?

Yesterday, at my Design Patterns & Testability session at the dotNED meeting, I tried to explain the purpose of the Query Command Separation principle. However, somebody from the company Quadrant (forgot to ask for his name) mentioned an entirely different explanation of the pattern. Since many design principles are not very well specified, I was expecting some discussion, but in this case, I was caught off guard a little bit.

He was explaining it as a pattern for distributing changes over multiple synchronized databases. For instance, when one database is used for reporting or querying and the other for maintaining state, command-like objects are used to apply the same change to both databases. I heard about this approach and it sounded like the Command pattern. However, he mentioned an article from Greg Young posted on Code Better, so it sounded serious enough for me to investigate.

Turns out we were both right. As a technical design pattern, the QCS principle does indeed what I though it did and has been written down by Bertrand Meyer. At the same time though, Greg Young and Udi Dahan and some of their fellow Distributed Domain Driven Design guys have been redefining this pattern on the architecture level. You can read about that over here.


Published: 27-03-2009 by Dennis Doomen | 0 Comments | 0 Links to this post
 

Slides from the Design Patterns & Testability session at dotNED

As usual, I ran out of time big time, but still, it was a great evening. We continued until 21:45 and even though my throat was hurting as hell due to the flu, people were paying attention very well. TDD en testability are really difficult subjects and always cause a lot of discussion, but the discussion itself already proved some of the claims I made. So, I'm happy!

 DSCF1184

You can download the slides here and the code that shows all the examples I had in mind (and failed to show within the available time) here.


Published: 27-03-2009 by Dennis Doomen | 0 Comments | 0 Links to this post
 

There really is LINQ to SharePoint

This is probably old hat, but here it is: http://www.codeplex.com/LINQtoSharePoint. Our Information Worker group had its regular meeting last evening with a special focus on development. When exploring all the ways the development experience could be improved in the next version of SharePoint (develop on a workstation! yeah!) one of the attendies asked for LINQ querying lists. Somewhere in the back of my head it rang a bell, but I couldn't put my finger on it. So here it is, follow the link above. Never underestimate the power of CodePlex...

Published: 25-03-2009 by Wim The | 0 Comments | 0 Links to this post
 

Accessing a private key for a certificate

I ran into an interesting issue yesterday with trying to access the private key of a certificate. Why I needed to do that, isn’t really relevant for this post, but the trouble I ran into is something worth sharing.

 

First of all, you need a certificate with an exportable key: you can do so when you import the certificate into the certificate store. So far so good, this is easy. It got alot worse after that: while trying to open the certificate’s private key, I got an error saying: “Handle is invalid”. Thanks very much for this very descriptive error… What this basically means is that, in my case, the ASP.NET application does not have access the private key. Or better: the identity the application pool uses does not have access to the private key, which is stored on disk. This can be solved by downloading the Winhttpcertcfg tool from Microsoft. This tool allows you to add permissions on the private key of the certificate. You have to run the tool from the command-line (it is located in C:\Program Files\Windows Resource Kits\Tools) and specify the store, certificate issuer and the user you want to grant access to.

Example:

winhttpcertcfg -g -c LOCAL_MACHINE\MY -s <Certificate Issuer> -a <Account name>

Ok fine, the “Handle is invalid” error had disappeared, but now I got another error: “System cannot find the file specified”. Hmm, okay, another very clear error message. Thanks again, I started to wonder whether using the System.Security.Cryptography also means that you get cryptic error messages along with it. Problem was though, that my application pool was configured to use a custom account. When I switched this to the default Network Service account there wasn’t a single problem. It turned out that the RSACryptoServiceProvider class tries to access the user profile of the configured account in the application pool. But since this user has not logged in to the machine yet (and probably never will), it cannot access the directories.

You can find a more detailed explanation on this other blog site I ran into while investigating the problem: http://blogs.msdn.com/alejacma/archive/2007/12/03/rsacryptoserviceprovider-fails-when-used-with-asp-net.aspx

All that I needed to do now, was directing the RSACryptoServiceProvider instance to the machine certificate store by adding parameters with the constructor:

   1: var rsaParameters = new CspParameters
   2:                         {
   3:                             Flags = CspProviderFlags.UseMachineKeyStore
   4:                         };
   5: var rsa = new RSACryptoServiceProvider(rsaParameters);

After the change in code, everything worked just fine.


Published: 18-03-2009 by Arnold Jan van der Burg | 0 Comments | 0 Links to this post
 

Dutch Open Space Code Day 2009

Open Space Code is a hands-on programming event following the Open Space format. The concept was borrowed (with permission) from the Open Space Coding Day that was held in the UK recently. Open Space events are more freeform than normal conferences, where all the interactivity is mostly found in coffee breaks. Mostly they're just great fun.

twitter

Announcements will be posted on this website and on this Twitter account @openspacecodenl, if you want to attend, send an email at info@openspacecode.nl.

The target date is Saturday the 6th of June 2009 from 9.00 to 17.30, the target location is in Den Haag near the A4 but hasn't been confirmed yet.


Published: 15-03-2009 by Dennis Doomen | 0 Comments | 0 Links to this post
 

Design Patterns & Testability at dotNED and SDN

March will be busy month for me. On Thursday the 26th of March, we will be hosting the monthly Dutch dotNED community at the Holiday Inn hotel in Leiden. I'll be talking about testability and design patterns by showing how Test Driven Development and Design Patterns can help you create highly maintainable software. I'll start with a short introduction on TDD and list quite a few principles that I've learned from some of the more noticeable members of the community. I'll then continue with coding an example application using various design pattern and in TDD-style. Check out the registration page here.

On Monday the 30th, I'll repeat the design patterns part of that session at the quarterly SDN Event in Driebergen. And if you're into testability, you'll be in for a joy because quite a few sessions will be covering that subject.


Published: 15-03-2009 by Dennis Doomen | 0 Comments | 0 Links to this post
 

LINQ to XML – My first steps in the world of LINQ

Having read Programming Microsoft LINQ last summer and having done nothing with it in the mean time started bothering me especially since every other college I’ve got back at the office has worked with it. So I decided it was time to step up to the proverbial ‘'plate’’ and get some game time with LINQ.

As I’m never content in doing “How to ”- Labs and having nothing to show for it, I’ve decided to build an application I can keep using when I done building it. Hopefully I can keep myself committed for a full series of postings on my progress.

Anyways what is this application I want to build? Well it’s an application which gives me a full listing of all the WII games brought out by Nintendo and in where I can keep track of which games I own.

Seeing this going to be a small application with a very limited need to store data, I opted to use an XML file as my datastore. The traditional way of storing CLR-types to XML is to annotate the object with XML-attributes and serializing the object with an xml serializer. Or one could construct and XML document using a  DOM which is as we know a very painstaking, error prone process.

For my first steps in to the world of LINQ I use LINQ to XML to create my datastore. In my application I created a class named GameData which encapsulates all read and writes to the datastore.

   1: /// <summary>
   2:     /// Data repository
   3:     /// </summary>
   4:     class GameData
   5:     {
   6:         private const string dataStoreFile = @"c:\_TFSWorkspace\WIIGames\data\Game.xml";
   7:         public IList<Game> gameList = new List<Game>();
   8:  
   9:         public GameData() 
  10:         { 
  11:             
  12:         }
  13:         public void Add(Game gameToAdd)
  14:         {
  15:             if (!gameList.Contains(gameToAdd)) 
  16:             {
  17:                 gameList.Add(gameToAdd);
  18:             }
  19:         }
  20:         public void Remove(Game gameToRemove)
  21:         {
  22:  
  23:         }
  24:         /// <summary>
  25:         /// loads internal data structure from disk
  26:         /// </summary>
  27:         public void Load() 
  28:         {
  29:             XDocument doc = XDocument.Load(dataStoreFile);
  30:             gameList = (from games in doc.Descendants("game")
  31:                        select new Game() 
  32:                        {
  33:                            Bestandsnaam = games.Element("bestandsnaam").Value,
  34:                            Regio = games.Element("regio").Value,
  35:                            Release = DateTime.ParseExact(games.Element("releasedatum").Value,"dd-MM-yyyy",null),
  36:                            ReleaseNaam = games.Element("releasenaam").Value,
  37:                            HansNummer = Int32.Parse(games.Element("hansnummer").Value),
  38:                            Naam = games.Element("naam").Value,
  39:                            Nummer = Int32.Parse(games.Attribute("nummer").Value)
  40:                            
  41:                        }).ToList<Game>();
  42:         }
  43:         /// <summary>
  44:         /// Saves internal data structure to disk
  45:         /// </summary>
  46:         public void Persist()
  47:         {
  48:             XDocument doc = new XDocument(
  49:                 new XDeclaration("1.0", "utf-8", "yes"),
  50:                 new XElement("games",
  51:                     from game in gameList
  52:                     select new XElement("game",
  53:                         new XAttribute("nummer", game.Nummer),
  54:                         new XElement("naam",game.Naam),
  55:                         new XElement("hansnummer",game.HansNummer),
  56:                         new XElement("releasenaam",game.ReleaseNaam),
  57:                         new XElement("releasedatum",game.Release.ToString("dd-MM-yyyy")),
  58:                         new XElement("regio",game.Regio),
  59:                         new XElement("bestandsnaam",game.Bestandsnaam)
  60:                         )
  61:                       )
  62:                     );
  63:             doc.Save(dataStoreFile);
  64:         }
  65:     }

If you put your eye on linenumber 46 you’ll see the function Persist() in which an XML document is created by using a“functional construction”. A functional construction has the advantage that is puts the developers focus on the hierarchical structure of an XML document itself as apposed to the object construction and the rules of DOM  when constructing an XML document using one of the traditional forms.

 

Functional construction has been made possible by utilizing nested constructors and  Object Initialization Expressions. As you can see on line 51 through 61 the collection of games gets iterated over and immediately gets assigned to an new XElement  named “game”.

On line 27 you’ll find the function Load() which does the reverse process of reading the XML document from disk and creating an in-memory representation.

Here’s what the XML looks like:

   1: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
   2: <games>
   3:   <game nummer="0">
   4:     <naam>Manhunt 2 (Europe)</naam>
   5:     <hansnummer>0</hansnummer>
   6:     <releasenaam>MANHUNT.2.PAL.Wii.iNTERNAL-DORADO</releasenaam>
   7:     <releasedatum>01-01-0001</releasedatum>
   8:     <regio></regio>
   9:     <bestandsnaam>mnt2_drd</bestandsnaam>
  10:   </game>
  11:   <game nummer="1">
  12:     <naam>Red Steel (USA)</naam>
  13:     <hansnummer>0</hansnummer>
  14:     <releasenaam>Red_Steel_USA_Wii-PARADOX</releasenaam>
  15:     <releasedatum>21-12-2006</releasedatum>
  16:     <regio />
  17:     <bestandsnaam>pdx-red</bestandsnaam>
  18:   </game>
  19: </games>

Well that is all for now hopefully you can put it to good use. Next time my focus will be making my application searchable by utilizing Lucene.Net.

 

Stay Tuned!


Published: 10-03-2009 by Hans ter Wal | 0 Comments | 0 Links to this post
 

Format source code in your blog posts

There is a nice add-in for Visual Studio that allows you to copy your source code as HTML. This can be useful for example when you want to add a code sample to your blog posts.
The add-in is called CopySourceAsHtml (CSAH). It gives you an extra option in your edit- and context menu: 'Copy as HTML...'. The copied HTML reflects your Visual Studio color settings.
 
 
You can also use an online tool at http://www.manoli.net/csharpformat/. There you can paste your source code in a textbox and convert it to HTML. You will need to add an extra stylesheet to your blog website and add a reference to it in the <head> section of your page.

Published: 10-03-2009 by Martin Opdam | 1 Comment | 0 Links to this post
 

Best practice for accessing objects in ASP.NET cache

Fetching data from a webservice or a database can take some time. When it concerns static data that is used often in your application, it is wise to store the data in cache. That way you only have the performance hit of fetching the data once. ASP.NET has a HttpContext.Cache object that can be used to store your data. But what is the best way to read and write data in cache? And how do you handle the situation where multiple users of your web application access the same data in cache? I will try to answer these questions with an example.
Say you have a web application that uses a list of countries. The countries are stored in a database and do not change very often so you want to fetch and store the list in cache. You create a property 'Countries' that handles the fetching and caching of the countries. An obvious solution would be:

   1:  public List<string> Countries
   2:  {
   3:      get
   4:      {
   5:          // Try getting the countries from cache
   6:   
   7:          if (Cache["countries"] == null)
   8:          {
   9:              // Not in cache, so get the countries
  10:              // from the database and store them in cache
  11:              Cache["countries"] = GetCountriesFromDatabase();
  12:          }
  13:   
  14:          return (List<string>)Cache["countries"];
  15:      }
  16:  }

However, this is not a very good solution, because you should never assume objects in cache to be there. The cache can be expired at any time (for example because of a lack of resources). Even right after an object has been stored in cache, it can be removed. If, in the above example, the cache is cleared just before the return statement, the Countries property will incorrectly return null. To solve this, we should use a temporary variable. Like this:

   1:  public List<string> Countries
   2:  {
   3:      get
   4:      {
   5:          // Try getting the countries from cache
   6:          List<string> countries = (List<string>)Cache["countries"];
   7:          if (countries == null)
   8:          {
   9:              // Not in cache, so get the countries 
  10:              // from the database and store them in cache
  11:              countries = GetCountriesFromDatabase();
  12:              Cache["countries"] = countries;
  13:          }
  14:   
  15:          return countries;
  16:      }
  17:  }

This is better, because now it is no longer possible to return null when the cache is cleared. But this solution is not optimal either. What happens when multiple users are using the application at the same time and the Countries property is called from multiple threads simultaneously. When this happens before the cache has been filled it will result in multiple expensive calls to the database, just to get the same list of countries and store it in cache. This will degrade the overall performance. It would be enough to let just one thread fetch the countries and store them in cache. This can be accomplished by using locks:

   1:  private readonly object CountriesCacheLock = new object();
   2:   
   3:  public List<string> Countries
   4:  {
   5:      get
   6:      {
   7:          lock (CountriesCacheLock)
   8:          {
   9:              // Try getting the countries from cache
  10:              List<string> countries = (List<string>)Cache["countries"];
  11:              if (countries == null)
  12:              {
  13:                  // If not available from cache, apply a lock to fill the
  14:                  // cache in a thread-safe way. This avoids that multiple 
  15:                  // threads will simultaneously fetch the same list of
  16:                  // countries from the database
  17:                  countries = GetCountriesFromDatabase();
  18:                  Cache["countries"] = countries;
  19:              }
  20:   
  21:              return countries;
  22:          }
  23:      }
  24:  }

With the lock in place only one thread at a time can access the implementation of the Countries property, so there will be no more simultaneous calls to get the countries from the database. And still this is not an optimal solution, because now multiple threads must wait for each other before they can read the cache which is a loss of performance. Reading a value from cache is a thread-safe operation and could therefore be done by multiple threads at the same time. So the reading of the cache should be moved outside the lock:

   1:  private readonly object CountriesCacheLock = new object();
   2:   
   3:  public List<string> Countries
   4:  {
   5:      get
   6:      {
   7:          // Try getting the countries from cache
   8:          List<string> countries = (List<string>)Cache["countries"];
   9:          if (countries == null)
  10:          {
  11:              lock (CountriesCacheLock)
  12:              {
  13:                  // If not available from cache, apply a lock to fill the
  14:                  // cache in a thread-safe way. This avoids that multiple 
  15:                  // threads will simultaneously fetch the same list of
  16:                  // countries from the database
  17:                  countries = GetCountriesFromDatabase();
  18:                  Cache["countries"] = countries;
  19:              }
  20:          }
  21:   
  22:          return countries;
  23:      }
  24:  }

But now we are back to the performance issue of multiple threads accessing the Countries property when the cache has not been filled. In such situation, the first thread will apply the lock en start the time consuming operation of fetching the list of countries. Threads that in the meantime access the Countries property will have to wait for the lock to be released. But when that happens each thread that has been waiting for the lock will still go and fetch the list of countries again. For this to work more efficiently we will have to check again if the cache has been filled within the lock. Only if the cache is still empty we have to do the expensive database call. The final solution now looks like this:

   1:  private readonly object CountriesCacheLock = new object();
   2:   
   3:  public List<string> Countries
   4:  {
   5:      get
   6:      {
   7:          // Try getting the countries from cache
   8:          List<string> countries = (List<string>)Cache["countries"];
   9:          if (countries == null)
  10:          {
  11:              // If not available from cache, apply a lock to fill the
  12:              // cache in a thread-safe way. This avoids that multiple
  13:              // threads will simultaneously fetch the same list of
  14:              // countries from the database.
  15:              lock (CountriesCacheLock)
  16:              {
  17:                  // Try getting the countries from cache again, because the
  18:                  // cache might have been filled while waiting for the lock
  19:                  countries = (List<string>)Cache["countries"];
  20:                  if (countries == null)
  21:                  {
  22:                      // If still not in cache, get the countries 
  23:                      // from the database and store them in cache
  24:                      countries = GetCountriesFromDatabase();
  25:                      Cache["countries"] = countries;
  26:                  }
  27:              }
  28:          }
  29:   
  30:          return countries;
  31:      }
  32:  }

See also:
http://stackoverflow.com/questions/39112/what-is-the-best-way-to-lock-cache-in-aspnet


Published: 10-03-2009 by Martin Opdam | 0 Comments | 0 Links to this post
 
 Next >>