Monday, June 29, 2009
Convert time from one timezone to another in .Net
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
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
Getting calling method name in C# using Reflection
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
Regedit:
HKCU/Software/Microsoft/Windows/DWM/
Composition = 1
CompositionPolicy = 2
Right click Command Prompt and run as admin:
net stop uxsms
net start uxsms
http://chimetv.com/tv/products/glass2k/Glass2k.exe
Saturday, June 20, 2009
URL Encoding
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.
Character | Code 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.
Character | Code Points (Hex) | Code Points (Dec) | Why encode? |
---|---|---|---|
Space | 20 | 32 | 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 ("#") | 23 | 35 | This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins. |
Percent character ("%") | 25 | 37 | 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
- Searching for the System.Diagnostics.DebuggableAttribute
- Searching for the System.Reflection.AssemblyConfigurationAttribute
- AssemblyConfigurationAttribute must be added by the programmer but is human readable.
- DebuggableAttribute is added automatically and is always present but is not human readable.
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/
.Net Framework 4.0: System.Linq.Parallel
.Net Framework 4.0 has parallel computing extensions for LINQ. Previously it was possible to download parallel extensions for LINQ separately from CodePlex. Of course, you can still use these extensions if you have older version that 4.0. I wrote a little, simple and pretty pointless example that illustrates how parallel queries work in .Net Framework 4.0.
My example creates simple data source that contains integers from 1 to 100. Then it queries this source two times. At first we will run query with parallel extensions and then we will run usual LINQ query. After querying we will write out the results. So it is really simple code but it returns some interesting results.
private static void ParallelAndSerialQueries()
{
// Source data that parallel and serial queries use.
var source = Enumerable.Range(1, 100);
// Perform parallel query
var parallelQuery = from p in source.AsParallel()
where p.ToString().Contains("1")
select p;
parallelQuery.ForAll((x) =>
{
Console.WriteLine("Parallel: " + x);
});
// Perform serial query
var serialQuery = from s in source
where s.ToString().Contains("1")
select s;
serialQuery.All((x) =>
{
Console.WriteLine("Serial: " + x);
return true;
});
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
Serial | Parallel |
---|---|
1 | 10 |
Now let’s compare data that queries returned. We can see that in the case of classic serial LINQ query and data processing all the values are handled as they were sorted. Bigger number is always after smaller number. This is the same order as numbers have in our data source.
Parallel results are different. If we look at the results we can see that numbers are not ordered all the time. Some numbers are printed out much sooner or later than we may be expected before. This is because of the parallel nature of first query.
Parallel activities doesn’t run on same processor core. Some cores have more things to do and some cores have more free resources. That’s why parallel results have seemingly random order. Okay, their order is not random and as I just said it depends on workload of cores.
Is parallel processing more powerful?
Parallel computing is not another silver bullet that automagically solves performance issues. In the current example serial query was about two times faster that parallel one (exact numbers with 10000 elements in source: serial – 0.68 seconds, parallel – 1.31 seconds). Of course there are scenarios when parallel computing performs way better than serial computing. I recommend you to test the performance of your LINQ queries before you make your final decision over serial and parallel processing.
Using C# UDPClient Send and Receive message
1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel;
4: using System.Data;
5: using System.Drawing;
6: using System.Linq;
7: using System.Text;
8: using System.Windows.Forms;
9: using System.Net.Sockets;
10: using System.Threading;
11: using System.Net;
12:
13: namespace NoticeSystemClient
14: {
15: public partial class MainForm : Form
16: {
17: public delegate void ShowMessage(string message);
18: public ShowMessage myDelegate;
19: Int32 port = 11000;
20: UdpClient udpClient = new UdpClient(11000);
21: Thread thread;
22: public MainForm()
23: {
24: //CheckForIllegalCrossThreadCalls = false;
25: InitializeComponent();
26: }
27:
28: private void MainForm_KeyDown(object sender, KeyEventArgs e)
29: {
30: if (e.KeyCode == Keys.Escape)
31: {
32: thread.Abort();
33: udpClient.Close();
34: Close();
35: }
36: }
37:
38: private void ReceiveMessage()
39: {
40: while (true)
41: {
42: IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
43: byte[] content = udpClient.Receive(ref remoteIPEndPoint);
44:
45: if (content.Length > 0)
46: {
47: string message = Encoding.ASCII.GetString(content);
48:
49: this.Invoke(myDelegate, new object[] { message });
50: }
51: }
52: }
53:
54:
55: private void ShowMessageMethod(string message)
56: {
57: richText.Text = message;
58: }
59:
60: private void MainForm_Load(object sender, EventArgs e)
61: {
62: myDelegate = new ShowMessage(ShowMessageMethod);
63: thread = new Thread(new ThreadStart(ReceiveMessage));
64: thread.IsBackground = true;
65: thread.Start();
66: }
67: }
68: }
Server:
1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel;
4: using System.Data;
5: using System.Drawing;
6: using System.Linq;
7: using System.Text;
8: using System.Windows.Forms;
9: using System.Net.Sockets;
10: using System.Net;
11:
12: namespace NoticeSystem
13: {
14: public partial class MainForm : Form
15: {
16: UdpClient udpClient = new UdpClient();
17: public MainForm()
18: {
19: InitializeComponent();
20: }
21:
22: private void btnClose_Click(object sender, EventArgs e)
23: {
24: udpClient.Close();
25: Close();
26: }
27:
28: private void btnSend_Click(object sender, EventArgs e)
29: {
30: Int32 port = 11000;
31: IPAddress ip = IPAddress.Parse(txtStartIP.Text.Trim());
32: IPEndPoint ipEndPoint = new IPEndPoint(ip,port);
33: byte[] content = Encoding.ASCII.GetBytes(richText.Text);
34: try
35: {
36: int count = udpClient.Send(content, content.Length, ipEndPoint);
37: if (count > 0)
38: {
39: MessageBox.Show("Message has been sent.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
40: }
41: }
42: catch
43: {
44: MessageBox.Show("Error occurs.", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
45: }
46: }
47: }
48: }
Visual Studio 2010 - Historical Debugger
Unlike the debugger of Visual Studio 2008 o before which only record the currently active stack, the historical debugger will record all the event like prior function calls, Method parameter etc(whatever required for debugger) even though there is no breakpoint. This allows the code to be rewound whenever an error occurs.
One drawback of Historical debugger would be that it will take a lot more time and memory as the historical debugger will be recording all events even if no breakpoint are set.
C# - Reading Embedded files at Runtime
Let’s assume we have class library MyExamples.TestLibrary where we have XML-file called mappings.xml. When we compile our class library then mappings.xml will be put inside assembly as embedded resource. Here is the code to read this XML-file (you need to import System.IO, System.Reflection and System.XML namespaces).
C#var fileName = "MyExamples.TestLibrary.mappings.xml";
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(fileName);
if (stream == null)
{
throw new FileNotFoundException("Cannot find mappings file.",
fileName);
}
var doc = new XmlDocument();
doc.Load(stream);
Free ASP.NET 4.0 beta hosting
Guys from ORCS Web are offering free ASP.NET 4.0 beta hosting until the end of October. Hosting plan is called “VS2010 and Web Deployment Tool Beta Program”. If you are interested in it then please feel free to sign up.
Beta hosting plan contains following features.
- Windows Server 2008 / IIS 7,
- Web Deployment for publishing (no FTP),
- ASP.NET 4.0 (or 2.0/3.0/3.5 per request),
- 200MB web space,
- 100MB SQL Server 2008 space,
- ORCS Web support.
Visual Studio 2010 - Multiple web.config
Visual Studio 2010 has support for multiple web.config files. It is one feature of new web application packaging and deployment system. We can create now separate web.config files for each configuration we have for application.
When web application is created then it has two configurations: Debug and Release. Visual Studio 2010 creates also two versions of web.config file as is seen on the image. Depending on active configuration correct web.config will be selected. This technique is called web.config transformation and it allows very powerful transformations of configuration files.
We can easily add new configurations and add web.config files for them right through Visual Studio 2010 IDE.
Web.config file is like template for configurations. Also you can handle it as default configuration. Configuration specific configuration files may add settings or change current ones. This is done using simple transformation tags.
Visual Studio 2010 also allows generation of web.config versions using command-line and MSBuild.
Visual Web Developer Team Blog has very good posting about web.config transformation. This posting is titled as Web Deployment: Web.Config Transformation and it gives you complete overview about transformations and packaging of web.config files.
If you want to try these things out on hosting environment then take a look at my blog entry Free ASP.NET 4.0 beta hosting available and Visual Web Developer Team Blog entry Free Web Hosting to try ASP.NET 4 Beta1, VS 2010 Beta1 and MS Web Deployment Tool RC1.
IIS Search Engine Optimization ToolKit
ScottGu just blogged about the new IIS SEO Toolkit that brings some new SEO features to IIS. You can download it from IIS Toolkit homepage or install it using Microsoft Web Platform Installer.
Toolkit provides you with following site analysis:
- violations like missing attributes of HTML tags,
- missing titles and descriptions,
- invalid markup,
- link text relevance,
- incorrect content types.
You can also find headers, content, links and word analysis for pages.
jQuery Tips
Selectors:
Getting text box value
$(“#TextBoxId”).val();
Chang or set label text
$(“#LabelId”).text(“Your Text”);
Set control CSS “i.e td border width”
$(“#td_id”).css('border-width', '1px');
Animation:
Display DIV element with animation
$("#div-id").show("slow");
$("#div-id").hide("slow");
Swap Items between two lists
$(“#list1-id :selected”).remove().appendTo(“#list2-id”);
Passing parameters to asp.net web services
var prm1=”value”;
var prm2=2;
$.ajax({
type: "POST",
url: "/AjaxWebMethods.aspx/WebMethod ",
data: '{"parameter1":"' + prm1+ '”,"parameter1":"' + prm2+ '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
/*your code*/
},
error: function(err) { /*your code*/}
});
Look for data line
Wednesday, June 17, 2009
AJAX Callback to ASP.NET Using jQuery
jQuery is just a JavaScript library so it will work seamlessly with ASP.NET both from page code as well as through backend driven code using the Page.ClientScript object or ScriptManager. You can use jQuery on its own as a client side and AJAX library that communicates with ASP.NET or you can use jQuery in combination with ASP.NET AJAX. The two actually complement each other quite well as jQuery provides functionality that the ASP.NET AJAX library does not and vice versa. For the most part the interaction between the two libraries is trouble free except for a few very rare edge cases.
One of the most obvious client-side features of any JavaScript client library is the ability to make AJAX calls to the server. jQuery includes a host of AJAX functions that make it easy to retrieve content from a URL in a variety of ways. Here’s a list of some of the functions available:
$.ajax(opt)
This the low-level AJAX function with many, many options that lets you create just about any kind of AJAX request. If you need full control over requests or you want to create a generic component that calls back to the server (like the WCF/ASMX client proxy I’ll discuss later) you’ll want to use this function. For now check out the documentation (http://tinyurl.com/4mcnaa) on the multitude of options available.
$(sel).load(url,callback)
The .load() function is the only AJAX function that works off a jQuery selector. It calls a URL on the server and loads the result as content into selected element(s). It’s a very quick and easy way to load HTML fragments and inject them into the client HTML document. You can provide an optional callback to be notified with the server result text when the callback completes, which is useful if you want to visually adjust the retrieved content-like applying an effect to visually cue the user to an update.
$.get(url,callback),$.post(url,data,callback)
These functions are simple helpers that provide basic get and post operations to the server. You specify a URL and a callback, which is called with the HTTP response from the server. $.post() also allows you to pass either a formatted POST buffer string or an object the properties of which are turned into POST encoded key value pairs.
$.getJSON(url,data,callback)
Similar to $.post(), but expects the result to be JSON which is automatically deserialized into a JavaScript value and passed to the callback as a parameter. While this function is handy for simple JSON results there are two things to watch out for: Dates are not parsed since there’s no date literal in JavaScript, so whatever the server returns will be used (typically a string). $.getJSON() also doesn’t support JSON POST data-only POST encoded variables. There’s no built-in JSON serialization. $.getJson() function is useful for simple JSON results returned from arbitrary services, but not usable for calling WCF or ASMX ASP.NET services since they expect JSON POST input. I’ll write more on this later in the article.
.getJSON() also supports cross-domain JSONP callbacks. If you specify a query string parameter of callback=? you can force the result to be routed to the callback you specify in the parameter list.
$.getScript(url,callback)
This function loads script code from the server and executes it once downloaded if you haven’t specified a callback. If specified, jQuery fires the optional handler instead and passes the JavaScript, plus the current AJAX request. This can be useful for JSONP cross-domain callbacks where you have no control over the parameters used.
Global AJAX Events
There are also a number of global AJAX events that you can take advantage of, all of which take callbacks as parameters: ajaxCallback(), ajaxError(), ajaxSend(), ajaxStart(), ajaxStop(), and ajaxSuccess(). These are useful for setting up global handlers that can centrally manage AJAX requests. You’re not likely to need these much unless you build components that need to know status of requests.
Heart Beat Design Pattern - Keeping Webpage Session Alive
Sometimes you want your web page to 'stay alive'. That is, if a user is filling out a complicated form, you do not want the session to time out before they are finished.
It's not simply a matter of increasing the session timeout to a very large value. If you do that, the sessions would be left active in the server memory for hours—long after the visitors have left the site. Increasing the session timeout IS a solution… but not necessarily a good solution.
The goal is that the session should stay active as long as the web page is open on the client machine …even if there are no post backs to reset the session timer. When the web page is closed, the session should time out normally.
I implemented a solution for this: The client will "ping" the server at intervals of less than the session timeout which will reset the session timer. This is known as the Heartbeat design pattern.
For testing purposes, I set the Session Timeout to two minutes in web.config:
<system.web>
<sessionState timeout="2">
sessionState>
To trace what is happening, I used a utility function called ODS (it's in a class called MiscUtilities):
/// ---- ODS ---------------------------------------
///
/// Output Debug String with time stamp.
///
public static void ODS(string Msg)
{
String Out = String.Format("{0} {1}",
DateTime.Now.ToString("hh:mm:ss.ff"), Msg);
System.Diagnostics.Debug.WriteLine(Out);
}
To watch the Session State events, I added debugging strings to the global.asax file:
<%@ Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
MiscUtilities.ODS("****ApplicationStart");
}
void Session_Start(object sender, EventArgs e)
{
MiscUtilities.ODS("Session_Start");
}
void Session_End(object sender, EventArgs e)
{
MiscUtilities.ODS("Session_End");
}
Here are the details:
We need a method at the server for the client to call. We use a WebMethod.
1. There must be a ScriptManager on the page.
2. The ScriptManager must have EnablePageMethods set to true.
3. The WebMethod must be public and static.
4. The WebMethod must have the EnableSession attribute set to true.
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="true">
asp:ScriptManager>
public partial class _Default : System.Web.UI.Page
{
[WebMethod(EnableSession=true ) ]
public static void PokePage()
{
// called by client to refresh session
MiscUtilities.ODS("Server: I am poked");
}
We need JavaScript at the client to call the server function at fixed intervals:
<script type="text/javascript">
var HeartBeatTimer;
function StartHeartBeat()
{
// pulse every 10 seconds
if (HeartBeatTimer == null)
HeartBeatTimer = setInterval("HeartBeat()", 1000 * 10);
}
function HeartBeat()
{
// note: ScriptManger must have: EnablePageMethods="true"
Sys.Debug.trace("Client: Poke Server");
PageMethods.PokePage();
}
<body id="MyBody" onload="StartHeartBeat();">
Here is what the output looks like without the heartbeat:
10:22:43.03 ****ApplicationStart
10:22:45.13 Session_Start
10:25:00.00 Session_End
Here is the output with the heartbeat:
10:26:06.10 ****ApplicationStart
10:26:08.05 Session_Start
Client: Poke Server
10:26:18.93 Server: I am poked
Client: Poke Server
10:26:28.95 Server: I am poked
Client: Poke Server
10:26:38.96 Server: I am poked
Client: Poke Server
10:26:48.98 Server: I am poked
. . . (lines deleted)
Client: Poke Server
10:29:59.45 Server: I am poked
Client: Poke Server
10:30:09.47 Server: I am poked
Client: Poke Server
10:30:19.48 Server: I am poked
. . . (lines deleted)
It looks like the session is staying alive while the client is idle: Excellent!
I hope someone finds this useful.
Visual Studio 2010 - Visual Basic Line Continuation
There are some new enhancements in Visual Basic 2010 or Visual Basic 10 where you can really have greater flexibility on how you handle multiple lines for continuous statements,
'Explicit Continious Line (no need to use & _ )
Dim sContinuation As String =
"Hey you know I can write multiple lines without & _"
Console.WriteLine(sContinuation)
'Multiple statements in a single line
Dim sMessage As String = "Hello Visual Basic 10" : Console.WriteLine(sMessage)
Tuesday, June 16, 2009
Visual Studio - JScript errors as warnings
To view JScript errors as warnings, we need to launch Options dialog from Tool -> Options menu, then expand Text Editor -> JScript -> Miscellaneous, check the checkbox "Show errors as warnings". Some users like to have JScript syntax errors shown in the Error List since it would encourage standard compliance, while others don't like to deal with validation errors since they are browser errors.
Monday, June 15, 2009
Kerala Microsoft User Group Mini TechEd on 27th June @ Technopark, Trivandrum
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||