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

Sunday, June 7, 2009

ASP.Net webpage Keyboard shortcut using jQuery

Nowadays most of the webapplication supports keyboard shortcut. Example of such applications include Windows Live Mail, Gmail etc. By using keyboard shortcuts user can do most of the operations using keyboard instead of switching between keyboard and mouse. In this article i will be explaining how to define our own keyboard shortcuts in webpages using ASP.Net and JQuery.

Prerequisites

.Net Framework 2.0 and above
jQuery

How To

1. Create a new ASP.Net website.

Here i will be demonstrating how we can navigate from one webpage to another using keyboard shortcuts.

2. Add a masterpage (default.aspx) and add two more webpages (page1.aspx, page2.aspx) to the current web application.

3. In the default.aspx add two linkbutton. These button will navigate to page1.aspx and page2.aspx respectivly.


<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1 Runat=">
<div>
<asp:linkbutton id="lnkPage1" runat="Server" poskbackurl="Page1.aspx">Page1</asp:LinkButton>
<br />
<asp:linkbutton id="lnkPage2" runat="Server" poskbackurl="Page2.aspx">Page1</asp:LinkButton>
<br />
</div>
</asp:Content>


4. In master page add the following jQuery


<head runat="server">
<title>My Website</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).keyup(function(event) {
var key = event.keyCode || event.charCode || 0;
if (key == 49) { // Page One Press 1
eval($("[id$='lnkPage1']").attr("href"));
} else if (key == 50) { // Page Two Press 2
eval($("[id$='lnkPage2']").attr("href"));
}
});
});
</script>
<asp:contentplaceholder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>


Using jQuery we are using the KeyUp event and performing actions based on which key has been pressed by the user. The KeyUp event fires when a key on the key is released. The key is captured using the event.KeyCode which returns the Ascii value of the key.

Here in our application page1 shortcut key is 1, whose Ascii value is 49 and page2 shortcut key is 2 whose Ascii value is 50.

