Hello world!

February 24, 2009

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Guidelines on developing WPF and Silverlight Applications

February 19, 2009

Microsoft has recently released the guidelines for developing composite WPF and Silverlight applications. The guidelines are supported with sample source code and documentation. The Composite Application Guidance for WPF and Silverlight is designed to help you more easily build enterprise-level Windows Presentation Foundation (WPF) and Silverlight client applications. It will help you design loosely coupled, independently evolvable pieces that work together in the overall application.

The guidance includes a reference implementation, reusable library code (named the Composite Application Library), documentation, QuickStart tutorials, and hands-on labs.

You can download the guidelines here.

Exception handling in Ajax

February 1, 2009

Exception handling plays an important role in any application development. The way we present our exceptions to the user decides the quality of our software. The way we design a pattern for exception handling in C#, ASP.NET we should also design a similar pattern for implementing Ajax exceptions. If an Ajax exception is not caught, then it should as a pop-up directly on the screen showing the exact technical error message with a code. A layman/user will never know what went wrong behind the scene.

Ajax Exception Message


Different ways of handling exception in Ajax
1. Using the AsyncPostBackErrorMessage property of the Script Manager class
You can set the exception message that needs to be shown to the user to the AsyncPostBackErrorMessage property of the ScriptManager object. This can be achieved in the following way:


scriptManager.AsyncPostBackErrorMessage = "Oops..\nAn error occurred while processing";

Set the above exception message in the catch block of the method. When an exception occurs, this message will be shown to the user in a pop-up window.

2. Using the above method will show the exception message to the user as a pop-up window. It is not a good practice to show a pop-up on error. Better way to do is to add a Label field to the web page and set the text of that label field with the exception message. For more clarity to the user, the exception message can be shown in Red color. Ajax inherently exposes an event OnAsyncPostBackErrorHandler. This event is invoked when an exception occurs in your web page. It is better to set the exception message in this event as shown below:

 protected void OnAsyncPostBackErrorHandler(object sender, AsyncPostBackErrorEventArgs e)
{
scriptManager.AsyncPostBackErrorMessage = "Oops..\nAn error occurred while processing";
}

Is this going to suffice? The answer it NO. Here we have just handled an event and set the required exception message to the AsyncPostBackErrorMessage property of the scriptManager class. We have to handle another event at client side to set this message to the Label control and inform the Ajax manager to not show the ugly pop-up. Following code will be inserted at the client side:

 <script language="javascript" type="text/javascript">
// Register the EndRequest Ajax event
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

// Here the Ajax EndRequest event is used to supress any ALERT error message and
// show them in the lblStatus instead.
function EndRequestHandler(sender, args) {
if (args.get_error()) {
var msg = args.get_error().description;
msg = msg.replace('Sys.WebForms.PageRequestManagerTimeoutException:', '');
msg = msg.replace('Sys.Webforms.PageRequestManagerServerErrorException:', '');
document.getElementById('ctl00_mainPlaceHolder_lblStatus').innerText = msg;
// This will avoid the pop-up
args.set_errorHandled(true);
}
}

</script>

Hope this helps. Your comments are welcome!

Window.open displays the cached version of page

January 29, 2009

Window.open JavaScript function inherently opens the cached version of the page requested. For the first time the web page will be brought from the server, but for subsequent requests it will display the cached version of the page that was bought first. How to avoid this..?

Window.open shows the cached version of the page ONLY if the URL requested matches the cached page URL. The best option is to change the URL every time you try to use the window.open statement. This can be achieved by two methods:

  1. Append a dummy queryString with Random value
  2. Append a dummy queryString with DateTime stamp

Out of the two the second method is most reliable, since the DateTime stamp will be unique every time you invoke the window.open statement. Example:


var dt = new Date().toString();
var URLToOpen = 'http://server.com/page1.aspx?TimeStamp=' + dt;
window.open('New Page','',URLToOpen);

Your comments are welcome.

How to get the position of a control using Javascript?

January 24, 2009

Here is a handy functions to get the posisiton of a control using Javascript:

Usage:

alert(getElementPosition('txtName').top + ' ' + getElementPosition('txtName').left);

Function:

 function getElementPosition(elemID) {
var offsetTrail = document.getElementById(elemID);
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail) {
offsetLeft += offsetTrail.offsetLeft;
offsetTop += offsetTrail.offsetTop;
offsetTrail = offsetTrail.offsetParent;
}
return { left: offsetLeft, top: offsetTop };
}

We can get the current scroll position of the document using:

var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement.scrollLeft;

Hope this helps you…

Virtual Tech Days is back!

January 23, 2009

Virtual Tech Days.. A series of technical sessions delivered by key note speakers is back ! The agenda for the sessions en comprises of Top web application security bugs, Weaving security in your apps, SDL threat modeling, ASP.NET Ajax fundas, UX fundas, WPF and lot more. Hurry up and register yourself to this exciting event!

