Google syntax highlighter

Created 09 May 2009 11:10
In setting up this blog, I was weighing up my options as to how to highlight code. You can do it manually by setting the colour of individual words, but that is just a pain in the ass, particularly for larger posts so I considered writing a JavaScript class for doing it. Fortunately, sense prevailed and I searched the web first, and I came across the Google syntax highlighter. This thing is awesome. It handles a number of different languages, displays line numbers automatically, and even has a number of utility options you can display like printing, clipboard copying, and more. Great stuff. Best of all, it's so easy to use. All you need to do is include the JavaScript files and the css file, and mark your code with some simple attributes:
 <pre name="code" class="brush: html">
   ... some code here ...
Finally, add some JavaScript to the end of your page, and that's it.
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.config.clipboardSwf = '';
You don't need the first two lines of this script unless you're adding it to a blog. If you ARE adding it to a blog, you'll need to host the .css and .js files on an external site and add them to your blog template. The rest of the instructions remain the same.

FxCop: Excluding rules in code

Created 11 May 2009 15:04
One of the tools we use at my current job to validate code as part of our automated build is FxCop. It can be a pain, but we've found it very useful in terms of standardising our code and rooting out all those un-used variables that seem to grow to epic proportions with a project of any decent size.

However, as with all tools, it's not perfect, and sometimes it throws errors that really aren't of any significance and can be safely ignored. This can be done from within the FxCop project, but it can also be done via code, which means it will be forever ignored, even if the FxCop project file changes.

This is a 2-step process:
  1. Declare conditional compile symbol for your project named CODE_ANALYSIS (In Visual Studio 2005 under the Build Tab of the project properties, there is a "Conditional compilation symbols" input field)
  2. Mark your method or property with a "SuppressMessage" attribute, as follows:
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string MyProperty
  get { return 123; }
The first parameter is the category of the error, and the second is the rule code and name split by a colon.

Custom Dictionary Sections in .NET Config Files

Created 14 May 2009 07:57

When you need to add complex configuration structures to .NET config files, you will generally create your own custom configuration section classes, and implement them within your application. However, if you just need a standard key/value pair, you don't need a custom configuration type at all. Instead, you can just define a section using the System.Configuration.DictionarySectionHandler, and there you go - no code required.


Say, for instance, you want a list of status codes that get checked by your application:

In the App.config, define the section and implement the required values:

<section name="StatusCodes" type="System.Configuration.DictionarySectionHandler"  />


  <clear />
  <add key="2" value="Two" />
  <add key="3" value="Three" />
  <add key="4" value="Four" />
  <add key="5" value="Five" />

To read these values in code, all you need to do is the following, and you have a Hashtable containing all the values defined in the config file:

Hashtable statusCodes = ConfigurationManager.GetSection("StatusCodes") as Hashtable;

SQL Server Query Plans

Created 19 May 2009 11:01

The caching of query plans in SQL Server is extremely important when it comes to application performance. The way this works is not very well understood - I still don't get all the intricacies of it but as a general rule of thumb, it's a good move to either:

  1. Use stored procedures: these get pre-compiled and allow the re-use of execution plans. They allow for parameters, allowing for a "shared" execution plan
  2. if use of stored procs is not possible or not part of your design, use sp_executesql - do NOT use EXEC when running dynamic sql. sp_executesql, unlike EXEC, can be parameterised and therefore also allows for "shared" execution plans.

You can analyse the cached execution plans on SQL Server with the following statement:

with CachedPlans as (
select top 100
    left([sql].[text], 100) as [text],
from sys.dm_exec_cached_plans p
outer apply sys.dm_exec_sql_text (p.plan_handle) sql
select * from CachedPlans
where text like '%Select * from MyTable%'
order by usecounts desc

Encrypting cookies with ASP.NET

Created 19 May 2009 13:59
I hadn't noticed it before, but ASP.NET provides a really simple way to encrypt your cookies. Cryptography is a field best left to the expert, but for simple encryption purposes this method is perfectly adequate.

First off, you will need to add an entry to your machine/web.config:
    validation="SHA1" decryption="AES" />
You can then encrypt/decrypt as follows:
  // encryption
  var ticket = new FormsAuthenticationTicket(2, "", DateTime.Now, DateTime.Now.AddMinutes(10), false, "mycookievalue");
  var encryptedData = FormsAuthentication.Encrypt(ticket);

  // decryption
  string myValue = FormsAuthentication.Decrypt(encryptedData).UserData.ToString();

Using Microsoft's Performance Monitor Tool

Created 20 May 2009 15:24
Knowing how to use PerfMon can be absolutely critical when faced with unknown performance problems on large information systems. When you're faced with a performance bottleneck in a large server farm, it can be very difficult to track down issues as minor hiccups can have knock-on effects that are far more apparent to the user than the server experiencing the source of the error, as other servers in the chain sit waiting for the problem to be resolved. PerfMon can be used to track hundreds of performance issues, this article purely serves as an introduction on how to use the tool as it isn't apparent when you load it up.

When you run PerfMon, you can see current statistic and current counters running, but it doesn't provide an option to "Save". It doesn't quite work like most applications. In order to start your own log, you need to expand the "Performance Logs and Alerts" tree item, and then select either Counter Logs, Alerts, etc, depending on what you want to log. In the main display area, you can then right-click and create a new log.

If you are creating a Counter Log, you will see a log file name, and you will have the ability to add Objects or Counters to that log file. I usually select individual Counters rather than whole objects, so you can zone in onto the exact items you need to check.

One item to note is that by default, PerfMon will log to a binary file. You can change it to log directly to a .csv file or even to a database. However, if you do log to a binary file format, you can always use the command-line "relog" tool to convert it into other formats. For example, to convert to csv:
  relog MyLogFile.blg -f csv MyLogFile.csv
Once you have finished setting logging options, the log is then saved on the machine. You can stop and start logging by right-clicking on the log and clicking Start/Stop. The settings can be exported and imported to/from html format, and you can adjust properties of the log.

Protecting .NET Code with Dotfuscator

Created 21 May 2009 10:41
Although .NET compiles into binary .dlls, these assemblies are extremely easy to reverse-engineer using Reflector, or any other decent Reflection tool. Although it's not completely secure, the simplest way to protect your code is to run it through the free obfuscation tool that comes with Visual Studio: Dotfuscator Community Edition. This is available on your programs menu under Visual Studio Tools.

All you need to do, is open up the program and load up your assembly. There are piles of options available, but the default settings are generally fine for most cases. Under the Input tab you can add all your input assemblies, provide an output folder under the Build tab, and hit the run button - this will build copies of your dll's but the namespaces, classes, methods, etc are obfuscated into code that is extremely difficult to read. Of course, it is still readable: it can be decompiled and debugged, but it's a LOT harder to use, particularly for larger projects.

Some notes on the tool:
  • when specifying the output directories it sometimes had issues with long folder names - using "C:Temp" was a simpler option and the build worked flawlessly from there
  • the community edition can be upgraded to the Enhanced Edition, just by registering (which is free)