In code we are accessing the master page control using $("[id$='lnkPage1']". The '$=' operator will match the end of the id string as in ctl100_ContentPlaceHolder1_lnkPage1

Once the page is rendered, we can see the source. The link button will be in the following html format


<a id="ctl00_ContentPlaceHolder1_lnkPage1" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$lbPage1", "", false, "", "Page1.aspx", false, true))"> Page 1</a>


The javascript code in the href which is responsible for the postback when the linkbutton is clicked. So we will be trying to invoke the same code using Keyboard shortcut. For this we will be using eval(), which executes the javascript code and emulates a click().

This article is just for explaining how to use jQuery with Asp.net webpage to create userfriendly applications. Am assuming you will get the trick of how the most popular webapplications make use of keyboard shortcut. You can extend the demostrated approach as per your requirement.

C# Sql Server Connection String

// ODBC DSN

using System.Data.Odbc;

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=DsnName;" +
"Uid=UserName;" +
"Pwd=Secret;";
conn.Open();

// ODBC -- Standard Connection

using System.Data.Odbc;

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Driver={SQL Server};" +
"Server=ServerName;" +
"DataBase=DataBaseName;" +
"Uid=UserName;" +
"Pwd=Secret;";
conn.Open();

// ODBC -- Trusted Connection

using System.Data.Odbc;

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Driver={SQL Server};" +
"Server=ServerName;" +
"DataBase=DataBaseName;" +
"Uid=;" +
"Pwd=;";
conn.Open();

// or

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Driver={SQL Server};" +
"Server=ServerName;" +
"DataBase=DataBaseName;" +
"Trusted_Connection=Yes;";
conn.Open();

// OleDb -- Standard Connection

using System.Data.OleDb;

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString =
"Driver=SQLOLEDB;" +
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

// OleDb -- Trusted Connection

using System.Data.OleDb;

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString =
"Driver=SQLOLEDB;" +
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();

// OleDb -- via IP Address

using System.Data.OleDb;

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString =
"Driver=SQLOLEDB;" +
"Network Library=DBMSSOCN;" +
"Data Source=xxx.xxx.xxx.xxx,1433;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

// .NET DataProvider -- Standard Connection

using System.Data.SqlClient;

SqlConnection conn = new SqlDbConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

// .NET DataProvider -- Trusted Connection

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();

// .NET DataProvider -- via IP Address

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Network Library=DBMSSOCN;" +
"Data Source=xxx.xxx.xxx.xxx,1433;" +
"Initial Catalog=DataBaseName;" +
"User Id=UserName;" +
"Password=Secret;";
conn.Open();

ASP.Net MVC Framework

Its a template which enable to create an ASP.NET programming environment centered around the MVC pattern. MVC framework doesn't support classic postbacks and viewstate and doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class.

In MVC framework, a URL is seen as the mean to address a logical server resource, but not necessarily an ASPX file to parse. MCV Framework employs a centralized HTTP handler that recognizes an application-specific syntax for links.

  • Enables clean separation of each component.
  • All contracts within the MVC framework are interface based and easily mockable.
  • Highly extensible and pluggable.
  • Include powerful URL mapping that enables to build applications with clean URLs.
  • MVC framework supports using the existing ASP.Net, aspx, ascx and .master files as view templates.
  • Supports existing Asp.net features like forms/windows authentication etc.

Representational State Transfer (REST)

REST is an architectural pattern that defines how network resources should be defined and addressed in order to gain shorter response times, clear separation of concerns between the front-end and back-end of a networked system. Rest is based on three following principles

1. Application expresses its state and implements its functionality by acting on logical resources
2. Each resource is addressed using a specific URL syntax
3. All addressable resources feature a contracted set of operations.

Here each page is splitted into distinct components - controller and view - that operate over the same model. This is opposed to the classic code-behind model where no barrier is set that forces you to think in terms of separation of concerns and controllers and view.

We can view MVC Framework as, having a central HTTP handler that captures all requests to resources identified with a new extension. This HTTP handler analyzes the syntax of the URL and maps it to a special server component known as the controller. The controller supports a new of predefined actions. The requested action is somehow codified in the URL according to an application-specific syntax. The central HTTP handler invokes the action on the controller and the controller will process the request up to generating the response in whatever response format you need. The response is generated through a view component.

Saturday, June 6, 2009

C# Namespace And Assemblies - Part 2

Assembly structure

Assemblies are built up of Common Intermediate Language (CIL) code. Also named as Microsoft Intermediate Lanaguage (MSIL). It contains information needed by the Just-In-Time (JIT) compiler to convert the CIL into native code @ runtime including references to other assemlies it references. Assemblies can be either exe or dll.

Four sections of an Assembly

1. First section called assembly manifest holds the following details

  • Identity of the Assembly
  • List of files that make up the assembly
  • Map of where things are in the assembly
  • Information about other assemblies that are referenced

2. Second section is called metadata section which contains information about all the types defined in the assembly. This information contains everything there is to know about each type.

3. Third section called CIL section contains the intermediate code for the assembly.

4. Fourth section is optional called resources section which hold graphics and other language resources.

Assemblies comprising more files will have one file as the primary module and the others as the secondary modules. Primary module contains the manifest of the assembly and references to the secondary modules. The file names of secondary modules end with extension .netmodule. The multiple-file assemblies are considered a single unit. They are developed together and versioned together

Identity of an Assembly

Identity of an assembly has 4 components that together can uniquely identify it.

1. Simple Name - File name without the file extension
2. Version Number - A string of four period separated integers in the form of
MajorVersion.MinorVersion.Build.Revision Ex 2.0.35.9
3. Culture Information - String that consists of two to five characters representing a language, or a language and a country or region. Example en-US
4. Public key - 128-byte string that is unique to the company producing the assembly

The public key is part of a public/private key pair, which is a set of specially chosen numbers that can be used to create secure digital signature. Public key is part of the assembly's identity.

Strongly Named Assemblies

Strong named assembly has a unique digital signature attached to it. Strong named assemblies has the following benefits

1. A strong name uniquely identifies an assembly. So the user can be sure that the assembly came from the claimed source.
2. Contents of an assembly with a string name cannot be altered without the security
components of the CLR catching the modification.
3. Strong named assemblies can only access other strongly named assemblies.

Programmer does not produce the strong name. The compiler produces it by taking information about the assembly and hashing it to create a unique signature that it attached to the assembly. Information uses in the hash process are

1. Sequence of bytes composing the assembly
2. Simple name
3. Version number
4. Culture information
5. Public/private key pair

Creating a Strongly Named Assembly

Using Visual Studio 2008

Open the properties of the project =>
Select Signing tab =>
Select the sign the Assembly check box and enter the location of the key file

Once we compile the project, compiler will produce a strong names assembly



Deploying an Assembly

We can just copy the assembly to a local directory along with the application. Program deployed this way are called private assemblies and the method of deployment is called xcopy deployment.

In some scenarios we will need to place the dll in a central location so more than once application can refer and user it. .Net has such a repository, called the global assembly cache(GAC). An assembly placed into the GAC is called a shared assembly. Only strong named assemblies can be added to the GAC.

The physical location of GAC is WindowsInstallationFolder\Assembly Ex: C:\Windows\Assembly

Installing Assemblies into the GAC

When we try to install an assembly, CLR's security component verifies the digital signature on the assembly in valid. If there is no digital signature, then the system will not install it into GAC.

The gacutil.exe command-line utility allows to add and delete assemblies from the GAC, and list the assemblies it contains.

We can use the following switched with the gacutil tool

/i - inserts an assembly into the GAC
/u - uninstalls an assembly from the GAC
/l - lists the assemblies in the GAC

Since an assembly identity consist of four parts, so if the version number of the library changes, or it has a different public key, these differences specify different assemblies. This results by which we can have many different assemblies in the GAC that has the same file name although they are different assemblies. This makes it easy for different applications to use different versions of the same dll at the same time. This is called side-by-side execution.

Delayed Signing

In delayed signing or partial signing the compiler uses only the public key for signing. The public key will be placed in the manifest to complete the assembly's identity. Delayed signing also uses a block of 0's to reserve space for the digital signature.

For creating a delay-signed assembly we must first create a copy of the key file that has only the public key. Next, add an additional attribute called DelaySignAttribute to the assembly scope of the source code and set its value to true.

C# Namespace And Assemblies - Part 1

Visual studio compilers produces assemblies as output.
Assemblies can be executables as well as class libraries.

Example of a class library

public class Calculator
{
int value1, int value2;
public Calculator(int value1, int value2)
{
this.value1 = value1;
this.value2 = value2;
}

public int Add()
{
return this.value1 + this.value2;
}

public int Add(int value1, int value2)
{
return value1 + value2;
}
}

When we compile this class using a C# compiler to produce a class library (Calculator.dll).

If we want to use Calculator object in say MyApplication

class MyApplication
{
static void Main()
{
Calculator calc = new Calculator(10, 20);
Console.WriteLine(calc.Add());
Console.WriteLine(calc.Add(20, 30));
}
}

The above code doesn't declare class Calculator, instead we will be using the classlibrary which contains the declaration of Calculator. But for MyApplication to compile properly, the compiler must be aware of the code in the assembly Calculator. For achieving this we need to give the compiler a reference to the assembly, by giving its name and location.

In Visual studio we can add references to a project by right clicking the project from solution explorer and adding reference to Calculator.dll

Once the reference is added MyApplication will compile properly.

The MsCorLib library

mscorlib is the assembly which contains the Console class. It resides in mscorlib.dll assembly. It also holds C# types and the basic types for most. This assembly is always required because of this Visual studio won't be displaying it under references folder.

Now if we have another Calculator class in say assembly Calculator1.dll.
If we use Calculator in MyApplication then a name clash can happen.

Namespaces

Namespace feature will help us to avoid the above problem. Namespaces group a set of types together and give them a name called the namespace name.

namespace SampleNamespace
{
TypeDeclarations
}

Namespace can contains period

namespace ABC.Calculator
{
public class Calculator
{
}
}

namespace XYZ.Calculator
{
public class Calculator
{
}
}

Now we can use both Calculator class and avoid the conflict.

In MyApplication we can qualify Calculator class as

ABC.MyCalculator.Calculator calc = new ABC.MyCalculator.Calculator();
XYZ.OurCalculator.Calculator newCalc = new XYZ.OurCalculator.Calculator();

Namespace can be any valid identifier. Period can be used to organize types into hierarchies.

1. Start namespace names with the company name.
2. Follow the company name with technology name.
3. Do not name a namespace with the same name as a class or type
4. Every type in a namespace must be different from all the others
5. The types in a namespace are called members of the namespace

BCL offers thousands of classes and types for building applications. Namespaces help to organize the related functionality in the same namespace.

Namespace is not closed in a single source file.

Namespace can be a member of another namespace. The member is called a nested namespace.
Two types of nesting

Textual nesting

namespace Nested
{
namespace Nested1
{
}
}

Separate declaration

namespace Nested
{
}

namespace Nested.Nested1
{
}

Using Directives


Since fully qualified names can be quite long, compiler gives flexibility to shorten it using either using namespace directive or using alias directive. We must be use the using directive on top of the source file before any type declarations. They will be applied for all the namespaces in the current source file.

Example

using System;

so in MyApplication we can use as

Console.WriteLine("") instead of System.Console.WriteLine

Using Sys = System;

Sys.Console.WriteLine("")

Thursday, June 4, 2009

Validating URL using C#

Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(txtUrl.Text))
{
MessageBox.Show("URL is valid.");
}
else
{
MessageBox.Show("URL is invalid!");
}

