This blog is moved to
http://amalhashim.wordpress.com

Monday, June 29, 2009

Convert time from one timezone to another in .Net

DateTime dlocal = DateTime.Now;

DateTime dNonLocal = TimeZoneInfo.ConvertTime(dlocal, TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"));

Thursday, June 25, 2009

Comma delimted String from List of String using C#

When you have a list of strings like IList of IEnumerable and you want to convert it to for example a comma separated list you can easily do that with the String.Join method.

List<string> list = new List<string>() { "A" , "B", "C", "D", "E" };
string commaSeparated = String.Join(",", list.ToArray());

The output will be like this:

A,B,C,D,E
This is an easy and clean way to create a delimiter separeated list of strings.

Getting calling method name in C# using Reflection

The name of the calling method can be extracted from the stack. Since the method on top of the stack is the method that is currently being executed, the calling method will be right below it. Thus, by instantiating StackTrace and getting the frame with index 1 will result in getting a StackFrame that corresponds to the call from the calling method. Finally, reflection can be used to get method name.
using System.Diagnostics;

void Log(string eventMessage)
{
Console.WriteLine("Event logged by " + (new StackTrace()).GetFrame(1).GetMethod().Name);
Console.WriteLine("Event: " + eventMessage);

}

Sunday, June 21, 2009

Enabling Aero and Glass Effects on Vista Home Basic

For enabling Aero you can do the following steps

Regedit:

HKCU/Software/Microsoft/Windows/DWM/

Composition = 1
CompositionPolicy = 2

Right click Command Prompt and run as admin:

net stop uxsms
net start uxsms

For enabling glass there is no hacks till found, one workaround is to use the free utility Glass2K from the below link

http://chimetv.com/tv/products/glass2k/Glass2k.exe

Saturday, June 20, 2009

URL Encoding

RFC 1738: Uniform Resource Locators (URL) specification

The specification for URLs (RFC 1738, Dec. '94) poses a problem, in that it limits the use of allowed characters in URLs to only a limited subset of the US-ASCII character set:

"...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL."

HTML, on the other hand, allows the entire range of the ISO-8859-1 (ISO-Latin) character set to be used in documents - and HTML4 expands the allowable range to include all of the Unicode character set as well. In the case of non-ISO-8859-1 characters (characters above FF hex/255 decimal in the Unicode set), they just can not be used in URLs, because there is no safe way to specify character set information in the URL content yet [RFC2396.]

URLs should be encoded everywhere in an HTML document that a URL is referenced to import an object (A, APPLET, AREA, BASE, BGSOUND, BODY, EMBED, FORM, FRAME, IFRAME, ILAYER, IMG, ISINDEX, INPUT, LAYER, LINK, OBJECT, SCRIPT, SOUND, TABLE, TD, TH, and TR elements.)

Characters that must be encoded includes the following

ASCII Control characters

These are ASCII non-printable character. Includes the ISO-8859-1 (ISO-Latin) character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal.)

Non-ASCII characters

These are by definition not legal in URLs since they are not in the ASCII set. Includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal.)

Reserved characters

URLs use some characters for special use in defining their syntax. When these characters are not used in their special role inside a URL, they need to be encoded. Below table provides a snapshot of the reserved character.

CharacterCode
Points
(Hex)
Code
Points
(Dec)
Dollar ("$")
Ampersand ("&")
Plus ("+")
Comma (",")
Forward slash/Virgule ("/")
Colon (":")
Semi-colon (";")
Equals ("=")
Question mark ("?")
'At' symbol ("@")
24
26
2B
2C
2F
3A
3B
3D
3F
40
36
38
43
44
47
58
59
61
63
64

Unsafe characters

Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded.

CharacterCode
Points
(Hex)
Code
Points
(Dec)
Why encode?
Space2032 Significant sequences of spaces may be lost in some uses (especially multiple spaces)
Quotation marks
'Less Than' symbol ("<")
'Greater Than' symbol (">")
22
3C
3E
34
60
62
These characters are often used to delimit URLs in plain text.
'Pound' character ("#") 2335 This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins.
Percent character ("%") 2537 This is used to URL encode/escape other characters, so it should itself also be encoded.
Misc. characters:
Left Curly Brace ("{")
Right Curly Brace ("}")
Vertical Bar/Pipe ("|")
Backslash ("\")
Caret ("^")
Tilde ("~")
Left Square Bracket ("[")
Right Square Bracket ("]")
Grave Accent ("`")

7B
7D
7C
5C
5E
7E
5B
5D
60

123
125
124
92
94
126
91
93
96
Some systems can possibly modify these characters.

How are characters URL Encoded?

URL encoding of a character consists of a "%" symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character.

Using C# How you can encode and decode URL's

.Net provide HttpUtility class for encoding and decoding URL's. You need to add System.Web reference to your project. Once you have added you can use the below code for encoding and decoding.

using System;
using System.Web;

namespace TestProject
{
class Program
{
static void Main(string[] args)
{
string encodedString = HttpUtility.UrlEncode("[hi this is a sample]");
Console.WriteLine("Encoded String : {0}", encodedString);

string decodedString = HttpUtility.UrlDecode(encodedString);
Console.WriteLine("Decoded String : {0}", decodedString);

Console.ReadLine();
}
}
}

Find whether an assembly was compiled in Debug or Release mode

I know two ways of accomplish this:
  • Searching for the System.Diagnostics.DebuggableAttribute
  • Searching for the System.Reflection.AssemblyConfigurationAttribute
Either attributes are applied to Assemblies and can be found in the Assembly Manifest but there are a major difference between them:
  • AssemblyConfigurationAttribute must be added by the programmer but is human readable.
  • DebuggableAttribute is added automatically and is always present but is not human readable.
You can easily get the Assembly Manifest by using the amazing ILDASM from your Visual Studio Studio Command Prompt:





And if you double click the MANIFEST item you will get all manifest data.

Looking carefully you will find the DebuggableAttribute:



And perhaps the AssemblyConfigurationAttribute.

AssemblyConfigurationAttribute

Locate the AssemblyConfigurationAttribute – this attribute can be easily interpreted: its value can either be Debug or Release.

DebuggableAttribute

If AssemblyConfigurationAttribute is not present then we must use the DebuggableAttribute to get our goal.

Since we cannot understood the DebuggableAttribute value we have to open the assembly from another tool and read this attribute content. There’s no such tool available out-of-the-box but we can easily create a Command Line tool and use a method similar to:

private bool IsAssemblyDebugBuild(string filepath)
{
return IsAssemblyDebugBuild(Assembly.LoadFile(Path.GetFullPath(filepath)));
}
private bool IsAssemblyDebugBuild(Assembly assembly)
{
foreach (var attribute in assembly.GetCustomAttributes(false))
{
var debuggableAttribute = attribute as DebuggableAttribute;
if (debuggableAttribute != null)
{
return debuggableAttribute.IsJITTrackingEnabled;
}
}
return false;
}

or (if you prefer LINQ)

private bool IsAssemblyDebugBuild(Assembly assembly)
{
return assembly.GetCustomAttributes(false).Any(x =>
(x as DebuggableAttribute) != null ?
(x as DebuggableAttribute).IsJITTrackingEnabled : false);
}

Thursday, June 18, 2009

24 javascript best practices for beginners - Jeffrey Way

Jeffrey Way has written an interesting article which describes the best practices we must follow while writing javascript.

The original article can be accessed from the below link.

http://net.tutsplus.com/tutorials/javascript-ajax/24-javascript-best-practices-for-beginners/