Quick tip: Cache busting in ASP.NET revisited

Anyone that tried to cache static files eventually got to a point where cache caused more problems than it solved. After all, telling all your users to press Ctrl + Refresh in their browsers is not exactly how one should do things on the web. Two years ago Mads Kristensen presented us with a solution in his article Cache busting in ASP.NET. The solution uses Fingerprint class, that basically updates cache object every time a static file is changed.

All fine and well. So why do I jab about it now? The solution, in my opinion has two glitches:

1. It is tightly bound with URL Rewrite IIS module.

2. It always links static content to root URL.

So, without further ado, I present you with “upgraded” solution that avoids both issues and works with relative URLs (relative to application URL anyway). In-page usage remains the same.

using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;

public static class Fingerprint
{

	public static string Tag(string rootRelativePath)
	{
		if (null == HttpRuntime.Cache[rootRelativePath])
		{
			var absolute = HostingEnvironment.MapPath("~" + rootRelativePath);
			var dateLastWrite = File.GetLastWriteTime(absolute);
			var result = VirtualPathUtility.ToAbsolute(
				string.Format("~{0}?{1}", 
					rootRelativePath, 
					dateLastWrite.Ticks));
			HttpRuntime.Cache.Insert(
				rootRelativePath, 
				result, 
				new CacheDependency(absolute));
		}
		return HttpRuntime.Cache[rootRelativePath] as string;
	}

}

This code is also available as gist.

Know thy tools

A few years ago, I wrote a post on why I don’t trust 3rd party APIs. It has never been more true than today (in days of NuGet, npm and other package managers) when adding an API is a matter of seconds. Seriously, you don’t even have to break a sweat. Package managers and web searchers got you covered. We live in the days where even “evil” Microsoft decided to move to the good side of the force and went open-source. Right? APIs get updated more promptly than ever and they are available for just about anything. And code reuse saves you a lot of time. So why am I still skeptic about it?

[Read the rest of this entry…]

Memory leaks in .NET?

In olden times, when I did C and C++ development, memory leaks were a common thing. From time to time I still wake up from nightmares in which I debug, trace and try to locate and plug memory leaks (of course, as this is nightmare, I fail to do either, or it wouldn’t be a nightmare). Thankfully, in unmanaged code, memory leaks can be spotted in a debugger (or a plain old segmentation fault) and if you are paying attention, you can plug the leak right after you made it.

Then came Java and .NET, JIT compilers and a great thing called garbage collector. And we were told, we can forget about memory allocation, deallocation and pointers as a whole. We now have a garbage collector that will do this for us. And it does, if you know how to use it. But now, we became so reliant on garbage collector, that we just assume it will do everything for us. These days, it seems developers think that just because application is written in .NET it will somehow obtain immunity to memory leaks.

Boy do I have news for you! It won’t. Just last week, I spent most of my time debugging, tracing and removing a memory leak that caused otherwise stable windows service to throw OutOfMemory exception in 90 minutes. As .NET code is managed, tracing the leak gets tricky and the fact that code was not mine only made it worse.

If you write a one-off trivial application, memory leaks are nothing to worry about, as garbage collector will release the memory, when application is closed. And since application runs only short period of time, unless you do something completely moronic, you are fine and users might not even notice.

But, as soon as you start writing serious applications and applications that have to run 24/7 (e.g. Windows Service), things change. Any serious application has to assume, that, if object is not disposed correctly, it will accumulate in memory until the application is closed or it crashes. Preferably on Friday at 3pm when you are about to head for your well deserved vacation.

So what can you do? Personally, I stick to one simple rule that removes a risk of good portion of possible memory leaks. Any object that implements IDisposable interface has to be either encapsulated in using statement or disposed explicitly. Preferably in finally statement of try-catch block. It also helps to go the extra mile and remove reference to objects used as soon as possible and thus allow garbage collector to do its job properly.

And our memory leak? With great cooperation from our customer and some good fortune, we obtained enough information to locate the leak. It was caused by opening a Stream object about 1 million times without ever closing it.

Quick tip: Extending column which is also (part of) primary key