The above code will validate URL's without http also. Alternatively you can use this

System.Globalization.CompareInfo cmpUrl = System.Globalization.CultureInfo.InvariantCulture.CompareInfo;
if(cmpUrl.IsPrefix(txtUrl.Text, "http://") == false)
{
txtUrl.Text = "http://" + txtUrl.Text;
}
Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(txtUrl.Text))
{
MessageBox.Show("URL is valid.");
}
else
{
MessageBox.Show("URL is invalid!");
}

Wednesday, June 3, 2009

C# Preprocessor Directives

Preprocessor directives guides the compiler how to treat the source code. In some scenarios we need to ignore some portions of the code, in such scenarios preprocessor directive can help. C# preprocessor directives are handled by the compiler.

Rules

1. Preprocessor directives must be on separate line
2. Must not terminate with semicolon compared to normal C# statements
3. Starts with # character
4. End of line comments are not allowed
5. Delimited comments are not allowed

Example

#define Version1

Preprocessor Directives


#define identifier - Defines a compilation symbol
#undef identifier - Undefines a compilation sysmbol
#if expression - If the expression is true, compiles the following section
#elif expression - If the expression is true, compiles the following section
#else - If the previous #if or #elif expression is false, compiles the following section
#endif - Marks the end of an #if construct
#region name - Marks the beginning of a region of code
#endregion name - Marks the end of a region
#warning message - Displays a compile time warning message
#error message - Displays a compile time error message
#line indicator - Changes the line number displayed in compiler messages
#pragma text - Specifies information about the program context


