Wednesday 25 June 2014

Calculate execution time for a method

When you do performance optimization or something similar you will need to determine the execution time for a particular method call or a piece of code. Here is some code that you can use in those scenarios. Either StopWatch or DateTime can be used to do this.

Using System.Diagnostics.Stopwatch


Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

// Your code, it could be in-line code, a web service call or whatever code you want to analyse, goes here

stopWatch.Stop();

// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);

Console.WriteLine("Time taken : " + elapsedTime);

// Or you can just call ToString() on TimeSpan var "ts"

Console.WriteLine("RunTime " + ts.ToString());

Using DateTime

DateTime start = DateTime.Now;

// Your code, it could be in-line code, a web service call or whatever code you want to analyse, goes here

DateTime end = DateTime.Now;

TimeSpan ts = end - start;

Console.WriteLine("Time taken : " + ts.ToString());

Free .NET decompiler

ILSpy

ILSpy is a free .Net decompiler.

ILSpy requires the .NET Framework 4.0.

Click here to download

Wednesday 18 June 2014

How to detect IE11 from User Agent?

Pre-IE11 versions of Internet Explorer browser have a common pattern/string i.e. "MSIE" within their user agent string. But that is not the case with IE11.

IE11 user agent string

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

IE10 user agent string

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)

Here is some JavaScript code to identify the version Internet Explorer from user agent string


var isIE11 =  navigator.userAgent.match(/Trident.*rv\:11\./);

var isIEButNotIE11 =  navigator.userAgent.match(/MSIE (\d+\.\d+)/);

This function can be used to get the version number of IE

function IEVersion() {

    var ieversion;

    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        ieversion = new Number(RegExp.$1);
    else if (navigator.userAgent.match(/Trident.*rv\:11\./))
        ieversion = 11;

    return ieversion;
}

What is My User Agent?

I found this website today while I was looking for differences between User Agent value of IE11 and other older versions of IE.

http://www.whatsmyuseragent.com/

When you open the website it will display your user agent string and IP address as well.