At work, I got a short task of extending a varchar column in our database from 25 chars length to 50. The task seems easy enough. But, as things usually turn out, it contained a GOTCHA! The column was also a part of primary key on that table. Thus, I started to wonder. Can you resize a column that is part of primary key without recreating primary key itself?

I did some empirical experiment on MSSQL and Oracle RDBMS and came to a conclusion. You actually can just extend the length of a primary key column and primary key will auto-adjust.

Also, in case you are wondering, the same applies to all possible constraints on the table that include said column.

Absolute minimum you need to know about storing passwords

In 2013 Forbes reported that approximately 30,000 sites across the globe are hacked each day. Yet, for some odd reason, in 2015, I still see web applications that employ questionable password storing mechanisms e.g. storing passwords in plain text or just hashing them with md5. With 30,000+ sites hacked a day, there is a strong chance that your site will be hacked next.

[Read the rest of this entry…]

Mobile apps development: Part I – Environments

Recently, I started to learn how to do mobile apps. Instead of classic ToDo app, that everyone is so fond of, I decided I will do a bit more realistic application. It would include, for starters a first time initialization, that would run (what a surprise!) at first run of installed app. This initialization would check connection, register account on my server (using web api) and use SQLite as local persistent storage.

[Read the rest of this entry…]

Quick tip: Do proper exception handling

This might be a bit of a d’oh, but if you decide to handle exception, handle it properly. What do I mean by saying “properly”? Have you ever seen code like this?

var myClass = new MyClass();
try {
    myClass.SomeMethodThatCanThrowException();
}
catch {
}
finally {
    myClass.Dispose();
}

This code is stupid. Exceptions are a sign of exceptional or unpredicted behaviour. Thus, they should be treated with all seriousness. The code above works fine, if no exception is thrown. However, we live in unpredictable world. Internet connection may die. Hard drive may crash. Computer can run out of memory. And, in the case above, as soon as exception is thrown, neither you nor user will have the slightest clue of what went wrong.

There are two ways to solve this:

  1. Re-throw exception using throw; statement and handle it later on or
  2. Handle it in catch part of statement.

 

I understand that sometimes you just don’t see the need to handle an exception, but the least you can do is write the exception to log file.

Quick Tip: Create custom server controls with a grain of salt

In asp.net world, creating custom server controls has become some sort of a standard. In fact, it is so easy to create a server control, that developers usually do it without thinking. The problem is, that server controls are a bit more complex than an average Joe would think. There are bunch of things you need to take care of, like handling client and server-side validation, handling control when view state is disabled etc. A developer must pay attention to these things, or weird bugs can start happening.

[Read the rest of this entry…]

Other developer essentials: Part IV – Google search

I don’t know about you, but I still have a vivid memory of the time before internet actually became useful. In those days, learning how to solve your problem included a lot of trial and error attempts and eventually a trip to local library. If finding a book on correct topic wasn’t enough of a challenge, finding a solution usually meant reading most of 800 page bible.

[Read the rest of this entry…]

Quick tip: Copying certificate serial number in windows has a glitch

The easiest way to obtain serial number of a certificate is to go to Internet options -> Content -> Certificates and double click the desired certificate. In the Details tab, there is a property list control with a row containing “Serial number” label in first column and value in second. When you click on it, the serial number is displayed in field below the properties list.

Certificate serial number

Certificate serial number

On Windows 8 and Server 2012 , selecting entire field content, pressing Ctrl + C and pasting it into Notepad or Notepad++ will display only text, without leading spaces. The problem is, the text contains special hidden characters in front and/or at the back of the pasted string. Characters are invisible to text editors, but are still there. You can see it, if you paste directly to Command prompt window.

Serial number pasted to command prompt

Serial number pasted to command prompt

On Windows 7 and Server 2008 and below serial number has visible “spaces” that represent those same hidden characters (as depicted in image of certificate details above) and user can select only real content of serial number field. Funny enough, if you access the field with code,  there are no special characters in the value.

As it is so easy to copy hidden special characters and as this “feature” caused major problems at one of the projects I support (not to mention hours used for debugging the issue), I created a small windows application that allows you to copy major properties (so far: Issuer, Issued to, Expiration date and Serial number) from all installed personal certificates in either Local machine or Current user certificate store to your clipboard. Source code of the application can be found on GitHub.