This blog has moved, permanently, to http://software.safish.com.

Thursday, May 21, 2009

Protecting .NET Code with Dotfuscator

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)

Wednesday, May 20, 2009

Using Microsoft's Performance Monitor Tool

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.

Tuesday, May 19, 2009

Encrypting cookies with ASP.NET

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:
  <machineKey
    validationKey="AutoGenerate,IsolateApps"
    decryptionKey="AutoGenerate,IsolateApps"
    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();

SQL Server Query Plans

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. he 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
    objtype,
    p.size_in_bytes,
    left([sql].[text], 100) as [text],
    usecounts
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

Friday, May 15, 2009

JavaScript Dimensions and Element Positioning

Now that the main browsers have (sort of) merged in terms of DOM element positioning, it's a lot easier to position your elements on a web page than it used to be. I still forget off-hand what is what, so here's a table of the document objects and their properties that are useful when writing dynamic element sizing and/or positioning.

Screen, Document and Element Sizes



screen.width
screen.height
The width and height of the user's screen e.g. 1440 x 900
screen.availWidth
screen.availHeight
The width and height of the user's screen excluding taskbars.
document.body.scrollWidth
document.body.scrollHeight
The actual width and height of the document (see blue arrow above).
document.body.clientWidth
document.body.clientHeight
The width and height of the document, not taking into account any scrolling (see red line above)
element.offsetWidth
element.offsetHeight
The width and height of an element. All style elements MUST be applied before getting this value, including display, visibility, etc.


Element Positioning

Unfortunately, getting an element position isn't quite as easy, due to different implementations in the browser. The following JavaScript function can be used to get the axt co-ordinates of an element within the document.

// gets the absolute position of an element on the screen
function getAbsolutePosition(element)
{
    var left = 0;
    var top = 0;
    // internet explorer
    if (element.offsetParent)
    {
        while (element.offsetParent)
        {
            left += element.offsetLeft
            top += element.offsetTop;
            element = element.offsetParent;
        }
    }
    // other browsers
    else if (element.x)
    {
        left = element.x;
        top = element.y;
    }
    return { x:left, y:top };
}
For example, if you have an element with id 'myElement':
var pos = getAbsolutePosition(document.getElementById('myElement'));
var left = pos.x;
var top = pos.y;

Thursday, May 14, 2009

Custom Dictionary Sections in .NET Config Files

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.

Example

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:
<configSections>
<section name="StatusCodes" type="System.Configuration.DictionarySectionHandler"  />
</configSections>
...
<StatusCodes>
  <clear />
  <add key="2" value="Two" />
  <add key="3" value="Three" />
  <add key="4" value="Four" />
  <add key="5" value="Five" />
</StatusCodes>
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;

Monday, May 11, 2009

Creating and Consuming .NET Web Services

I quite liked this article by Dimitrios Markatos: http://dotnetjunkies.com/Tutorial/4D13CEFA-D0FD-44BE-8749-8D17B5757564.dcik

FxCop: Excluding rules in code

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.

Saturday, May 9, 2009

Google syntax highlighter

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 ...
 </pre>
Finally, add some JavaScript to the end of your page, and that's it.
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
  SyntaxHighlighter.all();
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.

Intro

I'm creating this blog as a repository for anything technical I come across. As a programmer, this will generally involve discussions surrounding code, but I'll use it as a store for anything to do with computers.