#define and #undef

It can be any identifier except true or false. It will be represented as a string.

#define declares a symbol while #undef undefines a symbol.

#define Version1
#define Version2
....

#undef Version1

One thing we must remeber is, both #define and #undef must be used before any C# code. After code the #define and #undef directives can no longer be used.

using System;

#define Version1

namespace MySampelNamespace
{

#define Version2 /// Erro

The symbol scope is limited to a single source file.

Conditional Compilation

Helps use to mark a section of source code to be either compiled or skipped.

Condition is an expression which can be evaluated to either true or false.
Expression can have the following operators
!, ==, !=, &&, ||

#if !Version1
///Code
#endif

#if true
///Code
#endif

#if !Version1
///Code
#else
///Code
#endif

#if !Version1
///Code
#elif !Version2
///Code
#else
///Code
#endif

Diagnostic Directives

#warning Message

#error Message

The diagnostic messages will be listed along with the compiler generated warnings and error messages.

#if !Version1
#warning Version1 is not defined compiling version specific code
#end if

Line Number Directives

This directive can be used to do the following things
1. Change the line numbers reported by the compiler's warning and error messages
2. Change the filename of the source file being compiled
3. Hide a sequence of lines from the interactive debugger

#line integer
#line "filename"
#line default // Restores the real line number and filename

#line hidden //Hides the following code from stepping debugger
#line //Stops hiding from debugger

#line 250
sum = total + expense; /// From here the line number will be 250

#line 200 "changefile.cs" /// From here the line number and file will be changed

Region Directives

#region name
///Code for region 1
#endregion

This directive is used by visual studio for hiding and displaying regions

The Pragma warning Directive

Allows to turn off warning messages and to turn them back on.

#pragma warning diable 100, 200 /// Warning messages on line 100 and 200 will be diabled

#pragma warning restore 100 /// restore the warning @ line 100

#pragma warning disable /// disable all warning

#pragma warning restore /// enable all warning