You can find more info here:
http://www.virtualtechdays.com

Thanks!

How to Encrypt a Section in Web.Config?

January 20, 2009

It is often required to encrypt usernames, passwords or even connection string in the web.config file. The usual method to do is using any of the encryption algorithm and saving the encryption Key in the config file. .NET has provided with a classic feature of encrypting an entire section in the web.config file. Using this feature .NET saves the key in the Machine.key file. User ONLY needs to encrypt the section in the web.config file, the decryption of the section is taken care by the .NET framework. Here is a step by step procedure on encrypting a section:

Section in Web.config


<!-- User Credentials -->
<ImpersonateUser>
<add key ="domain" value ="domain_name"/>
<add key ="username" value ="user_name"/>
<add key ="password" value ="password"/>
</ImpersonateUser>

Step 1:
Open the Visual Studio Command Prompt in Administrative Mode
Go to Start –> Programs –> Visual Studio 2008 –> Visual Studio Tools –> Visual Studio Command Prompt right click and say “Run as Administrator

Step 2:
Type the following command:
aspnet_regiis -pef “ImpersonateUser” “D:\SourceCode\RootFolder” -prov “RsaProtectedConfigurationProvider
The web.config file should be present at the path “D:\SourceCode\RootFolder”. The actual command looks like:
aspnet_regiis -pef “SECTION_NAME” “PATH_TILL_WEB.CONFIG” -prov “ENCRYPTION_PROVIDER”

Step 3:
Run the above command.
The above command will encrypt the ImpersonateUser section in the web.config file and will save the web.config file at the given location. The encrypted section will look like:


<ImpersonateUser configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>nQGcFhli6gRmNXD1vjJG+fQw8nN80NwaXjKsVDsSbcoLqAmbKPDhZZvXw1E81uY6+3AhmUzp1SQSTavIVKjj8RvQI21LzaSSc8UUwo7Q7ZRHeBCpyQE+xRs9BlvsXjyn0oX/q5Ns4uoRU3OEkJlcYmFizrGG7YuHdvogh8+wFLE=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>YJODT4I4FKNuUqG3o3QEn8UGXS3jSeFjkVsE2r+jQuBy6fqh4Uc/psu49Rr0SgsDlx7RDm+yIzztRki7ETgNCaSwkkX0h3TXsnJv8jA+FuRmOqIXU8sfjF/5p1KNRkj8l1yzFueom2llRpjprclTvxlTVUQopOTXuodBV3dFnqnqTe/gu70GOqdNooNyWgn02hvG5GjL4mXdb8iMGDMJSrgin6E3nYMrkV71nMkPXi8+MeenWfRWQ1BH8BNblC9R</CipherValue>
</CipherData>
</EncryptedData>
</ImpersonateUser>

Most important thing is, while using the web.config key’s in the C# code we DO NOT have to decrypt the section. .NET automatically does it and provides us with the decrypted values.

Hope this helps. Your comments will help us improve 🙂

How to convert DataTable to XML in C#?

January 18, 2009

Following code illustrates about converting a DataTable to XML format. This is often required when passing a DataTable to a stored procedure. We can pass an XML directly to the procedure and process it.


/// <summary>
/// This method is used to convert the DataTable into string XML format.
/// </summary>
/// <param name="dtBuildSQL">DataTable to be converted.</param>
/// <returns>(string) XML form of the DataTable.</returns>
private static string ConvertDataTableToXML(DataTable dtBuildSQL)
{
DataSet dsBuildSQL = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;

sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
dsBuildSQL.Tables[0].TableName = "Table";
foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
return XMLformat;
}

Your comments are welcome!

How to position an image on Top Right Cornor of the Browser?

January 18, 2009

Following StyleSheet will position the DIV/IMG tag to the top right cornor of the browser window. This is required when absolute positioning an image is required.


DIV.TopRightCorner
{
position: fixed;
_position: absolute;
top: 0px;
right: 0px;
clip: inherit;
_top: expression(document.documentElement.scrollTop+document.documentElement.clientHeight-this.clientHeight);
_left: expression(document.documentElement.scrollLeft + document.documentElement.clientWidth - offsetWidth);
}

You can change the “top” and “right” to “botton” and “left” to appropriately position an image.
Your comments are always welcome!

How to Position HTML DIV tag at the Center?

January 18, 2009

Following StyleSheet class will position the DIV tag at the center of the screen. This is often required when showing the “Please Wait…” or “Processing…” message while processing Ajax request.


DIV.centered
{
border: 0;
background-color: #6095b3;
height: 10%;
width: 20%;
position: fixed;
_position: absolute;
left: 40%;
top: 40%;
color: black;
z-index: 100;
}

Your comments are always welcome !