Sei sulla pagina 1di 153

Hi,

I need to perform 2 things on submit.

1) if i click on submit button wat ever the empty textboxes are there that has get alert, for which i wrote a
javascipt.

2)if textboxes are not empty and when i click on submit button it has submit to database(table).

i.e before submitting i am calling javascript to check empty textboxes and if not when i click submit to
database.

2 events are performing here on click event.

How to perform these 2 events ..first javascript(for checking textbox's empty) has to perform and next
submit to database.

Plz help me..

//add this javascript to your aspx page


function ValidateControls()
{
if (document.YourFormID.txtBox.value =="" )
{
alert("Your Message");
event.returnValue = false;
return;
}
}
//add these attributes to your button
<asp:Button ID="btnId" runat="server" Text="Button" OnClick="btnId_Click"
OnClientClick="ValidateControls()" />

how to invoke the function in javascript if ur item is selected in listbox......

use following statement in page_load event

ListBox1.Attributes.Add("onchange", "youJavaScriptFunction();");

hello friends,
i have a textbox and dropdownlist.
i m applying validation for this
validation will be in such a way
if textbox is empty then dropdownlist will be empty
if textbox has valuethen dropdownlist will have value in javascript

var txtVal = document.getElementbyID('<%=textbox1.ClienID%>').value;


var ddlVal =
document.getElementbyID('<%=dropdownlist1.ClienID%>').value;
if(txtVal <> "")
{
if(ddlVal == "")
{
alert('please fill both');
return false;
}
}

use following javascript to find out position of the mouse when you click on the page.

<script type="text/javascript">
document.onmousedown = function (event) {
if (!event) {
event = window.event;
}
x = event.clientX;
y = event.clientY;
alert ("X: "+x+"\nY: "+y);
}
</script>

hope this helps.

Send Coding for to use sqlcommand builder in ASP.NET using C# with some sample C#
program

Implementing a Disconnected Data Management Strategy


using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.forms;

class DisconnectedDataform : form


{
private SqlConnection conn;
private SqlDataAdapter daCustomers;

private DataSet dsCustomers;


private DataGrid dgCustomers;

private const string tableName = "Customers";


// initialize form with DataGrid and Button
public DisconnectedDataform()
{
// fill dataset
Initdata();

// set up datagrid
dgCustomers = new DataGrid();
dgCustomers.Location = new Point(5, 5);
dgCustomers.Size = new Size( this.Clientrectangle.Size.Width - 10,
this.Clientrectangle.Height - 50);
dgCustomers.DataSource = dsCustomers;
dgCustomers.DataMember = tableName;

// create update button


Button btnUpdate = new Button();
btnUpdate.Text = "Update";
btnUpdate.Location = new Point(
this.Clientrectangle.Width/2 - btnUpdate.Width/2,
this.Clientrectangle.Height - (btnUpdate.Height + 10));
btnUpdate.Click += new EventHandler(btnUpdateClicked);

// make sure controls appear on form


Controls.AddRange(new Control[] { dgCustomers, btnUpdate });
}

// set up ADO.NET objects


public void Initdata()
{
// instantiate the connection
conn = new SqlConnection( "Server=(local);DataBase=Northwind;Integrated
Security=SSPI");

// 1. instantiate a new DataSet


dsCustomers = new DataSet();

// 2. init SqlDataAdapter with select command and connection


daCustomers = new SqlDataAdapter( "select CustomerID, CompanyName from
Customers", conn);

// 3. fill in insert, update, and delete commands


SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);

// 4. fill the dataset


daCustomers.Fill(dsCustomers, tableName);
}

// Update button was clicked


public void btnUpdateClicked(object sender, EventArgs e)
{
// write changes back to DataBase
daCustomers.Update(dsCustomers, tableName);
}

// start the Windows form


static void Main()
{
Application.Run(new DisconnectedDataform());
}
}The Initdata method in Listing 1 contains the methods necessary to set up the
SqlDataAdapter and DataSet. Notice that various data objects are defined at class level
so they can be used in multiple methods. The DataGrid's DataSource property is set in
the constructor. Whenever a user clicks the Update button, the Update method in the
btnUpdateClicked event handler is called, pushing modifications back to the data base.

Summary
DataSets hold multiple tables and can be kept in memory and reused. The
SqlDataAdapter enables you to fill a DataSet and Update changes back to the data base.
You don't have to worry about opening and closing the SqlConnection because the
SqlDataAdapter does it automatically. A SqlCommandBuilder populates insert, update,
and delete commands based on the SqlDataAdapter's select statement. Use the Fill
method of the SqlDataAdapter to fill a DataSet with data. Call the SqlDataAdapter's
Update method to push changes back to a data base.

http://www.c-
sharpcorner.com/UploadFile/ankithakur/Login_Using_Active_Directory0405200606180
1AM/Login_Using_Active_Directory.aspx

http://msdn2.microsoft.com/en-us/asp.net/bb278076.aspx
_______________________________________________________________________
_
Example: Send email with embedded images
Import Namespaces :

using System.Net.Mail;
using System.Net .NET Classes used :

# System.Net.Mail.LinkedResource
# System.Net.Mail.AlternateView
# System.Net.NetworkCredential
Send email with
embedded
images
This code snippet sends email with
embedded images in the body and
using the SMTP

public bool SendRichMail


(
string[] toAddresses,
string subject
)
{
if (
(toAddresses == null) ||
(toAddresses.Length == 0)
)
return false;

//parity checks and customized messages


string FromAddress = "myname@myserver.com";
//change this to some your email address
string SmtpHost = "smtphost.contoso.com";
//change this to the real smtp server address

string message =
"<html><body><img alt=\"image alternate text\"
src=\"cid:title\" /></body></html> ";

LinkedResource title = new LinkedResource( "title.jpg" );


//this file has to be there in the same directory as this assembly
title.ContentId = "Title";
//this has to match the cid in the message and is not case sensitive

//create an alternate view


AlternateView view =
AlternateView.CreateAlternateViewFromString
(
body,
null,
System.Net.Mime.MediaTypeNames.Text.Html
);

//link the resources


view.LinkedResources.Add( title );
//attach the from address
msg.From = new MailAddress( FromAddress );

//attach the to addresses


try
{
foreach ( string mailId in toAddresses )
msg.To.Add( mailId );
}
catch ( Exception e ) //do not catch Exception. I'm doing
this as I'm throwing back after logging
{
Log( e ); //this is a typical logging code and is
not attached
throw e;
}

//attach the alternate view to the message


msg.AlternateViews.Add( view );
msg.Subject = subject;
msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient();


client.Host = SmtpHost;

//using the default credentials


client.UseDefaultCredentials = true;

//if you are using any other credentials then use this
//string UserName = "username";
//string Password = "password";
//string Domain = "domain";
//client.Credentials = new NetworkCredential( UserName,
Password, Domain );

try
{
client.Send( msg );
}
catch ( Exception e ) //do not catch Exception. I'm
doing this as I'm throwing back after logging
{
Log( e ); //this is a typical logging
code and is not attached
throw e;
}
}
Understanding Security Aspects of .Net Framework – Part 1 of 5

This is part 1 of 5 part series that cover some of the important aspects of the security in
.Net framework.
Author: Sidhartha Gundavarapu
Microsoft

Posted Date: 06 Oct, 2006


.NET Classes used :

Introduction:

This is not an exhaustive guide to security in general or with respect to .Net framework.
This series of articles provides a high level understanding of the security issues that needs
to be known for all developers and how they can be handled. I’m not going to focus on
any part of .Net (say ASP.Net or Windows Forms) but rather give a common set of
features that can be applied to any sort of program (when needed).

To gain some interest on the article, I’ll list down the index. I’m writing these in my spare
time so the duration between one part and another takes some time and more importantly
based on the feedback I receive for my previous ones.

Ok, let me now start off with the index.

Part 1: Overview of Security


Part 2: .Net Framework Security Features
Part 3: Role-Based and Code-Based Security
Part 4: Using Cryptography in .Net Applications
Part 5: Configuring .Net Security

Security is one topic that will work wonders for insomnia patients. So, I’ll try and make
this as simple as possible – yet stressing on the important areas.

In this article, we’ll have a look at common security issues and the challenges of
implementing security in your applications

Importance of Security:

Security of an application is directly related to reach of your application.


If you are developing an application for a personal use, then that application would
typically reside in your machine and in some cases couple of machines. In this case, you
are the owner and the user of the application. These types of applications are the ones
which do not require much of security implemented within them since you know which
code executes for what functionality.
With Internet coming into picture, the software applications that utilize the medium are
more demanding in terms of security. The attackers of these applications have several
means to breach the security and hence there is more responsibility involved. It’s not only
the fundamental duty of the developer to induce security into the system, but that of the
administrators and the architects as well.

Security for Architects:

Security should not be an optional feature in your application. You should plan your
project such that security is one of the important features. There are several problems if
you do not analyze the security threats of your application. Some of them include: Denial
of Service, Automated attacks such as brute-force attack, organizational attacks, viruses,
Trojans, worms and other harmful programs that attack the vulnerability of your
application.

Security for Developers:

Developers should be aware of the types of attacks possible before they code some
functionality. They need to be updated with the information on several new attacks that
attackers/hackers use to exploit vulnerabilities. You can find several of these updates at:
http://msdn.microsoft.com/security. Above all, developers should co-ordinate with the
solution architects and the system administrators to ensure that the application is secure

Security for Administrators:

Administrators should understand the needs of the application and provide the
permissions that are just required for successful execution. Giving any higher privilege to
the application than required is potentially a huge vulnerability. Administrators need to
co-ordinate with the developers in identifying the needs of the application.

Common Threats to your application:

Some of the popular security threats attackers have tried in the past and are now very well
communicated across and gaining much larger audience are:

Buffer overflow – Buffer overflow occurs when a buffer (typically array) declared on the
stack is overwritten by copying data that is larger than the buffer onto that stack. This
causes loss in data. Furthermore, if the return address of the function is overwritten by an
address chosen, the attacker can control the application.

SQL injection – SQL injection occurs when the developer allows unchecked input string
in an SQL statement that will be executed at a database. Using the SQL injection attack,
the attacker can execute arbitrary commands in the database.

Example:
Select * from Products Where productId = ‘” + txtProductId.Text + “’”;

txtProductId can be passed a value of


‘; delete from products --
Hence the SQL statement will be
Select * from products where ProductId = ‘’; delete from products --

This will delete all the rows from the products table

Eavesdropping – Eavesdropping is the intercepting the conversation over a network by


unintended recipients. The entire communication between two end points will be
monitored to find any useful information.

Brute-force attack – brute-force attacks are extensive trial and error methods in order to
obtain a set of valid credentials. Brute-force attack does not have a definite time of
success and the time to break an algorithm is directly proportional to the complexity of
decoding.

Dictionary attack – Dictionary attack is similar to that of a brute-force attack, but instead
of random characters, the trial set consists of all the words in dictionary. The chances are
that the user uses a well know English word or name as his/her password.

Session hijacking – Session hijacking occurs when the attacker takes control of the
session information between two machines. This happens with TCP connections and
when a user opens a connection to a secure machine and the attacker gets hold of the
connection.

Luring attack – luring attack occurs when the attacker gains unauthorized access to the
resources using trusted code with higher privileges. Developer needs to ensure that the
program identifies the users who are authorized to access your application code to gain
indirect access to Operating system resources.

Man in the middle attack – Man in the middle (MITM) is an attack in which the attacker
has complete control of the communication between two end points and is able to read,
write, modify messages at will but without the users at both the end points getting any
clue that their connection has been compromised.

Denial of service – Denial of service (or Nuke attacks) occurs when the attacker
overloads the server with fake requests, thus not allowing its service to the intended
users. Typically the attackers attack web servers so that the website is not accessible to
anybody else.

Credential theft – Credential theft occurs when the attacker gets hold of the user’s login
credentials to access certain resource. Typically, the attacker does a brute-force attack to
get hold of the credentials. Once obtained, the attacker uses these credentials to get hold
of the resources
Data tampering – Data tampering occurs when the attacker interrupts the request and
modifies the request for personal advantage. A popular data tampering attack is to
intercept a billing transaction and change the shipping address.

Session/Cookie replay – A session/cookie replay attack is an attack where valid date is


transmitted repeatedly or delayed so that the attacker maliciously obtains additional
information.

Thanks to Vivek Madani for pointing out these two missing items
Cross-site scripting– Cross site scripting is embedding some malicious script in the page
and providing a fake URL that looks similar to the original URL, so that the user
mistakes the page to be original one and enter some sensitive information which will then
be used by the attacker.

Path traversal attack– This occurs when the attacker tries to manipulate the url to gain
unauthorized resources. for eg.,
http://www.mywebsite.com/sample.aspx?source=sample.html can be manipulated to
http://www.mywebsite.com/sample.aspx?source=bin/mywebsite.dll

Precautionary measures to be taken

Provide least privilege to the application to run correctly. Any additional privilege
provided to the application can always open up un-necessary security holes.

Provide default security settings to the application so that the attacker cannot attack the
application. Make sure that the default privileges are least required ones.

Always validate the user input. Validating the user input for type, length, range etc., can
reduce the attacks such as SQL injection and data tampering.

Never store any secret information on the disk in clear text format. Always encrypt the
secret information using a secure algorithm and a very secret key. This ensures that the
user data is not compromised.

Summary:

Security is a must for all the developers to know and use in their applications. No
application is too small for attacking. This is more so important if your application
involves critical information sharing.

Understanding Security Aspects of .Net Framework – Part 2 of 5

This is part 2 of 5 part series that cover some of the important aspects of the security in
.Net framework.
Author: Sidhartha Gundavarapu
Microsoft

Posted Date: 05 Nov, 2006


.NET Classes used :

Introduction

This is part 2 of 5 part series that covers some of the important aspects of the security.

This is not an exhaustive guide to security in general or with respect to .Net framework.
This series of articles provides a high level understanding of the security issues that needs
to be known for all developers and how they can be handled. I’m not going to focus on
any part of .Net (say ASP.Net or Windows Forms) but rather give a common set of
features that can be applied to any sort of program (when needed).

Part 1: Overview of Security


Part 2: .Net Framework Security Features
Part 3: Role-Based and Code-Based Security
Part 4: Using Cryptography in .Net Applications
Part 5: Configuring .Net Security

Security is one topic that will work wonders for insomnia patients. So, I’ll try and make
this as simple as possible – yet stressing on the important areas.

In this article, we’ll have a look at what are the security features available in .Net
Framework.

Security in .Net

.Net framework provides several inherent security features. The following are some of
the most important features that every .Net developer should know.

1. Type Safety
2. App Domains
3. Stack walks
4. Strong Names

Type safety:

You must be wondering why type safety is part of security features of .Net. This is
because type safety ensures that objects are isolated from each other and restricts any
unwanted corruption of the data. If you recollect the types of attacks, this will ensure that
some of them will be avoided. For example having a type safe array can avoid any kind
of buffer overruns.
Hence, buffer overruns are impossible in .Net. This is true only for managed code. If you
are using unmanaged code in your programs, your code will not be verifiably type safe
and is not complete safe from buffer overrun attacks.

For more information regarding type safety, please read my article Type safety, what and
why?

Usage of PEVerify.exe:

C:\>PEverify.exe
Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

Usage: PEverify <image file> [Options]

Options:
/IL Verify only the PE structure and IL
/MD Verify only the PE structure and MetaData
/UNIQUE Disregard repeating error codes
/HRESULT Display error codes in hex format
/CLOCK Measure and report verification times
/IGNORE=[,...] Ignore specified error codes
/IGNORE=@<file name> Ignore error codes specified in <file name>
/QUIET Display only file and Status. Do not display all errors.
/VERBOSE Display additional info in IL verification error messages.
/NOLOGO Don't display product version and copyright info.

Note: By default, MD is verified and then if there were no errors, IL is


verified. If /MD /IL options are specified, IL is verified even if
there were MD verification errors.

Example:
C:\Test\bin\Debug>peverify Test.exe

Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42


Copyright (c) Microsoft Corporation. All rights reserved.

All Classes and Methods in test.exe Verified.

Code Sample:
//This code fails the verification
unsafe
{
int* ptr = (int*) 0;
*ptr = 1000;
}

C:\>peverify C:\Test\bin\Debug\Test.exe

Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42


Copyright (c) Microsoft Corporation. All rights reserved.

[IL]: Error: [C:\Test\bin\Debug\Test.exe : Test.Program::Main][offset 0x00000004][found


Native Int][expected unmanaged pointer] Unexpected type on the stack.
[IL]: Error: [C:\Test\bin\Debug\Test.exe : Test.Program::Main][offset 0x00000005]
Unmanaged pointers are not a verifiable type.
2 Errors Verifying Program.exe

Application Domains:

Application domain is a very vast and important topic and couple of paragraphs certainly
does not do any justice to this.
In this article, I’ll try to cover what is absolutely required for a developer to know and not
any exhaustive or advanced functionality.

Disclaimers apart, let us look at application domains.

Isolating code to avoid any adverse affects on an application is not something new to
.Net. Operating System isolates the code into processes to ensure any adverse affects to
the operating system as a whole. That’s why most of the time, only the application
crashes instead of the operating system itself.

Application domains are created inside a managed process by the CLR to create isolation
within the process with respect to scope, security and memory. AppDomains are used for
communication between two separate applications or between different parts of the same
application. A single application can host multiple appdomains and code in one
appdomain needs a specific approach to communicate another appdomain even if both
the appdomains are part of the same process.

Infact, CLR creates atleast one AppDomain for all the managed processes. This
appdomain is called default appdomain and this cannot be unloaded before the processes
exits. Hence, it is always a good approach to create a separate appdomain to have more
control over the appdomain.

Now, let us see how an appdomain is related to security. Suppose, you have an assembly
that has permissions to manipulate the active directory and you do not want any
malicious users to access the assembly. This seems to be a straight forward situation. You
can provide permissions to the application level instead of assemble level. Now let us
make things little more complex. If some user creates another application which accesses
the assembly that is already loaded in the original process, then this will get hold of the
restricted assembly. This can be handled multiple ways like having code level checks or
using code based security (to be discussed in the next part) or have this assembly loaded
into a separate appdomain and provide stringent security to this isolation.

Let us now look at a simple example to demonstrate how to create and use appdomains:

//This code uses System.Security.policy

//Set up the Evidence


Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence( baseEvidence );
evidence.AddAssembly( "SecureAssembly.dll" );

// Create the AppDomain


AppDomain adsDomain = AppDomain.CreateDomain( "ADSDomain", evidence );

//To execute the assembly inside the appdomain


adsDomain.ExecuteAssembly ( "TestApp.exe", evidence );

All the code inside the SecureAssembly.dll can be accessed from the TestApp.exe using
the normal programming model.

Garbage collector does not automatically clean up the resources related to the
appdomains. Hence, it is recommended to unload all the resources held by that
appdomain through the program once they are no more required for your application.

AppDomain adsDomain = AppDomain.CreateDomain( "ADSDomain", evidence );




// unload the appdomain
AppDomain.Unload( adsDomain );

Stack Walks:

Untrusted code is one of the major security issues with the previous programming
environments. This often leads to the unauthorized access to the privileged resources that
your application has access to. To avoid such scenarios .Net introduced a concept called
walking the call stack (A.K.A Stack Walks). Stack walks ensure that the calling code has
the required permissions to access the resource. Moreover, the entire call stack will be
checked for the permissions instead of the end points only.

So, if you develop an assembly that has a method to manipulate active directory, and your
application is given required permission to access the active directory, you can
manipulate the active directory. If some malicious user creates another application and
uses your method in that assembly to manipulate the active directory, CLR checks for the
permission for that application to see if that application can access the active directory. If
not, then CLR throws a SecurityException.

At any point, the stack maintains the exact record of the sequence of method calls from
the top level code that requested the action to the actual method which executes the code.
To facilitate different situations, .Net provides a set of Security actions that can be
performed against the call stack.

The following are some of the most common Security actions:

Demand: invokes a full stack walk and checks if a Demand permission has been specified
for the caller or not. If the caller does not have the permission set, a SecurityException is
thrown.
Assert: can used to stop the stack walk to check for the required permission without
throwing any exception. CLR will not check for any callers above the stack from where
Assert action happens.
Deny: can be used to prevent any access to the resource. To remove an active deny, you
should call either RevertDeny or RevertAll functions
PermitOnly: can be used to ensure that only the specified resources can access the
resource
LinkDemand: occurs at the JIT stage unlike other actions that happen at the run time.
LinkDemand demands a shallow check, so only the next caller in the stack will be
checked for the permission.
InheritanceDemand: occurs at the JIT compilation stage like LinkDemand.
InheritanceDemand also demands a shallow check. However, this is specified for a class
instead of a method and hence, this should be used to ensure that only authorized code
can inherit from the class.

Let us look at a sample code that illustrates the usage:

[FileIOPermission(SecurityAction.Demand, Write = “C:\\error.log”]


Public void Log ()
{

}
Strong Name:

Everything we have dealt so far is to ensure that our code is executed by the authorized
programs only. But, if some malicious user changes the code altogether (by reverse
engineering the code, modifying it and compiling it back), nothing else will work.

To avoid such situations, .Net enables the developers to use public/private key to secure
the assembly. All the assemblies that have strong name attached will have a checksum
that ensures that the code is intact and is not replaced by anybody except for the original
author.

To know more about strong names and how to use them, please refer to MSDN.

Summary

Security is a must for all the developers to know and use in their applications. No
application is too small for attacking. This is more so important if your application
involves critical information sharing.
Type-Safe code. What and why?

This article explains what is type-safety and why is it important to understand this...
Author: Sidhartha Gundavarapu

Microsoft

Posted Date: 03 Nov, 2006


.NET Classes used :

Introduction

Before going any further, let us first have a look at what is type safe code and why is it
relevant to secure programming.

Type safety is certainly one of the most confusing aspects for somebody learning .Net.
When .Net was released, it had a tag attached claiming that the programs developed in
.Net are more stable when compared to programs developed using VB or VC++. This just
adds to the confusion if you do not understand type safety very well.

Type safety

Type safe code can access only the memory locations that it has permission to execute.
Type safe code can never access any private members of an object. Type safe code
ensures that objects are isolated from each other and are therefore safe for inadvertent or
malicious corruption.
CLR performs a mandatory type safety check, called verification, during JIT compilation.
This is done by a tool called peverify.exe, which examines the Microsoft Intermediate
Language and the metadata included in the assembly. If an assembly (or code) is
successfully verified as type safe, it is called verifiably type safe code.
The code is said to be verifiably type safe when any references to the types inside that
code are strictly compatible with the types they are referring to.

Code need no always be verifiably type safe. This is for the situations where you have
both managed as well as un-safe code in the same assembly. Remember, un-safe code
need no always be un-verifiable code.

Though this is a mandatory process performed by the CLR, it can be skipped by


providing necessary permissions to that assembly

CLR ensures that the type safe code does not end up in any undesirable situations like
calling native or unmanaged code or performing any malicious operations.

Example:

Usage of PEVerify.exe:

C:\>PEverify.exe
Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

Usage: PEverify <image file> [Options]

Options:
/IL Verify only the PE structure and IL
/MD Verify only the PE structure and MetaData
/UNIQUE Disregard repeating error codes
/HRESULT Display error codes in hex format
/CLOCK Measure and report verification times
/IGNORE=[,...] Ignore specified error codes
/IGNORE=@<file name> Ignore error codes specified in <file name>
/QUIET Display only file and Status. Do not display all errors.
/VERBOSE Display additional info in IL verification error messages.
/NOLOGO Don't display product version and copyright info.

Note: By default, MD is verified and then if there were no errors, IL is


verified. If /MD /IL options are specified, IL is verified even if
there were MD verification errors.

Example:
C:\Test\bin\Debug>peverify Test.exe
Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

All Classes and Methods in test.exe Verified.

Code Sample:
//This code fails the verification
unsafe
{
int* ptr = (int*) 0;
*ptr = 1000;
}

C:\>peverify C:\Test\bin\Debug\Test.exe

Microsoft (R) .NET Framework PE Verifier. Version 2.0.50727.42


Copyright (c) Microsoft Corporation. All rights reserved.

[IL]: Error: [C:\Test\bin\Debug\Test.exe : Test.Program::Main][offset 0x00000004][found


Native Int][expected unmanaged pointer] Unexpected type on the stack.
[IL]: Error: [C:\Test\bin\Debug\Test.exe : Test.Program::Main][offset 0x00000005]
Unmanaged pointers are not a verifiable type.
2 Errors Verifying Program.exe

Summary

Type safety is a simple concept and it will help the developers in developing better
applications if they understand this concept well.

Please get back to me for any additional information/suggestions/clarifications/short


comings regarding this topic
Boxing & Unboxing internals

How CLR boxes value types to reference types... In short, Why is boxing required?
Author: Sidhartha Gundavarapu

Microsoft

Posted Date: 26 Aug, 2006


.NET Classes used :

Introduction
As you might already know, Boxing is the process of converting value types to reference
types. But is this information enough to understand boxing? Lets look at a more closer
detail on boxing.

DISCLAIMER: This is the internals of memory management and not on how CLR boxes
values to references. So, please dont mistake that CLR does exactly the same thing
internally.

Value types and reference types

To understand boxing, we have to know the details of value types and reference types.

Value types are store on stack (as you already know) ad reference types reside on heap
(you know this one aswell). Now, lets go into more detail about value types and reference
types...

The structure of an object contains three layers,

1. sync headers (4 bytes)


2. vtable pointer (4 bytes)
3. actual data (size depends on the data)

and when we create an object, these three will be created logically and thus will be
recognised as a reference type.

-> Sync header is used for synchronization of the object in case of multhi-threading
-> a virtual table pointer which will store the address location of the virtual table that
stores the method pointers to the instance and static members of the class.

In case of value type, we do not have the sync headers and no reference header
information, hence are the value types.

Boxing

When we have to convert a value type to a reference type, we basically have to recreate
the structure of the object in the heap for the existing value type structure.

Though this seems to be simple looking at the structures, it involves fair bit of complexity
(keeping in view the architecture of stack and heap). Hence boxing is a costly affair

This process is called boxing!!!

Un Boxing

Un-Boxing is fairly simple when compared to boxing, but not simple enough to discard
the performance impact.
Hi all,

Its very urgent. i want to highlight the row and its corresponding column on mouse over.

Thanking in advance
smita

private void DataGrid2_ItemCreated(object sender,


System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string s = "javascript: highlightRow(" + e.Item.ItemIndex + ");";
e.Item.Attributes.Add("onmouseover", s);

In javascript

<script language="javascript">
function highlightRow(id)
{
var i = id+ 1;

var dt = document.getElementById("Datagrid2");
for(var j = 1; j < dt.rows.length; j++)
{
var row = dt.rows[j];

if(j == i)
{
row.style.backgroundColor = "gray";
}
else
{
row.style.backgroundColor = "white";
}
}
}
</script>

Sending emails from ASP.NET with attachment

This sample code shows how to send an email with an attachment.


Imports System.Web.Mail
Public Class WebForm2
Inherits System.Web.UI.Page

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub

Private Sub Send_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Search.Click
Dim MSg As New MailMessage
Dim mAtt As MailAttachment

mAtt = New MailAttachment("C:\mail.txt")


MSg.From = "pcranjithindia@gmail.com "
MSg.To = "pcrkidia@yahoo.co.in"
MSg.Subject = " From Ranjith "
MSg.Body = "Please see the attachment"

MSg.Attachments.Add(mAtt)

SmtpMail.Send(MSg)

Response.Write(" Done")
End Sub
End Class

Introduction

In the Object Oriented Programming , we always heard a term encapsulation.


Encapsulation or data hiding is the very important topic in OOP. encapsulation means to
wrapping up the data and methods into single unit. Now the question is that how can we
achieved the encapsulation in C#.

C# provides accessor methods (get and set methods) which are used to achieve the
encapsulation in the C#.

Let's look the class that will represent the user's login name, password and so on.

public class LogInToken { public string Name; public string


Password; }

The Name and Password


values are completely accessible by anyone using this class file. Following the rules of
encapsulation, we can hide the data by making the access modifier private:

public class LogInToken { private string Name; private string


Password; }

nOW, we need to provide a public exposed method that will allow access to the
Name and Password. These are called accessor methods, or setters and getters.

There are two ways of encapsulating or hiding the data.

1. CREATING METHODS TO HIDE DATA

See the GetName() and GetPassword() methods which are used to access these private
members.
public string GetName() { return Name; } public string
GetPassword(){ return Password; }

For setting the values of name and password , we will use the setters like :

public void SetName (string newName) { Name = NewName; }


public void SetPassword (string newPassword) { if (Name == "mm")
Password = newPassword; else //
throw exception that password is invalid }

2. USING PROPERTIES TO HIDE DATA

The second way to control access to data within a class file is by using properties. Instead
of creating methods that start with Get or Set, you simply make the pseudo-method
“look” like the data.

public string Name { get { return name;


} set { name = value; // C#
uses the implicit parameter "value" } } public string Password
{ get { return
password; } set {
if (name == "mm") password =
value; else // throw an exception
here for invalid password } }

SUMMARY

Which method you use is a matter of personal preference.By creating GetPassword and
SetPassword methods as in the earlier examples, you are asking that the user of your
class become familiar with all the methods needed to access data. When you use
properties,
the user simply needs to know the property names and can treat them as data
instead of methods.

Thanks
Gaurav Sharma
How to create a context menu and attach it to a control?

This code sample shows how to create a context menu and attach to a control.

System.Windows.Forms.ContextMenu contextMenu1;
contextMenu1 = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem menuItem1;
menuItem1 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem2;
menuItem2 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem3;
menuItem3 = new System.Windows.Forms.MenuItem();

contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[]
{menuItem1, menuItem2, menuItem3});
menuItem1.Index = 0;
menuItem1.Text = "MenuItem1";
menuItem2.Index = 1;
menuItem2.Text = "MenuItem2";
menuItem3.Index = 2;
menuItem3.Text = "MenuItem3";

textBox1.ContextMenu = contextMenu1;
.NET Classes used :
System.Directoryservices
System.Data
System.Data.SQlClient

Introduction

The Process is goes like this

Login ---> Authenticate with active directory users --> Authenticate with Form based
authentication with database.-->

Application main page

Active Directory : Active Directory is an implementation of LDAP directory services by


Microsoft for use in Windows

environments. Active Directory allows administrators to assign enterprise-wide policies,


deploy programs to many computers,

and apply critical updates to an entire organization. An Active Directory stores


information and settings relating to an

organization in a central, organized, accessible database. Active Directory networks can


vary from a small installation with

a few hundred objects, to a large installation with millions of objects.

please ckeck this for more information about the

active directory.

Now i am giving you the step by step process of authentication.

sTEP 1:Configure IIS for anonymous authentication

1.

In the IIS Manager (in Administrative Tools) or the MMC snap-in for IIS, right-click
the Web site for which you want to

configure authentication, and then click Properties.


2.
Click the Directory Security tab, and then under Authentication and access control,
click Edit.
3.

Select the Anonymous Authentication check box (labeled Enable anonymous access in
Windows Server 2003).
4.

Make the anonymous account for the application an account that has permission to
Active Directory.
5.

Clear the Allow IIS To Control Password check box, if it is present. The default
IUSR_ account does not

have permission to the Active Directory.

step 2 :

Add a reference of System.DirectoryServices.To Add reference right click project then


select add reference than Visual Studio

opens a dialouge box then select the System.DirectoryServices after selecting check your
web config it will shows you this

< add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral,


PublicKeyToken=B03F5F7F11D50A3A"/>

under the .

it assures that the reference has been added to your application.

Come to your login page's code behind file then import System.DirectoryServices

Imports System.DirectoryServices

Step 3 :Write code in Web Config file for Form authentication


< authentication mode="Forms"> < forms path="/"
loginUrl="login.aspx" protection="All" timeout="30"> < /forms>
< /authentication>

To cope with active directory put this after above code < identity impersonate="true"/>

Step 4: Write a Funtion to authenticate the active directory users. This funtion accepts the
user name and password and

authenticate with Active Directory users.

Public Function IsAuthenticated(ByVal domain As String, ByVal username As String,


ByVal pwd As String) As Boolean Dim domainAndUsername As String = ""
domainAndUsername = domain & "\" & username Dim entry As New
DirectoryEntry("LDAP://DC=ABC,DC=local", domainAndUsername, pwd) Dim obj
As Object Try obj = entry.NativeObject Dim search As New
DirectorySearcher(entry) Dim result As SearchResult search.Filter =
"(SAMAccountName=" + username + ")" search.PropertiesToLoad.Add("cn")
result = search.FindOne() If result Is Nothing Then Return False
End If Catch ex As Exception Return False End Try Return True
End Function

for more information about LDAP click here

step 5 :

Write Function for form authentication with database user.


Function ValidateUsers(ByVal UserName As String, ByVal PassWord As String) As
Boolean---------------------------------------------'Write your database logic here and
authenticate with database users 'In This User name and password will authenticate with
your respective database tableEnd function

STEP 6 :

Call both functions


If ValidateUsers(DBusername, DBpassword) And IsAuthenticated("ABC.local",
"activeDirectoryUser", "Userpassword") Then
FormsAuthentication.RedirectFromLoginPage(name, False) lblError.Text = ""
Else lblError.Text = "Invalid User Name , Password or Division" End If

Summary

I hope this article will helps you to create more secure web applications
Thanks
Gaurav Sharma
Introduction:

Generics, no doubt, is one of the wonderful and refreshing feature introduced in


Microsoft .Net Framework 2.0. Generics can be used to produce a strictly type safe data
structures, thus providing enormous performance optimization. Introduction of generics
brought a near end to the use of boxing/unboxing to store types in data structures.

This article assumes C# 2.0 knowledge.

Syntax:
The syntax of using generics is:
//usage with classclass MyClass< T >{ ...}

//usage with methodvoid MyMethod< U >(){ ...}

Problems with Generics:

Let us consider the following example...

//this method returns if both the parameters are equalpublic static bool Equals< T >(T t1,
Tt2){ return (t1 == t2)}

Apparantly, this code is a very good usage of generics. This method can be used to
compare the equality of any two similar types. The problem here is that, the IL generated
to compare say an integer and a string is different. int comparision is just check the values
on the stack, whereas it is not as simple for string. so the IL generated for Equals<string>
would be different to that of Equals<int>.

The case may be even different if the types being compared has a new definition of ==
operator. Because of this you may not use the == operator to compare any generic object
references without having any type of restrictions/constraints on them.

Solution:

There are two possible solutions for this (that were bundled out of the box) with C#.
1. Runtime casting
2. Restricting the allowable types while declaring the generic type

Runtime casting (a.k.a yuck!), sometimes, can be a good fit here. In this, the CLR will
cast the types at the runtime dynamically and thus ensuring the similar functional
behavior through out the application. But, this certainly is not the best way always
especially not when the types being used are overriding the default behavior of the
operators (just an example) involved in the operation.

The best fit, for most of the cases would certainly be having some kind of restriction on
what types should be allowed to be replaced in the generic type. In .Net, they are called
constraints.

Constraints are represented in C# using the where keyword. The following is the syntax:

public bool Compare< T >(T t1, Tt2) where T : IComparable{ ...}

Some of the ways we can use constraints are as follows:

1. specifying the type to be a reference type


public void MyMethod< T >() where T : class{ ...}

please note that class is the keyword here and should be used in the same case. Any
difference in the case will lead to a compilation error

2. specifying the type to be a value type


public void MyMethod< T >() where T : struct{ ...}

please note that struct is the keyword here and should be used in the same case. Any
difference in the case will lead to a compilation error

3. specifying a constructor as a constraint


public void MyMethod< T >() where T : new (){ ...}

please note that only a default constructor can be used in the constraints and using any
parameterised constructor will be a compilation error.

4. specifying a static base class as a constraint


public void MyMethod< T >() where T : BaseClass{ ...}

5. specifying a generic base class as a constraint


public void MyMethod< T, U >() where T : U{ ...}

Points to ponder

Though this list seems to be insufficient considering the complex scenarios, these can be
mixed appropriately.

The below is a valid combination of constraints

public void MyMethod< T >() where T : IComparable, MyBaseClass, new (){


...}//here we are using multiple constraints. using IComparable and MyBaseClass would
be case 4, using new() would be case 3.

The below is an example for an invalid combination of constraints


public void MyMethod< T >() where T : class, struct{ ...}//here we are trying to
specify the generic type as both reference and value type.

Summary

Generics, are a wonderful feature to work with and should be used where ever
appropriate for better optimization of the applications.
.NET Classes used :

System.Directoryservices
System.Data
System.Data.SQlClient
Introduction

The Process is goes like this

Login ---> Authenticate with active directory users --> Authenticate with Form based
authentication with database.-->

Application main page

Active Directory : Active Directory is an implementation of LDAP directory services by


Microsoft for use in Windows

environments. Active Directory allows administrators to assign enterprise-wide policies,


deploy programs to many computers,

and apply critical updates to an entire organization. An Active Directory stores


information and settings relating to an

organization in a central, organized, accessible database. Active Directory networks can


vary from a small installation with

a few hundred objects, to a large installation with millions of objects.

please ckeck this for more information about the

active directory.

Now i am giving you the step by step process of authentication.

sTEP 1:Configure IIS for anonymous authentication

1.

In the IIS Manager (in Administrative Tools) or the MMC snap-in for IIS, right-click
the Web site for which you want to

configure authentication, and then click Properties.


2.

Click the Directory Security tab, and then under Authentication and access control,
click Edit.
3.
Select the Anonymous Authentication check box (labeled Enable anonymous access in
Windows Server 2003).
4.

Make the anonymous account for the application an account that has permission to
Active Directory.
5.

Clear the Allow IIS To Control Password check box, if it is present. The default
IUSR_ account does not

have permission to the Active Directory.

step 2 :

Add a reference of System.DirectoryServices.To Add reference right click project then


select add reference than Visual Studio

opens a dialouge box then select the System.DirectoryServices after selecting check your
web config it will shows you this

< add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral,


PublicKeyToken=B03F5F7F11D50A3A"/>

under the .

it assures that the reference has been added to your application.

Come to your login page's code behind file then import System.DirectoryServices

Imports System.DirectoryServices

Step 3 :Write code in Web Config file for Form authentication

< authentication mode="Forms"> < forms path="/"


loginUrl="login.aspx" protection="All" timeout="30"> < /forms>
< /authentication>

To cope with active directory put this after above code < identity impersonate="true"/>
Step 4: Write a Funtion to authenticate the active directory users. This funtion accepts the
user name and password and

authenticate with Active Directory users.

Public Function IsAuthenticated(ByVal domain As String, ByVal username As String,


ByVal pwd As String) As Boolean Dim domainAndUsername As String = ""
domainAndUsername = domain & "\" & username Dim entry As New
DirectoryEntry("LDAP://DC=ABC,DC=local", domainAndUsername, pwd) Dim obj
As Object Try obj = entry.NativeObject Dim search As New
DirectorySearcher(entry) Dim result As SearchResult search.Filter =
"(SAMAccountName=" + username + ")" search.PropertiesToLoad.Add("cn")
result = search.FindOne() If result Is Nothing Then Return False
End If Catch ex As Exception Return False End Try Return True
End Function

for more information about LDAP click here

step 5 :

Write Function for form authentication with database user.


Function ValidateUsers(ByVal UserName As String, ByVal PassWord As String) As
Boolean---------------------------------------------'Write your database logic here and
authenticate with database users 'In This User name and password will authenticate with
your respective database tableEnd function

STEP 6 :

Call both functions

If ValidateUsers(DBusername, DBpassword) And IsAuthenticated("ABC.local",


"activeDirectoryUser", "Userpassword") Then
FormsAuthentication.RedirectFromLoginPage(name, False) lblError.Text = ""
Else lblError.Text = "Invalid User Name , Password or Division" End If
Summary

I hope this article will helps you to create more secure web applications
Thanks
Gaurav Sharma

hi..i work on asp.net 2.0, c# and VS 2005.


i have a gridview which is bound to database thro sql connection string. the grid has 7
colums and displays around 350 records on load event. I have generated colums by
Asp:Boundfield.. Its working fine. The coding is...

DataSet _dataset = new DataSet();


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// BindDropItemCategory();
bindGridAll();

}
}

private void bindGridAll()


{
using (SqlConnection _conn = new SqlConnection(GetConnectionString()))
{
using (SqlCommand _command = new SqlCommand())
{
_conn.Open();
_command.Connection = _conn;
_command.CommandText = "select * from ItemInfoView where
ItemCategoryId=1 order
by ItemCategoryId";
using (SqlDataAdapter _adapter = new SqlDataAdapter())
{
_adapter.SelectCommand = _command;
_adapter.Fill(_dataset, "inventory");
}
}
}
grid_inventory.DataSource = _dataset.Tables["inventory"];
grid_inventory.DataBind();
}

i make the elements of the first colum as a link and on clicking that link a new popup will
open.

i generated the link thro java script . coding as follows.

<SCRIPT language ="JavaScript1.2">


function poponload(t)
{
var inp=t;
testwindow= window.open ("inventoryitem.aspx?p=" + inp,
"mywindow","location=1,status=1,scrollbars=1,width=450,height=350");
testwindow.moveTo(0,0);
}

</SCRIPT>

and in the gridview row event i have coding as...

protected void grid_inventory_RowDataBound(object sender, GridViewRowEventArgs


e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string _link = e.Row.Cells[0].Text;
int _index = e.Row.DataItemIndex;
string _indexkey = grid_inventory.DataKeys[_index].Values.ToString();
e.Row.Cells[0].Text = "<a href='javascript:poponload(" + _indexkey + ");'>" +
_link + "</a>";

}
}

till here no pblm....

if i go for page index changing i get pblm ..the coding is...

protected void grid_inventorypageindexchange(object sender,GridViewPageEventArgs e)


{

grid_inventory.PageIndex = e.NewPageIndex;
bindGridAll();
}
i have set the page size as 15. if i click next page the exception as

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

The exception is displayed in gridwiewrow event.

pls can any one guid me to solve this....

Answers .............

Submit Answer ... get surprise gifts and you can participate in Google AdSense
Revenue Sharing Program
--------------------------------------------------------------------------------
18 Dec 07 05:19 AM : amisha : Satyam Computers
either
int _index = e.Row.DataItemIndex - 1;
or put
string _indexkey = grid_inventory.DataKeys[_index].Values.ToString();
thn it wont throw error

18 Dec 07 05:20 AM : Rajaraman : CTS,Hyderabad


http://www.cognizant.com
Go through this.

http://forums.asp.net/p/1139250/1838215.aspx
Code Sample Category: C# Syntax
Language: C#
Author: Md Zafar Imam

Mindtree Consulting Ltd


Posted Date: 02 Mar, 2007
Import Namespaces :

using System.Windows.Forms .NET Classes used :

System.Windows.Forms.Application

Creating singleton class in C#

Singleton class is one from which we wan instantiate only one object. For creating
singleton class, we have to make the constructor as private and provide a special method
to instantiate the class. In this code sample, the method GetProgram() will create the
instance if it does nto exist and return the instance.

public class Program


{
private static Program m_Program = null;
private frmInputForm m_inputForm;

private Program()
{
m_inputForm = new frmInputForm();
}

public static Program GetProgram()


{
if (m_Program == null)
{
m_Program = new Program();
}
return m_Program;
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(GetProgram().GetInputForm());
}
public frmInputForm GetInputForm()
{
return m_inputForm;
}
}
Code Sample Category: Collections
Language: C#
Author: santosh narayan poojari

Infrasoft Technology ltd

Posted Date: 08 May, 2007


Import Namespaces :

using System.Collections .NET Classes used :

System.Collections.Generic

Anonymous Methods in C#

Anonymous Method of C#2.0 can ease Sorting operation in Ascending / Descending


order on Generic collection List. One can avoid tedious use of implementing
IComparable / IComparer for List. This sample code shows how to use Anonymous
methdos in C#.

protected void Page_Load(object sender, EventArgs e)


{
List<Customer> customerList = new List<Customer>();
customerList.Add(new Customer(01111, "Santosh"));
customerList.Add(new Customer(01112, "Narayan"));
customerList.Add(new Customer(01113, "Poojari"));
customerList.Sort(
delegate(Customer lhs, Customer rhs) {
return lhs.CustomerID.CompareTo(rhs.CustomerID);
//OR return rhs.CustomerID.CompareTo(lhs.CustomerID);
});
//one can use customerList.Reverse() to reverse the sort order
foreach (Customer customer in customerList)
Response.Write(customer.CustomerID+"<br>");
}
public class Customer
{
private int m_CustomerID = int.MinValue;
private string m_CustomerName = string.Empty;
public Customer(int customerId,string customerName)
{
this.m_CustomerID = customerId;
this.m_CustomerName = customerName;
}
public int CustomerID
{
get { return m_CustomerID; }
set { m_CustomerID = value; }
}
public string CustomerName
{
get { return m_CustomerName; }
set { m_CustomerName = value; }
}
}
Code Sample Category: Event Handling
Language: C#
Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 07 Mar, 2007


Import Namespaces :

using System.Windows.Forms;
using System.Collections.Generic .NET Classes used :

System.Windows.Forms.Form
System.Windows.Forms.MessageBox
System.Windows.Forms.MessageBoxButtons
System.Collections.Generic.Dictionary

Creating and invoking custom events

Events are used to handle the situations dynamically. Let say almost in all the windows
application we are using button control, and the click event of it. Actually the click is
happening in the button control, but user [we] able to handle the click event in form. The
same way we can use the events for our own controls, business objects etc.

Example:
Class “Store” is used to add and delete the items. Also the class has the event called
“OnDelete”, which is used to handle something before the delete operation. The user of
the “Store” class can write his codes required to execute before the delete operation.

In this example I have handled the OnDelete event to show the warning message while
deleting.

// Declare a delegate for the event handler.


public delegate void StoreEventHandler(string itemName,ref bool action);

public class Store


{
// Declare an event handler
public event StoreEventHandler OnDelete;

private Dictionary<int, string> ItemList = new Dictionary<int, string>();

public void Add(int Id,string Name)


{
ItemList.Add(Id,Name);
}

public void Delete(int Id)


{
bool canDelete=false;

//fire the on delete event[s]


OnDelete(ItemList[Id], ref canDelete);

if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}

How to use the Store object in your application:

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
Store myStore = new Store();
myStore.OnDelete += new StoreEventHandler(myStore_OnDelete);

myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");

myStore.Delete(2);
}

void myStore_OnDelete(string itemName, ref bool action)


{
DialogResult r = MessageBox.Show("Are you sure you want to delete item
'"+itemName+"' from the store","Confirm Item Delete", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
action = true;
}
else
{
action = false;
}
}
}
Code Sample Category: C# Syntax
Language: C#
Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 12 Mar, 2007


Import Namespaces :
using System.IO;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

System.IO.StreamWriter
System.Windows.Forms.Form
System.Windows.Forms.MessageBox

Creating and using static constructors

Static constructors are used to initialize the static Filed and properties, the user can’t call
this constructor manually, this will get invoke before the first object created for the class
[or] before accessing the static fields.

Here’s the simple example for the static contractors, I have created the
“MyEventLogManager” class with static constructor, which is used to log the project
events to the file.

Implementing “MyEventLogManager” with static constructor

public class MyEventLogManager


{
private static System.IO.StreamWriter sw;

//Static constructor
static MyEventLogManager()
{
//Intiating the stream writer
MessageBox.Show("Static constructor invoked..");
sw = new System.IO.StreamWriter("C:\\project.log",true);
}

public static void LogEvent(string message)


{
//Writing event message into file
sw.WriteLine(DateTime.Now.ToLongTimeString()+":"+message);
}

public static void SaveEventLog()


{
//Close the stream
sw.Close();
}

Testing the “MyEventLogManager

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
MyEventLogManager.LogEvent("Login Successfull[Admin user]");
MyEventLogManager.LogEvent("Item Added to Database");
MyEventLogManager.LogEvent("Item Deleted from Database");
MyEventLogManager.SaveEventLog();
}
}

Code Sample Category:


C# Syntax
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 12 Mar, 2007


Import Namespaces :

using System.IO;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.IO.StreamWriter
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox
Creating and using static constructors

Static constructors are used to initialize the static Filed and properties, the user can’t call
this constructor manually, this will get invoke before the first object created for the class
[or] before accessing the static fields.

Here’s the simple example for the static contractors, I have created the
“MyEventLogManager” class with static constructor, which is used to log the project
events to the file.

Implementing “MyEventLogManager” with static constructor

public class MyEventLogManager


{
private static System.IO.StreamWriter sw;

//Static constructor
static MyEventLogManager()
{
//Intiating the stream writer
MessageBox.Show("Static constructor invoked..");
sw = new System.IO.StreamWriter("C:\\project.log",true);
}

public static void LogEvent(string message)


{
//Writing event message into file
sw.WriteLine(DateTime.Now.ToLongTimeString()+":"+message);
}

public static void SaveEventLog()


{
//Close the stream
sw.Close();
}

Testing the “MyEventLogManager

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
MyEventLogManager.LogEvent("Login Successfull[Admin user]");
MyEventLogManager.LogEvent("Item Added to Database");
MyEventLogManager.LogEvent("Item Deleted from Database");
MyEventLogManager.SaveEventLog();
}

}
Code Sample Category:
Exceptions
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 12 Mar, 2007


Import Namespaces :

using System;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.Exception
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox

Creating custom exceptions

Exceptions are very use full while developing high level applications; normally we are
using the try catch block to catch the exceptions thrown by the .net frame work. As the
same way we can create/handle our own exceptions.

Rule: All types of exceptions must derive from “System.Exception” class.

Here’s the simple example. I have created a exception class named


“InvalidUserException” which I am invoking when the current user is not valid to access
the application.
Creating custom exception, by inheriting the “System.Exception”

//Creating own exception by inheriting the Exception class


public class InvalidUserException:Exception
{
public override string Message
{
get
{
return "Invalid User";
}
}
}

Implementing the “LoginManager” class, which is used to validate the current user

public class LoginManager


{
//Instead of hard coded values you can add logic to retrive from the database
public string ValidUserName="Admin";
public string ValidPassword="AdminPass";

public bool ValidateUser(string userName,string password)


{
if (ValidUserName == userName && ValidPassword == password)
{
//Login successful
return true;
}
{
//Login Failed
throw new InvalidUserException();
}
}
}

Testing the implementation

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
LoginManager lm = new LoginManager();

string currentLoginName = textBox1.Text;


string currentLoginPassword = textBox2.Text;
try
{
if (lm.ValidateUser(currentLoginName, currentLoginPassword))
{
//User is valid,Open next form
MessageBox.Show("Login Success");
}
}
//Catching the custom exception
catch (InvalidUserException ex)
{
MessageBox.Show(ex.Message, "Login Faild", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);

//Resets the input elements


textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
}

}
Code Sample Category:
Automation
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG
Posted Date: 08 Mar, 2007
Import Namespaces :

using System.Globalization;
using System.Reflection;
using System .NET Classes used :

# System.Globalization.CultureInfo
# System.Reflection.Missing
# System.Reflection.BindingFlags
# System.Activator
# System.Type
# System.object

Open and print Excel document programmatically using late binding technique

Opening and using an assembly during runtime is called late binding. This is very help
full to play with multiple versions of office application. For example if want to print a
excel document from the windows application, normally we add a reference of the excel
dlls or PIA to our application, but the same thing will fail if the target machine has the
older versions of the dlls. To avoid this version problem we can use the late binding logic,
because here we are not referring any dlls during the development time, we are referring
only at the runtime with the program id.

After creating the instance of the excel application, we can use the reflection concept to
invoke its methods.

I have done a sample late binding code below. Here I am opening, printing and closing
the excel document.

The following class is used to open,print and close the Excel document

public class MSExcel


{
Type ExcelType;
object ExcelApplication;
public object oBook;

public MSExcel()
{
//Gets the type of the Excel application using prorame id
ExcelType = Type.GetTypeFromProgID("Excel.Application");

//Creating Excel application instance from the type


//Check the running processes using alt+ctrl+del
ExcelApplication = Activator.CreateInstance(ExcelType);
}
public void Open(string strFileName)
{
object fileName = strFileName;
object readOnly = true;
object missing = System.Reflection.Missing.Value;
object[] oParams = new object[1];

//Getting the WoorkBook collection [work Sheet collection]


object oDocs = ExcelApplication.GetType().InvokeMember("Workbooks",
System.Reflection.BindingFlags.GetProperty,
null,
ExcelApplication,
null, CultureInfo.InvariantCulture);
oParams = new object[3];
oParams[0] = fileName;
oParams[1] = missing;
oParams[2] = readOnly;

//Open the first work sheet


oBook = oDocs.GetType().InvokeMember("Open",
System.Reflection.BindingFlags.InvokeMethod,
null,
oDocs,
oParams, CultureInfo.InvariantCulture);

}
public void Close()
{
//Closing the work sheet
oBook.GetType().InvokeMember("Close",
System.Reflection.BindingFlags.InvokeMethod,
null,
oBook,
null, CultureInfo.InvariantCulture);
}
public void Print()
{
//Printing the sheet
oBook.GetType().InvokeMember("PrintOut",
System.Reflection.BindingFlags.InvokeMethod,
null,
oBook,
null, CultureInfo.InvariantCulture);
}
public void Quit()
{
//Close the Excel application block
//Check the running processes using alt+ctrl+del
ExcelApplication.GetType().InvokeMember("Quit",
System.Reflection.BindingFlags.InvokeMethod,
null,
ExcelApplication,
null, CultureInfo.InvariantCulture);
}
}

Testing the MSExcel class

Public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
MSExcel excel = new MSExcel();

//Note: Give the vaild path


excel.Open("C:\\TestBook.xls");
excel.Print();
excel.Close();
excel.Quit();
}
}
Code Sample Category:
Reflection
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 08 Mar, 2007


Import Namespaces :

using System;
using System.Windows.Forms;
using System .NET Classes used :

# System.Attribute
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox
# System.Exception

Creating and using Attributes

Attributes are used to describe the element; basically it’s a configuration element. For
example while doing the XML serialization we can control the XML output with the help
of attributes. We can configure the property like XMLElement or an XMLAttribute,
according to this attributes serialization will happen.

Here’s a simple scenario, using attributes I have implemented the Method level security.

The class “Store” has 3 methods AddItem, DeleteItem, GetItem. Only the respective user
can access the methods, if any other peoples try to call these methods it will throw an
exception.

Methods Allowed Roles


----------------------------------------
AddItem Manager
DeleteItem Manager, StoreRoomStaff
GetItem All roles

I have created following Attribute class which is inherited from “Attribute” class

public class AllowedRoles:Attribute


{
public string[] Roles;
public AllowedRoles(string[] roleIds)
{
Roles = roleIds;
}
}

The following “Store” class methods have the “AllowedRoles” attributes, with the role
name parameters.

public class Store


{
[AllowedRoles(new string[] { "Manager" })]
public void AddItem(object Item)
{
//Add item to datastore
MessageBox.Show("Item Added sucessfully");
}

[AllowedRoles(new string[] { "Manager", "StoreRoomStaff" })]


public void DeleteItem(int ItemId)
{
//Delete item from datastore
MessageBox.Show("Item Deleted sucessfully");
}

//no Secrity attributes avilable, so its accessable for all the roles
public void GetItem(object Item)
{
//Get Item From the datastore
MessageBox.Show("Item Added sucessfully");
}
}

The following “SecurityManager” class is used to check the current user has the
permission to access the specified method or not. If not it will throw an exception.

public class SecurityManager


{
public static bool IsAllowedForTheRole(Type Class, string methodName, string
RoleId)
{
MethodInfo mi = Class.GetMethod(methodName);
AllowedRoles r = mi.GetCustomAttributes(typeof(AllowedRoles), true)[0] as
AllowedRoles;
if (r == null)
{
return true;
}
else
{
foreach (string role in r.Roles)
{
if (role == RoleId)
{
return true;
}
}

throw new Exception("User not allowed to perform this operation");


}
}
}

Testing the “AllowedRoles” attributes and the “SecurityManager”

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
string currentRole = string.Empty;
Store obj = new Store();

//Setting the role


currentRole = "Manager";

//Check the access rigths using the SecurityManager


if (SecurityManager.IsAllowedForTheRole(typeof(Store), "AddItem", currentRole))
{
obj.AddItem("Milk");
}

currentRole = "StoreRoomStaff";
if (SecurityManager.IsAllowedForTheRole(typeof(Store), "DeleteItem",
currentRole))
{
obj.DeleteItem(1);
}

try
{
//note: StoreRoomStaff does not have the rights to delete a Item
currentRole = "StoreRoomStaff";
if (SecurityManager.IsAllowedForTheRole(typeof(Store), "AddItem",
currentRole))
{
obj.AddItem("Biscuts");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Code Sample Category:
Reflection
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 08 Mar, 2007


Import Namespaces :

using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.Reflection.MethodBody
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox

Counting the number of local variables used in an method

Here's a simple example of Reflection which is used to identify the local variables used in
a method. MethodBody class is used to access the method code body entities, using this
class we can analyze the method code blocks.

Following ‘score’ class has ‘CalculateTotal’ method, the one which we are going to
analyze

public class Score


{
private int m_Score1;
public int Score1
{
get { return m_Score1; }
set { m_Score1 = value; }
}
private int m_Score2;
public int Score2
{
get { return m_Score2; }
set { m_Score2 = value; }
}

private int m_Score3;


public int Score3
{
get { return m_Score3; }
set { m_Score3 = value; }
}
public void CalculateTotal()
{
int total, average;
total = Score1 + Score2 + Score3;
average = total / 3;
MessageBox.Show("Total Score:" + total + "\nAverage:" + average);
}
}

Counting the local variables declared in the ‘CalculateTotal’ Method

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
Score obj = new Score();
obj.Score1 = 70;
obj.Score2 = 80;
obj.Score3 = 60;

// Getting the methdinfo


MethodInfo mi = obj.GetType().GetMethod("CalculateTotal");

// Getting the methodBody


MethodBody mb = mi.GetMethodBody();
// Displaying the count of variable used in the 'CalculateTotal' Method
MessageBox.Show(mb.LocalVariables.Count.ToString());

foreach (LocalVariableInfo lvi in mb.LocalVariables)


{
// Displaying the variable information
MessageBox.Show(lvi.ToString());
}
}
Code Sample Category:
Reflection
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 07 Mar, 2007


Import Namespaces :

using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.Reflection.MethodInfo
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox

Invoke methods dynamically using reflection

Here's a simple example of Reflection which is used to invoke the method of an instance.
MethodInfo class is used to access the specific method of the instance, using this class we
can invoke the methods even if it has parameters. This is very help full when you are
using late binding.

The following class has number of methods which we are going to invoke using
reflection

public class AirCraft


{
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}

private int m_Speed;

public int Speed


{
get { return m_Speed; }
set { m_Speed = value; }
}

public void ShowName()


{
MessageBox.Show("Aircraft name is " + Name);
}

public void StartFly()


{
MessageBox.Show(Name+" Is Flying...(Speed:"+Speed+" km/h)");
}

public void StopFly()


{
MessageBox.Show(Name+" Landed Safely");
}
}

implemeting the reflection concept to invoke the method of an instance

public class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
AirCraft obj = new AirCraft();
obj.Name = "Black Bird";
obj.Speed = 1000;
InvokeMethod(obj, "ShowName");
InvokeMethod(obj, "StartFly");
InvokeMethod(obj, "StopFly");
}
private void InvokeMethod(object instance,string methodName)
{
//Getting the method information using the method info class
MethodInfo mi = instance.GetType().GetMethod(methodName);

//invoing the method


//null- no parameter for the function [or] we can pass the array of parameters
mi.Invoke(instance, null);
}
}
Code Sample Category:
Reflection
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 07 Mar, 2007


Import Namespaces :

using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.Reflection.PropertyInfo
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox

Accessing all the properties of an instance using reflection

Here's a simple example of Reflection which is used to read the all properties from an
instance. PropertyInfo class is used to access the specific property of the instance, using
this we can get or set the value for the instance. It is very use full when you don’t know
the type of the instance.

public class Student


{
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}

private int m_Id;


public int Id
{
get { return m_Id; }
set { m_Id = value; }
}

private int m_Age;


public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
}

The bellow code is used to access the properties of the Studnet class

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
Student obj = new Student();
obj.Name = "Jax";
obj.Id = 1298;
obj.Age = 23;
ReadAllTheProperties(obj);
}

public void ReadAllTheProperties(object obj)


{
//Getting all the properties into an array
PropertyInfo[] propInfo = obj.GetType().GetProperties();

//Looping the array


foreach (PropertyInfo pi in propInfo)
{
string value = string.Empty;
string name = string.Empty;
name = pi.Name;
value = pi.GetValue(obj, null).ToString();
MessageBox.Show(name + "=" + value);
}
}

}
Code Sample Category:
Event Handling
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 07 Mar, 2007


Import Namespaces :

using System.Windows.Forms;
using System.Collections.Generic .NET Classes used :

# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox
# System.Windows.Forms.MessageBoxButtons
# System.Collections.Generic.Dictionary

Creating and invoking custom events

Events are used to handle the situations dynamically. Let say almost in all the windows
application we are using button control, and the click event of it. Actually the click is
happening in the button control, but user [we] able to handle the click event in form. The
same way we can use the events for our own controls, business objects etc.

Example:
Class “Store” is used to add and delete the items. Also the class has the event called
“OnDelete”, which is used to handle something before the delete operation. The user of
the “Store” class can write his codes required to execute before the delete operation.

In this example I have handled the OnDelete event to show the warning message while
deleting.
// Declare a delegate for the event handler.
public delegate void StoreEventHandler(string itemName,ref bool action);

public class Store


{
// Declare an event handler
public event StoreEventHandler OnDelete;

private Dictionary<int, string> ItemList = new Dictionary<int, string>();

public void Add(int Id,string Name)


{
ItemList.Add(Id,Name);
}

public void Delete(int Id)


{
bool canDelete=false;

//fire the on delete event[s]


OnDelete(ItemList[Id], ref canDelete);

if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}

How to use the Store object in your application:

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
Store myStore = new Store();
myStore.OnDelete += new StoreEventHandler(myStore_OnDelete);

myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");

myStore.Delete(2);
}

void myStore_OnDelete(string itemName, ref bool action)


{
DialogResult r = MessageBox.Show("Are you sure you want to delete item
'"+itemName+"' from the store","Confirm Item Delete", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
action = true;
}
else
{
action = false;
}
}
}
Code Sample Category:
C# Syntax
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 07 Mar, 2007


Import Namespaces :

using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :

# System.Windows.Forms.Form
# System.Windows.Forms.Button

Implementing Anonyms functions in c# [.net 2.0]

Anonym’s functions are used to build dynamic handlers for the event or for the delegates.
The following code explains to create dynamic handler for the button click event.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
Button b1 = new Button();
b1.Text = "invoke anonyms method";
b1.Width = 200;
this.Controls.Add(b1);

//Mapping Anonyms function to the button click event


b1.Click += delegate(object obj, EventArgs eventArgs)
{
MessageBox.Show("Button Click handled from Anonyms method");
};
}
}
Code Sample Category:
Winforms Controls
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 06 Mar, 2007


Import Namespaces :

using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel .NET Classes used :

# System.Windows.Forms.Panel
# System.Drawing.Color
# System.Drawing.Graphics
# System.Drawing.Rectangle
# System.Drawing.Pen
# System.Drawing.Drawing2D.LinearGradientBrush
# System.ComponentModel.IContainer

Creating Panel control with Gradient colors

OnPaint method is responsible to render all types of controls .net, it’s a virtual method we
can add our extra codes by overriding this method. In this example I have added the code
to display the gradient colored rectangle.

Here I have created the component from the Panel control (derived from
System.windows.forms.panel)

Implementing the component

public partial class GradientColoredPanel : Panel


{
Pen p = new Pen(Color.Black);

//Setting the default value for start color of the panel


Color _GradientStartColor = Color.SkyBlue;
public Color GradientStartColor
{
get { return _GradientStartColor; }
set { _GradientStartColor = value; }
}

//Setting the default value for end color of the panel


Color _GradientEndColor = Color.Blue;
public Color GradientEndColor
{
get { return _GradientEndColor; }
set { _GradientEndColor = value; }
}

LinearGradientMode _GradientFillMode = LinearGradientMode.Horizontal;


public LinearGradientMode GradientFillMode
{
get { return _GradientFillMode; }
set { _GradientFillMode = value; }
}

protected override void OnPaint(PaintEventArgs e)


{
//Getting the graphics object of the panel
Graphics g = e.Graphics;
Rectangle r = new Rectangle(0, 0, this.Width, this.Height);

//Filling the rectangle with LinearGradientBrush


LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush(r,
GradientStartColor,
GradientEndColor, GradientFillMode);
g.FillRectangle(myLinearGradientBrush, r);

base.OnPaint(e);
}
}

Using the GradientColoredPanel in form

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
//Creating new instance for GradientColoredPanel component
GradientColoredPanel myPanel = new GradientColoredPanel();

//Setting the start and end color


myPanel.GradientStartColor = Color.Red;
myPanel.GradientEndColor = Color.Pink;

//Color fill mode


myPanel.GradientFillMode = LinearGradientMode.Vertical;
myPanel.Width = 300;
myPanel.Height = 300;

//Adding the control to form(or you can drag and drop from the tools menu)
this.Controls.Add(myPanel);

}
Code Sample Category:
Operating System
Language:
C#

Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 27 Mar, 2007


Import Namespaces :

using System.Diagnostics;
using System.Windows.Forms .NET Classes used :

# System.Diagnostics.EventLog
# System.Windows.Forms.Form

Write to Event Log

System.Diagnostics.EventLog class lets write our application logs to the windows event
log, rather than writing logs into the specific file, its easy, and also good in terms of
performance, and multiple users environment.

Opening the windows event log:

Go to Run command and type “eventvwr”, then press the OK button, this will open the
windows event log, [or] you can also use the control panel to open it. You can see number
of event log already exists in the tree view, like “Application”, “security”, “System” etc.
in the same manner we can also add our logs from our application.

The following class is used to communicating with windows event log.

public class MyProjectHelper


{
static EventLog EL;
static MyProjectHelper()
{
if (!EventLog.SourceExists("TestApplication"))
{
//Creating new Log, (it will appear as a tree node in windows event log)
EventLog.CreateEventSource("TestApplication", "NewLog");
EL = new EventLog();
EL.Source = "TestApplication";
}

}
public static void AddEvent(string Message)
{
//Log a information to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Information);
}

public static void AddException(string Message)


{
//Log a exception to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Error);
}
public static void AddWarning(string Message)
{
//Log a warning to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Warning);
}
}

Using the MyProjectHelper class to write the event logs

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
//Logging Event
MyProjectHelper.AddEvent("Project Statrted");

//Logging Warning
MyProjectHelper.AddWarning("Too Many users connected with database..");

//Logging Exception
MyProjectHelper.AddException("Exception while accessing DB");
}
}
Code Sample Category:
ASP.NET WebForms
Language:
JavaScript
Author: Manikandan Balakrishnan

LogicaCMG

Posted Date: 12 Mar, 2007


Import Namespaces :
.NET Classes used :

Using objects in JavaScript

JavaScript supports for prototype oriented programming logics. Here we can create
objects for the functions instead of class. It’s very use full when we are implementing the
complex JavaScript logics.

Here I have created SpaceCraft prototype which is having following entities

Fields [or] Properties:


Name
Model
Speed
FuelCapacity

Methods:
ShowDetails()
StartFly()
IncreaseSpeedBy(increment value)
StopFly()

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Test Page</title>
<script type="text/javascript" language="javascript">
//Creating the prototype for the space craft
function ClassSpaceCraft(name,model)
{
//This is constrcutor
this.Name=name;
this.Model=model;
this.Speed=200;
this.FuelCapacity=100;
this.ShowDetails=function()
{
alert("Space craft
name:"+this.Name+"\nModel:"+this.Model+"\nSpeed:"+this.Speed);
}
this.StartFly=function()
{
alert("Space craft "+this.Name+" is flying..[Speed:"+this.Speed+"/kmh]");
}
this.IncreaseSpeedBy=function(speedValue)
{
this.Speed+=speedValue;
alert("Current speed:"+this.Speed);
}
this.StopFly=function()
{
alert("Space craft "+this.Name+" landed safely..");
}
}

//Using the Prototype


var obj=new ClassSpaceCraft("BlackBird","BB12");
obj.Speed=2000;
obj.ShowDetails();

//Calling the methods


obj.StartFly();
obj.IncreaseSpeedBy(500);
obj.StopFly();
</script>
</head>
<body>
</body>
</html>

Hi,
I my project how can we convert date from mm/dd/yy formate to DD/mm/yy formate

i use below code to write date

lblTime.Text = (DateTime.Now).ToShortDateString();

plz send some code to me


Answers .............

Submit Answer ... get surprise gifts and you can participate in Google AdSense
Revenue Sharing Program
--------------------------------------------------------------------------------
27 Mar 07 02:42 AM : Mayur :
hi try this
TextBox1.Text = Format(Now.Today, "dd/MM/yy").ToString

27 Mar 07 02:45 AM : Manikandan Balakrishnan : LogicaCMG


DateTime class has number of overloaded ToString method, in that you can pass the
string to format the DateTime according to required format.

Try the bellow code:

lblTime.text=DateTime.Now.ToString("dd/MM/yy");
Code Sample Category: Debug
Language: C#
Author: critic

Posted Date: 28 Aug, 2007


Import Namespaces :
.NET Classes used :

Find line number of code where Exception was thrown

This examples shows how to find the filename, method name and line number where the
exception was thrown in the application.

Most of the applications log errors and exceptions in the application. It will be very
useful if you can automatically log the method name and line number of the piece of code
which threw the exception. The below code sample displays the method name and the
line number at which the exception was thrown.

try
{
// Some code that can cause an exception.

throw new Exception("An error has happened");


}
catch (Exception ex)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex,
true);

MessageBox.Show(trace.GetFrame(0).GetMethod().Name);
MessageBox.Show("Line: " + trace.GetFrame(0).GetFileLineNumber());
MessageBox.Show("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}

Remember to use appropriate constructor for StackTrace class. Otherwise the method
GetFileLineNumber() will not show line number. It may always returns 0.
Code Sample Category: Operating System
Language: VB.NET
Author: Tony John

HP GDIC

Posted Date: 16 Feb, 2007


Import Namespaces :

#Imports System .NET Classes used :

System.Environment

Find windows folder

While many programmers assume that the windows path is C:\Windows or C:\WINNT, here
is the correct piece of code to find the windows directory in any Windows machines

Environment.GetEnvironmentVariable("SystemRoot")

Environment.GetEnvironmentVariable("windir")
Code Sample Category: Operating System
Language: C#
Author: Tony John

HP GDIC

Posted Date: 15 Feb, 2007


Import Namespaces :

using System.Net.NetworkInformation;
using System.Net.NetworkInformation .NET Classes used :

System.Net.NetworkInformation.Ping
System.Net.NetworkInformation.PingReply
System.Net.NetworkInformation.PingException

How to ping a computer

This code snippet shows how to ping a computer or device in the network and check if they
are accessible.

// Pass host name or IP Address.


public void PingHost(string host)
{
try
{
System.Net.NetworkInformation.Ping ping = new
System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pingReply = ping.Send(host);

MessageBox.Show("Status: " + pingReply.Status.ToString());


}
catch (System.Net.NetworkInformation.PingException e)
{
MessageBox.Show(e.Message);
}
}
how to add the session values..can i get the code..in c# ..? plz..
Answers .............

Submit Answer ... get surprise gifts and you can participate in Google AdSense Revenue
Sharing Program
--------------------------------------------------------------------------------
25 Feb 05 05:32 AM : Zabiullah : Emerald Software Pvt. Ltd.
Hi!

Following C# Syntax Is Used To Add Session

Session..Add(key,value);

Example:
Session.Add("Name",TextBox1.Text);

To Retrieve The Session Value Use The Following Syntax

returnValue = Session[key];

Example:
string userName = Session["Name"].ToString();

Regards,
Zabi.

Author: shwetakeshri

infitech global.com

Hi,

Plz explain how to create an event in c# .net ?

regards,

shweta

Answers .............
Submit Answer ... get surprise gifts and you can participate in Google AdSense Revenue Sharing Program
asp.net web hosting and offshore software development
02 Feb 07 12:09 AM : Adarsh Saxena :
Hi Shweta

This code sample will help yu to understand the creation of event.

namespace TestCollections
{
public class ListWithChangedEvent : System.Collections.ArrayList
{
public event System.EventHandler Changed;

protected virtual void OnChanged(System.EventArgs e)


{
if (Changed != null)
{
Changed(this, e);
}
}

public override int Add(object value)


{
int i = base.Add(value);
OnChanged(System.EventArgs.Empty);
return i;
}

public override void Clear()


{
base.Clear();
OnChanged(System.EventArgs.Empty);
}

public override object this[int index]


{
set
{
base[index] = value;
OnChanged(System.EventArgs.Empty);
}
}
}
}

namespace TestEvents
{
using TestCollections;

class EventListener
{
private ListWithChangedEvent m_list;

public EventListener(ListWithChangedEvent list)


{
m_list = list;

m_list.Changed += new System.EventHandler(ListChanged);


}

private void ListChanged(object sender, System.EventArgs e)


{
System.Console.WriteLine("This is called when the event fires.");
}

public void Detach()


{
m_list.Changed -= new System.EventHandler(ListChanged);
m_list = null;
}
}

class Test
{
static void Main()
{
ListWithChangedEvent list = new ListWithChangedEvent();

EventListener listener = new EventListener(list);

list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}

Output
This is called when the event fires.
This is called when the event fires.
02 Feb 07 12:29 AM : Manikandan Balakrishnan : LogicaCMG
Event keyword is use to create a event
Please nor this event key word is not a datatype
But we need to create a delegate which we are going to use as a datatype of the event

public delegate void SimpleEventDelegate(object sender, EventArgs e); //Datatype (like a class)
public class SampleEventClass
{
public event SimpleEventDelegate SampleEvent; //(SampleEvent is an event type of
SimpleEventDelegate)
}
ASHX Files

ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET.
The following code institutes a simple HTTP handler:
Author: Siva

Posted Date: 17 Mar, 2004


.NET Classes used :

# System.Web

<%@ WebHandler Language="C#" Class="Hello"%>

using System.Web;

public class Hello : IHttpHandler


{
public void ProcessRequest (HttpContext context)
{
string name = context.Request["Name"];
context.Response.Write ("Hello, " + name);
}

public bool IsReusable


{
get { return true; }
}
}
If this code is placed in an ASHX file named Hello.ashx and requested using the URL
http://.../hello.ashx?Name=Jeff, it returns "Hello, Jeff" in the HTTP response. ASHX files provide
developers with a convenient way to deploy HTTP handlers without customizing CONFIG files or
modifying the IIS metabase.

Siva
how to provide paging index in datagrid

This article explains ...how to privide indexing i.e. allow paging in data grid
Author: Ami Desai

Posted Date: 06 Oct, 2005


.NET Classes used :

# using System.Configuration;
# using System.Data.SqlClient ;
# using System.Data.SqlTypes;

private void Page_Load(object sender, System.EventArgs e)


{

DataTable dt = new DataTable();


DataRow dr;

dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));


dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(string)));
dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));

for (int i = 0; i <=100; i++)


{
dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now.ToShortDateString();
dr[3] = (i % 2 != 0) ? true : false;

dt.Rows.Add(dr);
}
if (chk1.Checked)
MyDataGrid.PagerStyle.Mode = PagerMode.NumericPages;
else
MyDataGrid.PagerStyle.Mode = PagerMode.NextPrev;
dv = new DataView(dt);
MyDataGrid.DataSource = dv;
MyDataGrid.DataBind();
lblEnabled.Text = "AllowPaging is " + MyDataGrid.AllowPaging;
lblCurrentIndex.Text = "CurrentPageIndex is " + MyDataGrid.CurrentPageIndex;
lblPageCount.Text = "PageCount is " + MyDataGrid.PageCount;
lblPageSize.Text = "PageSize is " + MyDataGrid.PageSize;

}
private void MyDataGrid_PageIndexChanged(object source,
System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
MyDataGrid.DataSource = dv;
MyDataGrid.DataBind();
}
Grid View Paging and Sorting

This article gives a small example of using Gridview implementing paging and sorting using Asp.Net 2.0

Author: S Sunil Naidu

Sonata

Posted Date: 08 Nov, 2005


.NET Classes used :

# System.Data.SqlClient

<H2><u>Gridview Paging and Sorting </u></H2>

Gridview : Displays the values of a data source in a table where each column represents a field and each row
represents a record.

i am putting the sample code please check out if it is helpful

As you know :

<H2><u>AllowPaging:</u></H2> Gets or sets a value indicating whether the paging feature is enabled.
<H2><u>AllowSorting:</u></H2> Gets or sets a value indicating whether the sorting feature is enabled.

In aspx code please write the gridview as


<asp:GridView
AllowPaging=true
AllowSorting=true
ID="grdView"
runat="server"
AutoGenerateColumns=false
Width="50%"
GridLines="Horizontal"
PageSize =5
OnPageIndexChanging="grdView_PageIndexChanging"
OnSorting ="grdView_OnSorting"
DataKeyNames="CustomerName" HeaderStyle-ForeColor=green HeaderStyle-
BackColor=RosyBrown
>

<RowStyle Backcolor="#e1e1ff" />


<Columns>
<asp:TemplateField HeaderText="First Name" SortExpression="CustomerName" HeaderStyle-
ForeColor=Green>
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%# DataBinder.Eval(Container.DataItem,
"CustomerName")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" SortExpression="City" HeaderStyle-Font-
Underline=true HeaderStyle-ForeColor=white>
<ItemTemplate>
<asp:Label ID="lblCity" Text='<%# DataBinder.Eval(Container.DataItem, "City") %>'
runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<H2>In Code Behind using the following code......</H2>

public partial class GridViewPgSort : System.Web.UI.Page


{
DataSet ds = new DataSet();
DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dv = bindgrid();
grdView.DataSource = dv;
grdView.DataBind();
}
}

private DataView bindgrid()


{
String ConnString = "Data Source=localhost;Initial Catalog=DatabaseName;Integrated Security=True";
String StrQuery = "select * from TableName";
SqlDataAdapter sadp = new SqlDataAdapter(StrQuery, ConnString);
sadp.Fill(ds);
if (ViewState["sortExpr"] != null)
{
dv = new DataView(ds.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
dv = ds.Tables[0].DefaultView;
return dv;
}

<H2><u>//Sorting Event:</u></H2>

protected void grdView_OnSorting (Object sender, GridViewSortEventArgs e)


{
ViewState["sortExpr"] = e.SortExpression;
grdView.DataSource = bindgrid();
grdView.DataBind();
}
<H2><u>// Paging Event
</u></H2>

protected void grdView_PageIndexChanging(Object sender, GridViewPageEventArgs e)


{
grdView.PageIndex = e.NewPageIndex;
grdView.DataSource = bindgrid();
grdView.DataBind();
}

Thanx
Sunil
Handling events & delegates with code example

Introduction
This article will demonstrate,
What is Delegate & Event…?
How to handle them at runtime…?
with an example

Author: dayanandavt

Honeywell

Posted Date: 02 Jul, 2007


.NET Classes used :

Delegates
Delegates are type safe reference/pointers & ability to point to any methods. By using a delegate, a
program can dynamically call different methods at runtime

Events
An event is a user defined runtime entity, used to achieve the dynamic communication by means of
program elements rather than procedural flow of control from one part to another. It is the way to establish
the connection between program occurrence and resulting actions at runtime.

Consider the following example in which an event will be thrown whenever an element is inserted into the
list.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DelegateEventDemo
{

public delegate void AddEvent(object sender,EventArgs e);

class DelegateHandler
{

public event AddEvent OnAdditionToList;

public ArrayList al = new ArrayList();


public DelegateHandler()
{
// Registering the Changed method to event
OnAdditionToList += new AddEvent(Changed);
}

public void OnListChanged(EventArgs e)


{
// Publish the event : Listening
if (OnAdditionToList != null)
OnAdditionToList(this, e);
}

private void Changed(object sender,EventArgs e)


{
// Notify the user
Console.WriteLine("New element has been inserted into the list.");
}

public ArrayList Add(int num)


{
al.Add(num);
// Fier the event it on occure
OnListChanged(EventArgs.Empty);
return al;
}

public ArrayList Get()


{
return al;
}

class Program
{
static void Main(string[] args)
{
DelegateHandler dh = new DelegateHandler();

// Client side handling of event


dh.OnAdditionToList += new AddEvent(ClientFunction);
for (int i = 1; i <= 10; i++)
dh.Add(i * 10);

ArrayList al = dh.Get();

for (int i = 0; i < al.Count; i++)


Console.WriteLine(al[i].ToString());

Console.ReadLine();
}

public static void ClientFunction(object sender, EventArgs e)


{
Console.WriteLine("Client handler is called.");

}
}
C# Example: How to record voice from microphone?

Code Sample Category: ASP.NET WebForms


Language: C#
Author: Rajaraman

CTS,Hyderabad

Posted Date: 18 Jul, 2007


Import Namespaces :

using Microsoft.VisualBasic;
using System.Runtime .NET Classes used :

Microsoft.VisualBasic.Devices;
Microsoft.VisualBasic;
System.Runtime.InteropServices;

How to record voice from microphone?


Do you want to record your voice from Microphone? If yes, you can use the Microsoft APIs to solve this
issue. It's a very simple approach to record your voice from Mic. I provided C#.net code to solve this issue.

1. Open C#.net web applications. And added the blow namespace.

using Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;

2. Add the below API.


[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true,
ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength,
int hwndCallback);

3. Create three Buttons and given the below name and text for the buttons.

1. Record
2. SaveStop
3. Read

1. Under Record Button Click paste the below Code:

// record from microphone


mciSendString("open new Type waveaudio Alias recsound", "", 0, 0);
mciSendString("record recsound", "", 0, 0);

2. Under Save / Stop button Click,

// stop and save


mciSendString("save recsound c:\\record.wav", "", 0, 0);
mciSendString("close recsound ", "", 0, 0);
Computer c = new Computer();
c.Audio.Stop();

3. Under Read Button Click

Computer computer = new Computer();


computer.Audio.Play("c:\\record.wav", AudioPlayMode.Background);
Save and Execute it.
SQL Example: Find Week in Given Date in SQL Server

Code Sample Category: SQL


Language: SQL
Author: Rajaraman

CTS,Hyderabad

Posted Date: 18 Jul, 2007


Import Namespaces :
.NET Classes used :

Find Week in Given Date in SQL Server

In Many caseswe need to prepare the records on weekly basis. In this case, the below function is very useful
to find the week in given date.

CREATE FUNCTION DBO.FINDINWEEK (@GIVENDATE DATETIME)


RETURNS VARCHAR(15)
AS
BEGIN
DECLARE @firstDayOfMonth VARCHAR(20),
@findWeek INT,
@weeks VARCHAR(30)

SET @firstDayOfMonth = CAST(MONTH(@givenDate) AS VARCHAR(2))+'/'+'1'+'/'+


CAST(YEAR(@givenDate) AS VARCHAR(4))

SET @findWeek= DATEPART(wk, @givendate) - DATEPART(wk, @firstDayOfMonth) + 1

SET @weeks = CASE @findWeek


WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
WHEN 4 THEN 'Fourth'
WHEN 5 THEN 'Fifth'
WHEN 6 THEN 'Sixth'
ELSE 'Seventh'
END

RETURN @weeks + ' Week'


END

How to call this function from Sql sever?

select dbo.FindInWeek('02/05/2007')

Output Second Week The result shows second week because the date 02/05/2007 falls on a Monday which
is the second week, considering the Sunday to Saturday as the week.
C# Example: How to write "Text to Speech Applications" in C#?

Code Sample Category: ASP.NET WebForms


Language: C#
Author: Rajaraman

CTS,Hyderabad

Posted Date: 18 Jul, 2007


Import Namespaces :

using SpeechLib .NET Classes used :

SpeechLib.SpVoice

How to write "Text to Speech Applications" in C#?

Hi Guys,

Microsoft always provides simple solutions for complex problems.

Microsoft introduced Speech SDK 5.1 to handle text to speech applications. You can download speech SDK
from below microsoft Site.

http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86EC97-40A7-453F-B0EE-
6583171B4530&displaylang=en

After installed SpeechSDK51.exe, you need to do the following steps to create speech application.
1. Open new C# Web Application.
2. Add the Reference Microsoft object speech application
3. Add the namespace : using SpeechLib;
4. You should refer the below api for this application.

[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true,


ExactSpelling = true)] private static extern int mciSendString(string lpstrCommand, string
lpstrReturnString, int uReturnLength, int hwndCallback);

Find the simple source code for speech application in web.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
using SpeechLib;

public partial class _Default : System.Web.UI.Page


{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true,
ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength,
int hwndCallback);

protected void Button4_Click(object sender, EventArgs e)


{
SpVoice spVoice = new SpVoice();
SpeechVoiceSpeakFlags svsp = new SpeechVoiceSpeakFlags();
spVoice.Speak(this.TextBox1.Text.ToString(),svsp);
}
}
XML serialization and Binary serialization
This article explains what is serialization, difference between xml serialization and binary serialization and
provides a sample project which demonstrates the serialization features in .NET Author: Tony John

HP GDIC

Posted Date: 22 May, 2004


.NET Classes used :

System.Xml.Serialization.XmlSerializer
System.IO.StreamWriter
System.IO.TextWriter
System.IO.TextReader
System.IO.Stream
System.IO.FileStream
System.IO.FileNotFoundException
System.Runtime.Serialization.IFormatter
System.Collections.ArrayList

What is serialization?

Serialization is the process of saving the current state of any object into persistent storage (like file system),
so that it can be retrieved later (Deserialize) and re create the same object.

For example, you have an object called student. You assign some values into the properties of this student
object and serialze this object into a file. You can keep this file and de serialize any time later to re produce
your student to the saved state.

What is serializable class ?

If a class can be serialized by using the builtin serialization features in .NET, that class is called serializable
class. Most of the classes provided by .NET Framework is serializable.

Different types of Serialization

There are two broad categories of serialization in .NET

1. XML Serialization
2. Binary Serialization

XML Serialization serializes the object into an xml file. This file is human readable and can be shared with
other applications.

Binary serialization is more efficient, but the serialized file is in binary format. It may not make any sense
for a human being to open this file and understand what it contains. It is a stream of bytes.
Can I make my own classes serializable ?

Yes, it is very easy to make any class serializable. Simply add an attribute called 'Serializable' just above the
class declaration and your class is serializable - means anybody can write few lines of C# code to save the
state of the instance of your class into disk and retrieve (deserialize) later.

[Serializable]
public class MyClass
{
public string name;
public string adress;
}

How to serialize classes ?

The following samples demonstrate how to do XML Serialization and Binary Serialization using .NET
classes.

We are serializing an 'ArrayList' object into disk and deserializing it again from the disk into another array
list.

If you are not familiar with ArrayList - it is a collection class provided by .NET Framework, which can hold
a list of any objects. The sample shown below uses an ArrayList which holds a list of strings.

XML Serialization

ArrayList itemsToSerialize = new ArrayList();


itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

XmlSerializer serializer = new XmlSerializer( typeof(ArrayList) );

TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );


serializer.Serialize( writer, itemsToSerialize );
writer.Close();

In the first step, we are creating an array list and adding two strings into it. next step is to create an instance
of XmlSerializer class, which is provided by .NET Framework to help serialize any objects. In the
constructor of XmlSerializer class, we have to specify what type of object we want to serialize using this.
Since we are going to serialize an ArrayList, we are specifying 'typeof(ArrayList)'.

Next, we are going to do the real thing - saving the state of the ArrayList into an XML file. We will create a
TextWriter object and specify the xml file name to which we will save the ArrayList.

The following lines will save the arraylist 'itemsToSerialize' into the file 'MyApplicationData.xml':
TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

Now, you can check the folder where your application executable is. A file with the name
'MyApplicationData.xml' will be created and you can open the file in any text editor to see the content.

Deserialization

We have serialized an arraylist into an xml file. This means, the state of the arraylist is saved into the xml
file. So, we should be able to retrieve the same arraylist from this xml file. The following code will
deserialize the arraylist from the xml file.

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();


ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

Just few lines of code ! The above code will read the XML file 'MyApplicationData.dat' and restore the
arraylist 'itemsDeserialized' - means the list of items we originally saved into the XML file will be loaded
back to the array list. Now the arraylist 'itemsDeserialized' will contain two strings 'john' 7 'smith' whcih we
saved as part of the serialization process.

Binary Serialization

Binary serialization is pretty much same as XML serialization, except that the data stored in a stream of
bytes, not in XML format. See the sample code :

ArrayList itemsToSerialize = new ArrayList();


itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );


IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );

stream.Close();

The above code sample will serialize the arraylist 'itemsToSerialize' into the file 'MyApplicationData.dat'.

Deserializing the binary data

The objects serialized using binary formatter can be deserialized the same way.
Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();


ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

The above sample will read the file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized'.

Where is Serialization used

Serialization has lot of uses in application development. One important purpose is to transmit data between
application domains. Webservices and remoting uses serialization/deserialization technique to exchange
data.

When you call a webservice and pass parameters, the parameters are serialized into XML data and send to
the server. When the webservice return data, the result is serialized into XML and returned to the caller. This
means, you can pass only serializable data in web service calls.

In Remoting, you can choose either Binary or SOAP(XML) formatting. Depending on what format you
choose, data is serialized using xml or binary format and exchanged between the server and client.

In addition to the above, you can use serialization as a way to store the application data into files. For
example, you want to save the last logged in user name, but you don't have a database. You can serialize the
user object itself or serialize just the name of the user into disk. When you start the application next time,
you can deserialize the user name from the serialized data. Many of the applications use this serialization
mechanism to remember the user settings and application data.

Summary

The classes provided by .NET Framework make it very easy to persist the state of any serializable object
and restore it to the same state. In the above samples, we have used an ArrayList object. Instead of
ArrayList, we can serialize/de serialize any serializable objects including custom classes.

Sample Application

The attached sample application demonstrates both XMl serialization and Binary serialization. The sample
project has a list box. You can add/remove items to the listbox. When you press the serialize button, the
items in the listbox is copied to an ArrayList object and this array list is serialized.

When you press the de serialize button, the data is de serialzed into an Arraylist object and the listbox is
loaded from this array list.
Note that the data serialized will persist even after you close the application. So, you can add few items into
the list box in the sample project, serialize them into file and close the application. When you re start the
application, you can restore the state of your list box you saved last.

Download sample application


Creating List/ArrayList of your own type

How to create your own type of List & ArrayList Author: amit khosla

Second Foundation Chandigarh, India

Posted Date: 11 Apr, 2006


.NET Classes used :

System.Collections.CollectionBase

Many times, I use List. But List has a disadvantage that we cant get item like we get in arrays like: arr[i];

For this to overcome we have a class ArrayList.


ArrayList supports all functionalities of list. Other than this it give the feature of retrieving the items in
format: arr[i];

But in both I faced a problem that I was unable to get the Item in my type. I had to typecast it firstly then I
can work on it. So to make me work directly on the List items; I have to inherit a CollectionBase. This
ensures features of the List. Here I am giving the sample how to create the collection of our own type.

using System; using System.Collections; public class Vectors : CollectionBase //CollectionBase


is used to add List Functions //like
Add,insert,exist etc. { int x,y; //x & y co-ordinates.
public Vectors() //Making new vector to point to origin
{ x=0; y=0; } public int XCoord
//Setting & Retrieving X-Co-ordinate { get
{ return ( x ); } set
{ x=value; } }
public int YCoord //Setting & Retrieving X-Co-ordinate {
get { return ( y ); }
set { y=value; }
} public Vectors this[ int index ] //This feature make it work as an arraylist {
get { return( (Vectors) List[index] );
} set { List[index]
= value; } }
public int Add( Vectors value ) //Add Vector to the list {
return( List.Add( value ) ); } public int IndexOf( Vectors value
) //Return Index { return( List.IndexOf( value ) );
} public void Insert( int index, Vectors value ) {
List.Insert( index, value ); } public void Remove( Vectors value )
{ List.Remove( value ); } public bool Contains( Vectors
value ) { // If value is not of type Int16, this will return false.
return( List.Contains( value ) ); } protected override void OnInsert( int
index, Object value ) { // Insert additional code to be run only when inserting
values. } protected override void OnRemove( int index, Object value ) {
// Insert additional code to be run only when removing values. }
protected override void OnSet( int index, Object oldValue, Object newValue ) {
// Insert additional code to be run only when setting values. } protected
override void OnValidate( Object value ) { if ( value.GetType() !=
Type.GetType("System.Int16") ) throw new ArgumentException( "value must be
of type Int16.", "value" ); } }

The collection made here can be used easily.


C# Example: Reading an XML File

Code Sample Category: XML


Language: C#
Author: Vijay Kumar Naidu

WinWire Technologies Ltd.

Posted Date: 06 Aug, 2007


Import Namespaces :

using System .NET Classes used :

System.Xml

Reading an XML File

This Code helps you find the XML DOM that loads the file and gets you nodes value and attribute value of
the XML file. Basic example - especially for beginners.
Let us take a sample XML file as given below and name it as Sample.xml

<?xml version="1.0" encoding="utf-8" ?>


<Root>
<Parent name ="ABC">
<Child name="abc1"/>
<Child name="abc2"/>
</Parent>
<Parent name ="XYZ">
<Child name="xyz1"/>
<Child name="xyz2"/>
</Parent>
</Root>

Next, reading this XML file in our ASPX page. I have taken two listboxes on the page. ListBox1: Will get
you the XML Node names ListBox2: Will get you the XML attribute values

protected void Page_Load(object sender, EventArgs e)


{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("Sample.xml"));

XmlNode rnode = doc.SelectSingleNode("Root");


if (rnode.HasChildNodes)
{
cyclingnodes(rnode);
}
}

// Applying Recursion Method


private void cyclingnodes(XmlNode prnode)
{
foreach (XmlNode cnode in prnode.ChildNodes)
{
ListBox1.Items.Add(cnode.Name);
ListBox2.Items.Add(cnode.Attributes["name"].InnerText);

if (cnode.HasChildNodes)
{
cyclingnodes(cnode);
}
}
}
how to provide paging index in datagrid

This article explains ...how to privide indexing i.e. allow paging in data grid Author: Ami Desai

Posted Date: 06 Oct, 2005


.NET Classes used :

using System.Configuration;
using System.Data.SqlClient ;
using System.Data.SqlTypes;

private void Page_Load(object sender, System.EventArgs e)


{

DataTable dt = new DataTable();


DataRow dr;

dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));


dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(string)));
dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));

for (int i = 0; i <=100; i++)


{
dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now.ToShortDateString();
dr[3] = (i % 2 != 0) ? true : false;

dt.Rows.Add(dr);
}
if (chk1.Checked)
MyDataGrid.PagerStyle.Mode = PagerMode.NumericPages;
else
MyDataGrid.PagerStyle.Mode = PagerMode.NextPrev;
dv = new DataView(dt);
MyDataGrid.DataSource = dv;
MyDataGrid.DataBind();
lblEnabled.Text = "AllowPaging is " + MyDataGrid.AllowPaging;
lblCurrentIndex.Text = "CurrentPageIndex is " + MyDataGrid.CurrentPageIndex;
lblPageCount.Text = "PageCount is " + MyDataGrid.PageCount;
lblPageSize.Text = "PageSize is " + MyDataGrid.PageSize;

}
private void MyDataGrid_PageIndexChanged(object source,
System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
MyDataGrid.DataSource = dv;
MyDataGrid.DataBind();
}
Basic string operations

This sample shows the commonly used string operations. Author: Tony John

HP GDIC

Posted Date: 14 Feb, 2004


.NET Classes used :

' Declare a string variable and assign the value it it.


Dim myLine As String = "dotnetspider.com is the best technology site"

Dim str as String

' extract portion of the string - starting from position 0, get 16 characters.
str = myLine.Substring(0, 16)
Console.WriteLine(str) ' Displays : dotnetspider.com

' extract portion of the string - starting from position 17, get 12 characters.
str = myLine.Substring(17, 12)
Console.WriteLine(str) ' Displays : is the best

' Split the line into words. Split based on the space ("").
Dim strArray As String() = myLine.Split(" ")
Console.WriteLine("strArray has " & strArray.Length & " words") ' Displays : strArray has 6 words

' Convert all characters to UPPERCASE


str = myLine.ToUpper()
Console.WriteLine(str) ' Displays : DOTNETSPIDER.COM IS THE BEST TECHNOLOGY SITE
' Find location of a word in a string
Dim position As Int16 = myLine.IndexOf("best")
Console.WriteLine(position) ' Displays : 24

' Insert a string into another string in specific position


str = myLine.Insert(20, "one of ")
Console.WriteLine(str) ' Displays : dotnetspider.com is one of the best technology site
ASHX Files

ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET.
The following code institutes a simple HTTP handler: Author: Siva

Posted Date: 17 Mar, 2004


.NET Classes used :

System.Web

using System.Web;

public class Hello : IHttpHandler


{
public void ProcessRequest (HttpContext context)
{
string name = context.Request["Name"];
context.Response.Write ("Hello, " + name);
}

public bool IsReusable


{
get { return true; }
}
}

If this code is placed in an ASHX file named Hello.ashx and requested using the URL
http://.../hello.ashx?Name=Jeff, it returns "Hello, Jeff" in the HTTP response. ASHX files provide
developers with a convenient way to deploy HTTP handlers without customizing CONFIG files or
modifying the IIS metabase.
Siva
Runtime callable Wrapper

Lot of COM components would have been developed using VB 6. How can I call these components as it is
in ASP.Net? This is what I explained in this article with small example. Author: Venkat BS

Posted Date: 10 Dec, 2004


.NET Classes used :

Introduction

Lot of COM components would have been developed using VB 6. How can I call these components as it is
in ASP.Net? This is what I explained in this article with small example.

What is Runtime Callable Wrapper?

The common language runtime exposes COM objects through a proxy called the runtime callable wrapper
(RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to
marshal calls between a .NET client and a COM object.

Create a DLL using VB 6

Have Project name as VBClass


Have Class name as TestClass
Public Function WelcomeMe(strMyName As String) As String Dim strWelcome As String strWelcome =
"Hi Welcome " & strMyName & ". VB Component Called in .Net" WelcomeMe = strWelcomeEnd
Function

Compile the dll as VBClass.dll

Create Run Time Callable Wrapper

At this point you ready with sample COM component VBClass.dll, now create Run Time Callable Wrapper
using .Net tool called TBLIMP.

tlbimp VbClass.dll \out:ComImport.dll

Bin Directory

Copy ComImport.dll in the application BIN directory


Sample ASP.Net Page

Now create a sample ASP.Net page to call the Function WelcomeMe. Pass your name as a parameter for the
function WelcomeMe.
<%@ page language="vb" %><%@ import namespace="ComImport"%><script language="vb"
runat="server">sub page_load(sender as object,e as eventargs) Dim objCom as TestClass objCom =
new TestClass() lblmessage.text = objCom.WelcomeMe("Your Name")end sub</script><form
id=frmone runat="server"><asp:button id=cmdbutton1 Text="submit" runat="server"/><asp:label
id=lblmessage Text="Test" runat="server"/></form>

When the page gets load it calls the function WelcomMe and displays with the string that you passed for
WelcomeMe in the label.

OutPut Will be like this: Hi Welcome . VB Component called in .Net.

Summary

With this basic idea explore it more.


Migrating from VB 6.0 to VB.NET - Some Tips

Are you planning to migrate your old VB 6 application to VB.NET ? This articles give some basic idea on
migrating vb projects to vb.net. Author: Venkat BS

Posted Date: 07 Feb, 2005


.NET Classes used :

MIGRATION TIPS FROM VB 6.0 TO VB.NET

Points to consider when you migarate your code from VB 6.0 to VB.Net

Data Type Changes

VB.NET has no currency data type. Instead it provides decimal as a replacement.

VB.NET introduces a new data type called Char. The char data type takes 2 bytes and can store Unicode
characters.
VB.NET do not have Variant data type. To achieve a result similar to variant type you can use Object data
type. (Since every thing in .NET - including primitive data types - is an object, a variable of object type can
point to any data type).

In VB.NET there is no concept of fixed length strings.

In VB6 we used the Type keyword to declare our user defined structures. VB.NET introduces the structure
keyword for the same purpose. The rest of the syntax is same.

The Visual Basic 6.0 Long datatype is now the Visual Basic .NET Integer datatype, and the Visual Basic 6.0
Integer datatype is now the Visual Basic .NET Short datatype.

Variable Declaration

All variables must be declared with appropriate data type. Dim x (Not allowed)

Arrays

Arrays are zero based index by default

Error Handling

On error resume next error handling statements will work in VB.Net but advised to use Try.. Catch.. block.

Property Syntax

Visual Basic .NET introduces a more intuitive syntax for properties, which groups Get and Set together.
Your property statements are upgraded as shown in the following example:

Property Get MyProperty() As Integer MyProperty = m_MyPropertyEnd PropertyProperty Let


MyProperty(NewValue As Integer) m_MyProperty = NewValueEnd Property

is upgraded to:
Property MyProperty() As Short Get MyProperty = m_MyProperty End Get Set
m_MyProperty = Value End SetEnd Property

Others

All subroutines should enclose with paranthesis

VB.NET no longer supports default properties. You must explicitly specify the property you wish to access
from an object.
Convert integer, long, double datatypes to a string

This example demonstrates different methods to convert numeric datatypes to string datatype. Author: Tony
John

HP GDIC

Posted Date: 26 Jan, 2004


.NET Classes used :

System.Convert
System.String
System.Int32

There are several ways you can convert a number to string in .Net. Few examples are shown below.
Dim salary As String' Sample 1salary = 10000.ToString()' Sample 2Dim sal As Int32 = 10000salary =
sal.ToString()' Sample 3salary = System.Convert.ToString(sal)' Sample 4salary =
System.Convert.ToString(10000)
Asynchronous Execution in ADO.NET 2.0

In ADO.NET, when performing bulk database operations, the thread that is executing it will wait for the
database operation to complete and proceed the execution of other lines. If the database operation is bulk
and complicated, the amount of time the thread waiting will be more. To answer this, ADO.NET 2.0 is
packed with a new feature to execute bulk operations asynchronously. This article takes you through the
implementation of this new feature. Author: Karthick

Insoft.com Pvt.Ltd, Adyar, Chennai.

Posted Date: 01 Jan, 2008


.NET Classes used :

Introduction

ADO.NET 2.0 is packed with many new features that make the developers' life easier. One such feature is
executing bulk database operations asynchronously against a database. This article will help a developer to
start programming asynchronous commands in ADO.NET 2.0. In previous versions of .NET it is not
possible to execute a command asynchronously against a database. Well, this is mitigated with the arrival of
new extensions in ADO.NET with 2.0 releases. To understand asynchronous programming we should first
understand synchronous operation which is the common paradigm in ADO.NET.
Synchronous Model

Consider the listing of code below, which is purely synchronous.

Listing 1 - Synchronous

SqlDataReader dr1 = com.ExecuteReader();//Other lines of codes SqlDataReader dr2 =


com.ExecuteReader();

Synchronous means, the thread that is executing line 1 will wait until the database operations is complete
and proceed with the execution of line 2. If the database operation is really massive, then the execution will
not proceed with the other lines of code until the massive database operation is completed. This makes the
application respond slower and the end user might feel the application is not performing well. This
degradation can be mitigated with the new extensions of ADO.NET 2.0 which is called Asynchronous
ADO.NET commands. With this, it is possible to execute massive database operations asynchronously in a
separate thread by proceeding current execution of other lines of code without waiting for the massive
database operations to complete. We will see this in detail in coming sections.

Asynchronous Model

The command object of ADO.NET 2.0 is packed with the required methods to make this new feature
available. The main operations that can be performed through command object are:

Listing 2 - Command methods

ExecuteNonQuery()ExecuteReader()ExecuteScalar()ExecuteXmlReader()

Asynchronous model is supported for all the above operations except ExecuteScalar() method, which is
going to return the first row’s first column value. For programming the above operations asynchronously,
command object has one begin method and one end method for each of their synchronous counterparts. The
begin method will be called to start the execution while end method will be called when the execution
completes. Refer to the Figure 1 for Asynchronous counterparts of the above operations.

Async in action
I will implement asynchronous execution with DataReader object in this example.

Prerequisites

For the Asynchronous operation to work we have to set “Asynchronous Processing=true” or “Async=true”
in the connection string. Without this attribute set in connection string, the ADO.Net will give an error.

"This command requires an asynchronous connection. Set 'Asynchronous Processing=true' in the connection
string."

If in a same application you are using both Asynchronous and synchronous operation, it is better to use
separate connection string i.e. one with “Asynchronous Processing=true” and the other with “Asynchronous
Processing=false.” Because we are using the connection string with Async enabled for synchronous
operation, it will hit the performance some what.

The connection string will be:

"Data Source=.\SQLEXPRESS;Asynchronous Processing=true;AttachDbFilename=|DataDirectory|


\Database.mdf;Integrated Security=True;User Instance=True;"

Listing 3 - Async in action

con1 = new SqlConnection(


ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);con1.Open();com1 =
new SqlCommand("SELECT emp_id, fname, lname, job_id, hire_date FROM [employee] ORDER BY
emp_id, fname", con1); con2 = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);con2.Ope
n();com2 = new SqlCommand("waitfor delay '00:00:06';SELECT * FROM Authors", con2); IAsyncResult
ar1 = com1.BeginExecuteReader(); // Async line 1 IAsyncResult ar2 = com2.BeginExecuteReader(); //
Async line 2 //Perform some execution here //Perform some execution here dr1 =
com1.EndExecuteReader(ar1); //Sync line 1 dr2 = com2.EndExecuteReader(ar2); //Sync line 2

The thread that is executing the “Async line 1” continues executing the other lines of code (“Async line 2,”
etc.) in the above code (Listing 3 – Async in action) without waiting for the database operations to complete.
It means the database operation is given to a different thread and the current thread follows executing next
line i.e. “Async line 2.” This is called Asynchronous behavior. But the “Sync line 1” and “Sync line 2” will
be executed synchronously. The thread will wait for the “Sync line 1” to complete execution and proceed
with the “Sync line 2.” Download the code packed with this article and see it in action. I have used "waitfor
delay '00:00:06'" in the query to demonstrate the example as an alternative of complex stored procedure that
takes sometime to complete execution. Note “waitfor” statement will work only in Sql server 2005.

Thus we have learned to use the Asynchronous operations at a beginner level. Moving forward, we will
leverage more features that are packed with asynchronous operations that can be used in some complicated
scenarios.
Advanced scenarios with Asynchronous operations

Sometimes we may need to populate data in different grids from different tables that may take sometime to
complete because it is bulk. If we begin to populate the data in a traditional way, we need to fetch the data
one by one synchronously i.e. waiting for one database operation to complete to proceed with the other. We
can consider using asynchronous model in these types of scenarios to bind the grid and thus we can prevent
the waiting time for binding the grids.

To bind the grid we will be requiring the resultset which will be available only if the database operation is
complete i.e. if it is datareader the result will be available only by calling EndExecuteReader() if the
database operation is complete. We need a mechanism where we can detect the end of database operation
and bind the grid with the resultset.

This can be achieved by 3 ways.

· Through WaitHandle class

· Through Callback delegate

· Polling

Calling End method without detecting the complete signal will make the execution wait there until it is
completed.

WaitHandle class

WaitHandle class in System.Threading namespace comes to our rescue in these scenarios to detect the
completion signal from the asynchronous thread and complete the data binding.

WaitHandle class has 2 methods that take array of WaitHandle objects.

Listing 4 - WaitHandle methods

WaitHandle.WaitAll() WaitHandle.WaitAny()WaitHandle.SignalAndWait()

The first method WaitAll() will wait for all the asynchronous operation to complete and return a Boolean
indicating the completion of all the opeartion while the next method WaitAny() will give us any one index
of WaitHandle array indicating that it is completed. SignalAndWait() method signals one WaitHandle object
and waits on another, as an atomic operation. The most commonly used methods are WaitAll() and
WaitAny().
For making this work we need the WaitHandle object of each asynchronous operation. The IAsyncResult
object which is returned by Begin method has a property called AsyncWaitHandle that will give us
WaitHandle object to know the completion of the current asynchronous operation. Refer to the code below.

Listing 5 - WaitHandle methods

IAsyncResult ar1 = com1.BeginExecuteReader();


WaitHandle handles = ar1.AsyncWaitHandle;The next section will explain the use of WaitHandle object in
detail.

Using WaitHandle Object

Refer to the example code with this article to have a better understanding.

Listing 5 - WaitHandle implementation

try{ con1 = new SqlConnection(ConfigurationManager.ConnectionStrings[


"ConnectionString"].ConnectionString); con1.Open(); com1 = new SqlCommand( "SELECT emp_id,
fname, lname, job_id, hire_date FROM employee ORDER BY emp_id, fname" , con1); con2 = new
SqlConnection(ConfigurationManager.ConnectionStrings[ "ConnectionString"].ConnectionString);
con2.Open(); com2 = new SqlCommand("waitfor delay '00:00:06';SELECT * FROM Authors", con2);
con3 = new SqlConnection(ConfigurationManager.ConnectionStrings[
"ConnectionString"].ConnectionString); con3.Open(); com3 = new SqlCommand("waitfor delay
'00:00:06';SELECT * from Department", con3); IAsyncResult ar1 = com1.BeginExecuteReader();
IAsyncResult ar2 = com2.BeginExecuteReader(); IAsyncResult ar3 = com3.BeginExecuteReader();
WaitHandle[]handles = new WaitHandle[3]; handles[0] = ar1.AsyncWaitHandle; handles[1] =
ar2.AsyncWaitHandle; handles[2] = ar3.AsyncWaitHandle; for (int results = 0; results <
handles.GetLength(0); results++) { // wait for any handle, then process results as they come int index =
WaitHandle.WaitAny(handles, 8000, false); // 8 secs if (WaitHandle.WaitTimeout == index) throw
new Exception("Timeout Exception"); if (index == 0) { dr1 = com1.EndExecuteReader(ar1);
gvEmployee.DataSource = dr1; } else if (index == 1) { dr2 = com2.EndExecuteReader(ar2);
gvAuthors.DataSource = dr2; } else if (index == 2) { dr3 = com3.EndExecuteReader(ar3);
gvDepartment.DataSource = dr3; } } Page.DataBind(); } catch{ throw;} finally{ dr1.Close();
com1.Dispose(); con1.Close(); dr2.Close(); com2.Dispose(); con2.Close(); dr3.Close(); com3.Dispose();
con3.Close();}

The above code uses WaitHandle.WaitAny() method and populates data asynchronously and binds 3
gridviews. If we see this line:

Listing 6 - WaitHandle in action

int index = WaitHandle.WaitAny(handles, 8000, false);Here 8000 indicates that after 8000 milli seconds if
no completed signal is received then it is said to have reached timeout. WaitHandle.WaitTimeout property
will gives us the index of the WaitHandle object in the array indicating that it has reached the timeout.
Callback delegate

One of the overloads of begin method will accept a delegate argument with a state object to detect the
completion. Once the database operation is complete, ADO.Net will call the delegate and the state can be
accessed by IAsyncResult object.

Listing 7 - Callback delegate

BeginExecuteReader(AsyncCallback callback, object state)The call back method should accept


IAsyncResult as an argument and call the End method.

Visit the Keyvan's blog in the references section to see the implementation of callback delegate.

Polling

The completion signal can also be detected by a method called IsCompleted() in IAsyncResult which
returns a Boolean indicating that the operation is completed.

Cancel the execution

For some reason or business condition, if we like to cancel the operation, we can call Cancel() method
packed with the command object.

Points to consider

Since the database operation is executed in a separate thread, if an exception occurs then the operation is
signaled as complete and the actual exception will be thrown if we call End method. So we have to make
sure that we are having proper exception handling code in this scenario.

References

Asynchronous command execution in .NET 2.0

Conclusion
In this article I have discussed one of the useful features in ADO.NET 2.0 which helps us to increase the
scalability and performance of the database application drastically without much effort. Download the
source with this article and see it in action.

Happy Coding!!!
Working with Exceptions - Part III (Nested Try....Catch....Block)

Author: Sadha Sivam

Aspire Systems

Posted Date: 10 Mar, 2004


.NET Classes used :

Working with Exceptions - Part III (Nested Try....Catch....Block).

In this section of article I will be telling about structured exception handling, try...

catch... finally block.


What we saw in the Part I & II
We defined the exception, then we discussed in detail about the Unstructured Exception handling,

Structured Exception handling and about Try....Catch...Finally block.

In this section of article we will see more about Nested Try....Catch....Finally block.

Nested Exception

In .Net, it is possible to have nested try catch blocks inside each other, for example:

Try ' Block of code, where the chances of getting exception is there Try 'Block of code, where the exception
needs to be handled. catch FinallyEnd Try catch 'Block of code that nneds to be executed when the
exception of that type is caught Try 'Block of code, where the exception needs to be handled. catch
FinallyEnd TryFinally'Block of code that needs to be executed, even when there is no exceptions.End Try

Now, Lets see how the exception is handled in the above case. In the above code you can see that

i have three sets of Try...Catch... Finally block

One Outer class

One Inside the Outer Try block


One Inside the catch block of the Outer Try block.

Different Possiblities of Exception Raising

Say, for example an exception is raised in the Outer Try block (But outside the inner try

block), then the control jumps to the outer catch block and code in the matching outer catch

block is executed as usual.

Say, for example an exception is raised in the Inner Try block, then the check for the

matching catch block in the inner try...catch block. If found executes that block and its

finally block and comes out of the inner try block and proceeds as usual. If the matching catch

block is not found, then the control jumps finally block of the inner try...catch block and then

jumps to the catch block of the outer Try Block and proceeds as usual.

The Try... catch block inside the Catch statement is very simple. That is to handle the

exception raised in that Catch block.

Example

Public Function Structeddivide(ByVal a As Integer, ByVal b As Integer) As Integer Dim fis1 As


System.IO.FileStream Dim fw As System.IO.StreamWriter Dim fis2 As System.IO.FileStream
Dim fr As System.IO.StreamReader Try fis1 = New System.IO.FileStream("c:\WriteResult.txt",
IO.FileMode.Append) fw = New System.IO.StreamWriter(fis1) Try fw.WriteLine(a / b)
Catch overexp As OverflowException MsgBox("Inside the Inner Catch Block") End Try fis1
= New System.IO.FileStream("c:\WriteResult.txt", IO.FileMode.Append) fr = New
System.IO.StreamReader(fis1) MsgBox(fr.ReadLine) Return a / b Catch ioexc As
System.IO.IOException MsgBox("IO Exception Occured") Finally MsgBox("Calculation over")
fw.Close() fis1.Close() End Try End Function

In the above example if you see i have include the statement fw.writeline(a/b) where are two

possible exception in the statement,


One is when the parameter b is passed the value zero - raised the OverFlowException, if the

exception is raised, we are trapping that there it self and proceeding the next step.

When the file is locked for editing by some other user it causes the IOException which we are

trapping in the outer try...catch....block

How the Nested Try..Catch...Finnally will be usefull

Consider the case, where some expected Exception may raise in the try catch block which may

not be that important. Which should not affect our program execution. Say, if we have only one

exception handler then all the statement form the line of Exception raised will be ignored and

jumps to the try catch block.

If we implement the try..catch block for that statement alone, then this can be avoided.

We will see more about created User defined exception in our next section of this article
Seperating Data Tier codings in a class file using c#
09 Jan, 2008

Author: karthikeyan

i want to use the data tier class file seperately in my project . And Now i am using c# language. please help
me .
Answers .............

Submit Answer ... get surprise gifts and you can participate in Google AdSense Revenue Sharing Program
asp.net web hosting and offshore software development
09 Jan 08 12:43 AM : Harsha :
refer this link

http://www.dotnetspider.com/qa/Question118178.aspx

09 Jan 08 01:02 AM : Gunarathinamm : Integra Software Services


http://www.Integra-india.com
Hi,

use this code in Data Class file.

public static object GetCommand(int ExecuteType, string Procedurename, ArrayList ParameterName,


ArrayList ParameterType, ArrayList ParameterValue)
{
SqlConnection constr = new
SqlConnection(ConfigurationManager.ConnectionStrings["iTracksCnStr"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlParameter sqlpara = new SqlParameter();
object ReturnValue = new object();
ParameterName.TrimToSize();
ParameterType.TrimToSize();
ParameterValue.TrimToSize();
try
{
sqlcmd.Connection = constr;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = Procedurename;
sqlcmd.CommandTimeout = 1000;
for (int i = 0; i < ParameterName.Count; i++)
{
sqlpara = new SqlParameter("@" + ParameterName[i], ParameterType[i]);
sqlpara.Value = ParameterValue[i];
sqlcmd.Parameters.Add(sqlpara);
}

ParameterName.Clear();
ParameterType.Clear();
ParameterValue.Clear();
if (ExecuteType == 1)
{
constr.Open();
ReturnValue = sqlcmd.ExecuteScalar();
constr.Close();

}
else if (ExecuteType == 2)
{
constr.Open();
ReturnValue = sqlcmd.ExecuteNonQuery();
constr.Close();
}
else if (ExecuteType == 3)
{
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
ReturnValue = ds;
adapter.Dispose();
ds.Dispose();
}
else if (ExecuteType == 4)
{
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
ReturnValue = dt;
adapter.Dispose();
dt.Dispose();
}
else if (ExecuteType == 5)
{
constr.Open();
SqlDataReader Reader;
Reader = sqlcmd.ExecuteReader();
ReturnValue = Reader;

}
return ReturnValue;
}
catch
{
constr.Close();
throw;
}
finally
{
}
}

This gets only the SP name and Parameter details in arraylist.

In Presentation layer use this code:

ArrayList ParameterName = new ArrayList(); ArrayList ParameterType = new ArrayList();


ArrayList ParameterValue = new ArrayList();

ParameterName.Add("SelectFlag");
ParameterType.Add(SqlDbType.Int);
ParameterValue.Add(1);

ParameterName.Add("RFI_Type");
ParameterType.Add(SqlDbType.TinyInt);
ParameterValue.Add(int.Parse(rdlRaise.SelectedValue));

ParameterName.Add("jobcardid");
ParameterType.Add(SqlDbType.Int);
ParameterValue.Add(int.Parse(gvFullRaise.DataKeys[int.Parse(e.CommandArgument.ToString(
))].Values["JobCardId"].ToString()));

DataTable dt_JobStatus = (DataTable)LocalLibrary.GetCommand(4, "[RFI_GetJobStatus]",


ParameterName, ParameterType, ParameterValue);

Thanks,
Guna.
Tool to Transform an XML file using XSL/XSLT into HTML/XML file

This article explains how to write a simple exe which helps you to transform an xml file using an xsl/xslt
style sheet into a HTML or XML file. It also includes the sample code.
Author: Anusha

Posted Date: 01 Sep, 2005


.NET Classes used :

# Imports System.IO
# Imports System.Xml
# Imports System.Text
# Imports System.data
# Imports System.Xml.Xsl
# Imports System.Xml.XPath
Form Design

You need 3 textbox controls,


the input file and path
the style sheet and path
the output folder path

We have 2 OpenFileDialog boxes


Input file
Style Sheet

One FolderBrowserDialog to choose the folder where you want the output to be generated

We have 4 Buttons each for selecting the files/folder location and the last one does the transformation and
generates the output.

We have a progressbar control which displays the progress of the transformation.

We also have a label which displays the status of the transformation (success or failure)

Internal Logic

Public Class frmXML


Inherits System.Windows.Forms.Form

Sub main()
Dim frm As New frmXML
frm.ShowDialog()
End Sub

Defining the strings needs for input, output and the style sheet

Private gsTransformedXMLFile As String


Private gsXSLFile As String
Private sInputXMLFile As String

Function that does the transformation and generates the output


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim oXSLTransform As XslTransform
Dim oXSLTemplate As String
Dim oXMLResolver As XmlResolver

Defining a progressbar and incrementing its value to show the progress while the file is being transformed

ProgressBar1.Value = 1

Based on the option selected we generate an .html or .xml extension. The outout file that is being generated
is always a output.html or output.xml file. We append the file name and extension to the path chosen using
the FolderBrowserDiaglog to generate the output on the appropriate folder.

If rdHTML.Checked Then
gsTransformedXMLFile = txtOutput.Text + "/Output.html"
ProgressBar1.Value += 1
ElseIf rdXML.Checked Then
gsTransformedXMLFile = txtOutput.Text + "/Output.xml"
ProgressBar1.Value += 1
Else
gsTransformedXMLFile = txtOutput.Text
End If

ProgressBar1.Value += 1
gsXSLFile = txtStyleSheet.Text
ProgressBar1.Value += 1
sInputXMLFile = txtInput.Text
ProgressBar1.Value += 1
Try
oXSLTransform = New XslTransform
oXSLTransform.Load(gsXSLFile)
ProgressBar1.Value += 3
oXSLTransform.Transform(sInputXMLFile, gsTransformedXMLFile, oXMLResolver)
ProgressBar1.Value = ProgressBar1.Maximum
Message.Visible = True
Catch ex As Exception
Message.Visible = True
Message.ForeColor = System.Drawing.Color.DarkRed
Message.Text = "Error Transforming XML File"
MsgBox(ex.ToString, MsgBoxStyle.Critical, "XMLTransform Error")
Finally
oXSLTransform = Nothing
End Try

End Sub

The following functions uses File and Folder Dialogs to select the input and stylesheet files and output
folder

Private Sub btnInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnInput.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
txtInput.Text = OpenFileDialog1.FileName
End If
End Sub

Private Sub btnStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnStyle.Click
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
txtStyleSheet.Text = OpenFileDialog2.FileName
End If
End Sub

Private Sub btnOutput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnOutput.Click
If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
txtOutput.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub

Private Sub frmXML_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load
rdHTML.Checked = True
End Sub
End Class
Expanding and Collapsing dynamically.......Java Script/XSLT

This article explains how to use JavaScript to dynamicall expand and collapse tables.
Author: Anusha
Posted Date: 27 Sep, 2005
.NET Classes used :

These functions provided below are used to dynamically expand and collapse tables. These functions are
very helpful when you are generating an HTML from a XML using an XSLT. These functions are used for
collapsing all the rows, displaying just the first line of information, and also for expanding or collapsing just
one row of table/sub-table information. These functions use a style sheet where all these classes are defined.
In the java script, we change the ‘class’ attribute of the tags to achieve the desired effect. These functions are
self explanatory and they also include comments in between.

function outliner ()
{
oMe = window.event.srcElement
//get child element
var childrenName = oMe.get_ttribute("child",false);
var children = document.getElementsByName(childrenName);
//if child element exists, expand or collapse it.
if (null != children)
{
for(i=0; i < children.length; i++)
{
var child = children(i);
child.className = child.className == "collapsed" ? "expanded" : "collapsed";
}
}
}

// This function changes the pictures for collapsing and expanding


function changepic()
{
uMe = window.event.srcElement;
var check = uMe.src.toLowerCase();
if (check.lastIndexOf("report_expand.gif") != -1)
{
uMe.src = "Report_Collapse.gif";
hidetable();
}
else
{
uMe.src = "Report_Expand.gif";
hidetable();
}
}
// This functions hides the sub table if it is visible
function hidetable()
{
for(i=0; i <document.all.length; i++)
{
var elem = document.all(i);
if(null != elem)
{
if(elem.tagName == "TABLE")
{
if(elem.className == "infotable")
{
elem.className = "hidetable";
}
if(elem.className == "hidetable")
{
elem.className = "infotable";
}
}
}
}
}

//This function is for hiding any particular selected row


// When you click on the image(‘-’), it collapses just that row
function rowcollapse(id)
{
uMe = window.event.srcElement;
var check = uMe.src.toLowerCase();
if (check.lastIndexOf("report_expand.gif") != -1)
{
uMe.src = "Report_Collapse.gif";
}
else
{
uMe.src = "Report_Expand.gif";
}
var parent = document.getElementById((id));
if(parent != null)
{
var items = parent.getElementsByTagName("tr");
for(i=0; i < items.length; i++)
{
//get row
var row = items(i);
setclass(row);
}
}
}

//This function is used for changing the value of the class attribute
function setclass(currentrow)
{
if(currentrow.className == "rowexpanded")
{
currentrow.className = "rowcollapsed";
}
else if(currentrow.className == "rowcollapsed")
{
currentrow.className = "rowexpanded";
}
}

function rowcollapseAll()
{
for(i=0; i < document.all.length; i++)
{
var elem = document.all(i);
if(null != elem)
{
if(elem.className == "rowexpanded")
{
elem.className = "rowcollapsed";
}

if(elem.tagName == "IMG")
{
if(elem.src.toLowerCase().lastIndexOf("report_collapse.gif") != -1)
{
elem.src = "Report_Expand.gif";
}
}
}
}
}

function rowexpandAll()
{
for(i=0; i < document.all.length; i++)
{
var elem = document.all(i);
if(null != elem)
{
if(elem.className == "rowcollapsed")
{
elem.className = "rowexpanded";
}
if(elem.tagName == "IMG")
{
if(elem.src.toLowerCase().lastIndexOf("report_expand.gif") != -1)
{
elem.src = "report_collapse.gif";
}
}
}
}
}

//This function will expand all the rows

function expandAll()
{
for(i=0; i < document.all.length; i++)
{
var elem = document.all(i);
if(null != elem)
{
if(elem.className == "collapsed")
{
elem.className = "expanded";
}
if(elem.tagName == "IMG")
{
if(elem.src.toLowerCase().lastIndexOf("report_expand.gif") != -1)
{
elem.src = "Report_Collapse.gif";
}
}
}
}
}

//This function will collapse all the rows

function collapseAll()
{
for(i=0; i < document.all.length; i++)
{
var elem = document.all(i);
if(null != elem)
{
if(elem.className == "expanded")
{
elem.className = "collapsed";
}
if(elem.tagName == "IMG")
{
if(elem.src.toLowerCase().lastIndexOf("report_collapse.gif") != -1)
{
elem.src = "Report_Expand.gif";
}
}
}
}
}

The following style sheet defines the attributes of the classes used

.issuenone
{
background-color: #ffffff;
border-bottom: 0px;
border-left: 0px;
border-right: 0px;
border-top: 0px;
color: #000000;
font-weight: normal;
}
.content
{
background-color: #e7e7ce;
border-bottom: #ffffff 1px solid;
border-left: #ffffff 1px solid;
border-right: #ffffff 1px solid;
border-top: #ffffff 1px solid;
padding-left: 3px;
}
.expandable
{
cursor: hand;
}
.expanded
{
color: black;
}
.collapsed
{
display: none;
}
.rowexpanded
{
color: black;
}
.rowcollapsed
{
display: none;
}
.hidetable
{
display:none;
}
26 Jun 07 06:56 AM : dayanandavt : Honeywell
If u want to create ur own custom control button then inherit System.Windows.Forms.Button to ur class then
override OnPaint method as bellow with related info.

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace myCustomControlButton
{
/// <summary>
/// Summary description for cuteButton.
/// </summary>
public class myCustomControlButton : System.Windows.Forms.Button
{
private Color m_color1 = Color.LightGreen; //first color
private Color m_color2 = Color.DarkBlue; //second color
private int m_color1Transparent = 64;
private Button button1; //transparency degree (applies to the 1st color)
private int m_color2Transparent = 64; //transparency degree (applies to the 2nd color)
public Color cuteColor1
{
get { return m_color1; }
set { m_color1 = value; Invalidate(); }
}

public Color cuteColor2


{
get { return m_color2; }
set { m_color2 = value; Invalidate(); }
}

public int cuteTransparent1


{
get { return m_color1Transparent; }
set { m_color1Transparent = value; Invalidate(); }
}

public int cuteTransparent2


{
get { return m_color2Transparent; }
set { m_color2Transparent = value; Invalidate(); }
}

public myCustomControlButton()
{
}

protected override void OnPaint(PaintEventArgs pe)


{
// Calling the base class OnPaint
base.OnPaint(pe);
// Create two semi-transparent colors
Color c1 = Color.FromArgb
(m_color1Transparent, m_color1);
Color c2 = Color.FromArgb
(m_color2Transparent, m_color2);

Brush b = new System.Drawing.Drawing2D.LinearGradientBrush


(ClientRectangle, c1, c2, 10);

pe.Graphics.FillRectangle(b, ClientRectangle);
b.Dispose();
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 0);
this.button1.Name = "MyButton1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "MyButton1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.ResumeLayout(false);

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("U have clicked my button");
}

}
}
C# Example: Multi-Cast delegates

Code Sample Category: Event Handling


Language: C#

Posted Date: 09 Jul, 2007


Import Namespaces :
.NET Classes used :

Multi-Cast delegates

In this section of code i'll demonstrate how to call many methods at runtime associated with that particular
delegate.
using System;
using System.Collections.Generic;
using System.Text;

namespace DelegatesHandling
{
public delegate decimal Calculator(decimal num1, decimal num2);
public delegate void Test(string str);

class Program
{
Calculator claci_1;
Calculator claci_2;
Calculator calci;

decimal Addition(decimal n1,decimal n2)


{
return n1 + n2;
}

decimal Subtraction(decimal n1, decimal n2)


{
return n1 - n2;
}

void TestMethod1(string str)


{
Console.WriteLine("I am in TestMethod1 "+str);
}

void TestMethod2(string str)


{
Console.WriteLine("I am in TestMethod2 " + str);
}

static void Main(string[] args)


{

Program pgm = new Program();


pgm.claci_1 = new Calculator(pgm.Addition);
pgm.claci_2 = new Calculator(pgm.Subtraction);

pgm.calci = new Calculator(pgm.Subtraction);


pgm.calci += new Calculator(pgm.Addition);
decimal result = pgm.claci_1(12.23m, 344.422m);
Console.WriteLine("Addition = "+result);

result = pgm.claci_2(12.23m, 344.422m);


Console.WriteLine("Subtraction = " + result);

result = pgm.calci(12.2m,13.8m);
Console.WriteLine("Subtraction = " + result);

Console.ReadLine();

}
}
}
C# Example: Handling events & delegates with code example

Code Sample Category: Event Handling


Language: C#

Posted Date: 02 Jul, 2007


Import Namespaces :
.NET Classes used :

Handling events & delegates with code example

This article will demonstrate,


How to handle them at runtime with an example.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DelegateEventDemo
{
public delegate void AddEvent(object sender,EventArgs e);

class DelegateHandler
{

public event AddEvent OnAdditionToList;

public ArrayList al = new ArrayList();

public DelegateHandler()
{
// Registering the Changed method to event
OnAdditionToList += new AddEvent(Changed);
}

public void OnListChanged(EventArgs e)


{
// Publish the event : Listening
if (OnAdditionToList != null)
OnAdditionToList(this, e);
}

private void Changed(object sender,EventArgs e)


{
// Notify the user
Console.WriteLine("New element has been inserted into the list.");
}

public ArrayList Add(int num)


{
al.Add(num);
// Fier the event it on occure
OnListChanged(EventArgs.Empty);
return al;
}

public ArrayList Get()


{
return al;
}

}
class Program
{
static void Main(string[] args)
{
DelegateHandler dh = new DelegateHandler();

// Client side handling of event


dh.OnAdditionToList += new AddEvent(ClientFunction);

for (int i = 1; i <= 10; i++)


dh.Add(i * 10);

ArrayList al = dh.Get();

for (int i = 0; i < al.Count; i++)


Console.WriteLine(al[i].ToString());

Console.ReadLine();
}

public static void ClientFunction(object sender, EventArgs e)


{
Console.WriteLine("Client handler is called.");

}
}
Concurrency Control Using ADO.NET

This article explains ... Author: pradipta

Posted Date: 29 Nov, 2004


.NET Classes used :
While doing certain modification in the database some time you need to lock the data so that no one can else
perform modification in that data. There are two commonly known approaches for locking database they are
optimistic locking and pessimistic locking.
Both these approaches are used to maintain concurrency in the database. Pessimistic concurrency locking is
done at rows of the data source to prevent users from modifying data in a way that affects other users. In a
pessimistic model, when a user performs an action that causes a lock to be applied, no one else can perform
action until unless owner releases that lock. But this is not case with optimistic currency model. In
optimistic concurrency model user does not lock row while reading it, while user only locks the row while
updating changes to the database.

In .NET we use DataSet object for modifying changes in the database. The DataSet object uses optimistic
concurrency model with the help of DataAdaptor. The DataSet object is designed to encourage the use of
optimistic concurrency for long-running activities such as when you are working in distributed environment.

In real time execution DataSet maintains the versions of data that means if anyone modify any data in the
DataSet then it get maintain in the dataset as old version and new version. While updating modified data in
the database if any of the concurrency conflict occur it raises Exception, which sets DataRow’s HasError
Boolean value. This we can easily handle with DataAdaptor event and with our own programming logic.
A simple code sample, which explains you how can you manage, concurrency control in .NET environment

string connectionString = ".......................";SqlConnection myConnection = new


SqlConnection(connectionString);SqlDataAdapter myAdaptor = new SqlDataAdapter("SELECT Name,
City FROM Employee ORDER BY EmpID", myConnection);// Add the RowUpdated event
handler.myAdaptor.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);DataSet
supplierData = new DataSet();myAdaptor.Fill(supplierData, "Supplier");// Modify the DataSet contents.…
………………………………………….myAdaptor.Update(supplierData, "Supplier");foreach (DataRow
myRow in supplierData.Tables["Supplier"].Rows){if (myRow.HasErrors)Console.WriteLine(myRow[0] +
"\n" + myRow.RowError);}protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs
args){if (args.RecordsAffected == 0) {args.Row.RowError = "Optimistic Concurrency Violation
Encountered";args.Status = UpdateStatus.SkipCurrentRow;
Exception handling in .Net

An exception is an error condition or unexpected behavior encountered by an executing application during


runtime. .Net supports structured error handling. Author: Tony John

HP GDIC

Posted Date: 09 Mar, 2004


.NET Classes used :

System.Exception
System.IO.FileNotFoundException
System.DivideByZeroException
System.IO.File
Definition :

"An exception is an error condition or unexpected behavior encountered by an executing application during
runtime."

Exceptions can occur in programs due to various reasons including bad logic, non-availability of operating
system resources, network failure, attempt to access invalid objects etc. When the code which has a problem
is executed, it 'raises an exception'.

For example, if network connection to the database server is broken when you are accessing some data, .Net
Framework will raise an exception. Or, if you are attempting to read a File which do not exist, .Net
framework will raise a 'File Not Found' exception.

When an exception is raised in the system, if it is not 'handled', it will lead to program termination. This will
give a bad experience for the user and may lead to loss or corruption of data.

.Net framework provides very good, structured exception handling mechanism. In .Net, an 'exception' is a
class, which is derived from System.Exception class. When there is a problem ('exception') in the code, .net
runtime creates an 'exception' object which contains information about the nature of the problem. If you
handle the exception in the code, you will receive this exception object which contains information about
the nature of the error. This information can be used to show a friendly message to the user or to recover
from the error and continue executing the program.

How to Handle Exceptions in C#

Exceptions are handled in .Net using the 'try/catch/finally' statements. The code which 'may cause an
exception' is enclosed within a 'try' block as shown below:
try { // some code that may cause an exception. }

Now we are safe. You have protected your code. If an exception occurs in the code enclosed within the 'try'
block, you can handle it. To handle an exception, attach a 'catch' block to the 'try'.
try { // some code that may cause an exception. // If an
exception occurs in the above code, the execution will not continue within the // 'try' block.
Instead, the execution will jump to the 'catch' block. } catch (Exception ex) { // If an
exception occurs in the try block, this block will be executed. // Write the error handling code
here. }

When an exception is raised, the control of execution is transfered to the 'catch' block. You can write the
error handling code here. Yo may show a friendly message to the user or try to recover from the error by
writing appropriate code.

In the above case, we are blindly catching all exceptions. You may change the 'catch' block slightly to
handle only specific types of exceptions.
In the following example, we are attempting to copy a file to a new name. If the file doesn't exists, it will
throw a 'FileNotFound' exception.
try { System.IO.File.Copy ( "C:\\test.txt", "C:\\new.txt" );} catch
( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); }

In this case, if 'c:\test.txt' doesn't exists, then it will throw an exception. We are catching this specific type of
exception in the 'catch' block and displaying the 'exception message' to the user.

NOTE:
It is not a good idea to display the raw exception message to the user. Instead, show a friendly message to
the user and log the actual exception message to some log file for trouble shooting purposes.

In the above example, we are handling only a specific type of exception :


'System.IO.FileNotFoundException'. If any other type fo exception occurs in the above code, it is not
handled and will lead to program termination. For example, if an exception of type
'OutOfMemoryException' occurs, it is not handled and program will terminate.

To catch all types of exceptions, specify the root 'Exception' in the 'catch' block. But it is a bad
practise to catch all exceptions. You should catch only specific exceptions which are expected in teh specific
code block. For example, if you are accessing a file, you may catch 'System.IO.FileNotFoundException' and
if you are performing mathemtical operations, you may catch 'System.DivideByZeroException' exception.
Also, you can create and throw custom exceptions. If the code you are calling is expected to throw any
custom exception, you may catch those custom exceptions.

Handling more than one Exception

You can have zero or more 'catch' blocks attached with each 'try' blocks. Depending on the type of the
exception thrown, appropriate 'catch' block will be executed.
try { // some code that can throw exception. } catch
( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); }
catch ( System.DivideByZeroException ex ) { MessageBox.Show( ex.Message ); }

The above code sample handles two specific exception types : FileNotFoundException &
DivideByZeroException. When an exception occurs within the 'try' block, it will first check wether it is of
type 'FileNotFoundException'. If so, it executes that catch block. If not, it will check whether it is of type
'DivideByZeroException'. If the exception doesn't belong to one of these types, it will not be handled.

A root exception matches all exceptions derived from it. Since all exceptions are derived from
System.Exception, if you catch 'System.Exception', it will catch all exceptions.
try { // some code that can throw exception. } catch
( System.Exception ex ) { MessageBox.Show( ex.Message ); } catch
( System.IO.FileNotFoundException ex ) { MessageBox.Show( ex.Message ); }
catch ( System.DivideByZeroException ex ) { MessageBox.Show( ex.Message ); }

In the above code, 'catch ( System.Exception ex )' will catch all exceptions including
'FileNotFoundException' and 'DivideByZeroException'. So even if the 'DivideByZeroException' occurs, it
will be handled by the first catch block. So, if you handle more than one exception, the inherited ones
should be handled first. If catching 'System.Exception', it should be the last 'catch' block.

Using the 'finally' statement to perform cleanup operations


try { // some code that can throw exception. } catch ( System.Exception
ex ) { MessageBox.Show( ex.Message ); } finally {
MessageBox.Show( "exiting the try/catch block" ); }

The 'finally' block is guaranteed to be executed whether there is an exception or not. If there is NO
exception raised within the 'try' block, the 'finally' block is executed after executing the last statement within
the try block.

If an exception is raised within the 'try' block, then 'catch' block is executed. After executing the last
statementin the 'catch' block, the 'finally' block is executed.

The purpose of the 'finally' block is to provide a way to perform any cleanup operations. For example, if you
are opening a file and performing some file operations within the 'try' block,
you can do the file closing within the 'finally' block. This will ensure that the file is closed even if there is an
exception during file operations.
How to throw an Exception in .Net

.Net supports structured exception handling. You can create and throw system or custom exceptions using
the 'throw' statement. Author: Tony John

HP GDIC

Posted Date: 09 Mar, 2004


.NET Classes used :

System.IO.FileNotFoundException
System.Exception

Using 'throw' statement to raise an exception

Remember the old days where you will get an error code back when you call a COM object and then search
all over the Google to find what this stupid number mean ?

Those days are gone. No more error codes and magic numbers. In .net, if there is an error, you will get an
exception.

NOTE:
Exception/Error is different from 'false'. If you have a method called 'IsNumber()', it should return false if
the passed parameter is not a number, and not an Exception. Exceptions should be raised only if there is an
unexpected error.

How to Raise an Exception ?

You can raise an exception using the 'throw' statement. In your code, you can check for error conditions and
create and throw appropriate exceptions. The caller of the method need not check for error codes returned
from a method. See the following sample code :
private void SaveData( Object data ) { if ( data == null ) {
// Create and throw an exception of type 'ArgumentNullException'. throw new
ArgumentNullException(); } }

You can also re-throw a caught exception using the 'throw' statement.
try { // Some code that may cause an exception. // ... } catch
( Exception ex ) { // Re-throw the same exception so that the caller of this method
// can catch this exception. throw; }

The above code will simply re-throw the exception which was caught. This would be useful if you want to
perform some error logging and then re-throw the exceptions.

But it is always a good practise to add more information to the exception before you re-throw it. For this,
you can create a new exception and embed the caught exception as 'inner-exception' in the new exception
you create.
try { // Some code that may cause an exception. // ... } catch
( System.IO.FileNotFoundException ex ) { // Create a new exception with additional
information and embed // the original exception as inner-exception. throw new
System.IO.FileNotFoundException( "An error occurred in the method 'SaveData()'. The
file 'C:\app.txt' doesn't exists.", ex ); }

The 'throw' statement can be used to throw custom exceptions also. It is a good practise to create
custom exceptions for your application and throw custom exception in case of application errors. For
example, you can have custom exception classes like 'DataFileNotFoundException',
'UserNotSignedInException' etc.

How to throw an Exception


Author: Tony
in .Net John
HP GDIC
Posted Date: 09 Mar, 2004
.Net supports structured exception handling. You can create and throw
system or custom exceptions using the 'throw' statement.

.NET Classes used :


System.IO.FileNotFoundException
System.Exception

Using 'throw' statement to raise an exception

Remember the old days where you will get an error code back when you call a COM object and then search
all over the Google to find what this stupid number mean ?

Those days are gone. No more error codes and magic numbers. In .net, if there is an error, you will get an
exception.

NOTE:
Exception/Error is different from 'false'. If you have a method called 'IsNumber()', it should return false if the
passed parameter is not a number, and not an Exception. Exceptions should be raised only if there is an
unexpected error.

How to Raise an Exception ?

You can raise an exception using the 'throw' statement. In your code, you can check for error conditions and
create and throw appropriate exceptions. The caller of the method need not check for error codes returned
from a method. See the following sample code :

private void SaveData( Object data )


{
if ( data == null )
{
// Create and throw an exception of type
'ArgumentNullException'.
throw new ArgumentNullException();
}
}

You can also re-throw a caught exception using the 'throw' statement.

try
{
// Some code that may cause an exception.
// ...
}
catch ( Exception ex )
{
// Re-throw the same exception so that the caller of
this method
// can catch this exception.
throw;
}

The above code will simply re-throw the exception which was caught. This would be useful if you want to
perform some error logging and then re-throw the exceptions.

But it is always a good practise to add more information to the exception before you re-throw it. For this, you
can create a new exception and embed the caught exception as 'inner-exception' in the new exception you
create.

try
{
// Some code that may cause an exception.
// ...
}
catch ( System.IO.FileNotFoundException ex )
{
// Create a new exception with additional information
and embed
// the original exception as inner-exception.
throw new System.IO.FileNotFoundException( "An error
occurred
in the method 'SaveData()'. The file 'C:\app.txt'
doesn't exists.", ex );
}

The 'throw' statement can be used to throw custom exceptions also. It is a good practise to create
custom exceptions for your application and throw custom exception in case of application errors. For example, you can have
custom exception classes like 'DataFileNotFoundException', 'UserNotSignedInException' etc.
________________________________________________________________________________________________________

Exception handling in .Net Author: Tony


John
HP GDIC
An exception is an error condition or unexpected behavior encountered by Posted Date: 09 Mar, 2004
an executing application during runtime. .Net supports structured error
handling.

.NET Classes used :

System.Exception
System.IO.FileNotFoundException
System.DivideByZeroException
System.IO.File

Definition :

"An exception is an error condition or unexpected behavior encountered by an executing application during
runtime."

Exceptions can occur in programs due to various reasons including bad logic, non-availability of operating
system resources, network failure, attempt to access invalid objects etc. When the code which has a
problem is executed, it 'raises an exception'.

For example, if network connection to the database server is broken when you are accessing some data,
.Net Framework will raise an exception. Or, if you are attempting to read a File which do not exist, .Net
framework will raise a 'File Not Found' exception.

When an exception is raised in the system, if it is not 'handled', it will lead to program termination. This will
give a bad experience for the user and may lead to loss or corruption of data.

.Net framework provides very good, structured exception handling mechanism. In .Net, an 'exception' is a
class, which is derived from System.Exception class. When there is a problem ('exception') in the code, .net
runtime creates an 'exception' object which contains information about the nature of the problem. If you
handle the exception in the code, you will receive this exception object which contains information about the
nature of the error. This information can be used to show a friendly message to the user or to recover from
the error and continue executing the program.
How to Handle Exceptions in C#

Exceptions are handled in .Net using the 'try/catch/finally' statements. The code which 'may cause an
exception' is enclosed within a 'try' block as shown below:

try
{
// some code that may cause an exception.
}

Now we are safe. You have protected your code. If an exception occurs in the code enclosed within the 'try'
block, you can handle it. To handle an exception, attach a 'catch' block to the 'try'.

try
{
// some code that may cause an exception.

// If an exception occurs in the above code, the


execution will not continue within the
// 'try' block. Instead, the execution will jump to the
'catch' block.
}
catch (Exception ex)
{
// If an exception occurs in the try block, this block
will be executed.
// Write the error handling code here.
}

When an exception is raised, the control of execution is transfered to the 'catch' block. You can write the
error handling code here. Yo may show a friendly message to the user or try to recover from the error by
writing appropriate code.

In the above case, we are blindly catching all exceptions. You may change the 'catch' block slightly to handle
only specific types of exceptions.

In the following example, we are attempting to copy a file to a new name. If the file doesn't exists, it will
throw a 'FileNotFound' exception.

try
{
System.IO.File.Copy ( "C:\\test.txt", "C:\\new.txt" );
}
catch ( System.IO.FileNotFoundException ex )
{
MessageBox.Show( ex.Message );
}

In this case, if 'c:\test.txt' doesn't exists, then it will throw an exception. We are catching this specific type of
exception in the 'catch' block and displaying the 'exception message' to the user.

NOTE:
It is not a good idea to display the raw exception message to the user. Instead, show a friendly message to
the user and log the actual exception message to some log file for trouble shooting purposes.

In the above example, we are handling only a specific type of exception :


'System.IO.FileNotFoundException'. If any other type fo exception occurs in the above code, it is not
handled and will lead to program termination. For example, if an exception of type 'OutOfMemoryException'
occurs, it is not handled and program will terminate.

To catch all types of exceptions, specify the root 'Exception' in the 'catch' block. But it is a bad
practise to catch all exceptions. You should catch only specific exceptions which are expected in teh specific
code block. For example, if you are accessing a file, you may catch 'System.IO.FileNotFoundException' and
if you are performing mathemtical operations, you may catch 'System.DivideByZeroException' exception.
Also, you can create and throw custom exceptions. If the code you are calling is expected to throw any
custom exception, you may catch those custom exceptions.

Handling more than one Exception

You can have zero or more 'catch' blocks attached with each 'try' blocks. Depending on the type of the
exception thrown, appropriate 'catch' block will be executed.

try
{
// some code that can throw exception.
}
catch ( System.IO.FileNotFoundException ex )
{
MessageBox.Show( ex.Message );
}
catch ( System.DivideByZeroException ex )
{
MessageBox.Show( ex.Message );
}

The above code sample handles two specific exception types : FileNotFoundException &
DivideByZeroException. When an exception occurs within the 'try' block, it will first check wether it is of type
'FileNotFoundException'. If so, it executes that catch block. If not, it will check whether it is of type
'DivideByZeroException'. If the exception doesn't belong to one of these types, it will not be handled.

A root exception matches all exceptions derived from it. Since all exceptions are derived from
System.Exception, if you catch 'System.Exception', it will catch all exceptions.

try
{
// some code that can throw exception.
}

catch ( System.Exception ex )
{
MessageBox.Show( ex.Message );
}
catch ( System.IO.FileNotFoundException ex )
{
MessageBox.Show( ex.Message );
}
catch ( System.DivideByZeroException ex )
{
MessageBox.Show( ex.Message );
}

In the above code, 'catch ( System.Exception ex )' will catch all exceptions including
'FileNotFoundException' and 'DivideByZeroException'. So even if the 'DivideByZeroException' occurs, it will
be handled by the first catch block. So, if you handle more than one exception, the inherited ones should be
handled first. If catching 'System.Exception', it should be the last 'catch' block.

Using the 'finally' statement to perform cleanup operations


try
{
// some code that can throw exception.
}
catch ( System.Exception ex )
{
MessageBox.Show( ex.Message );
}
finally
{
MessageBox.Show( "exiting the try/catch block" );
}

The 'finally' block is guaranteed to be executed whether there is an exception or not. If there is NO exception raised within the 'try'
block, the 'finally' block is executed after executing the last statement within the try block.

If an exception is raised within the 'try' block, then 'catch' block is executed. After executing the last statementin the 'catch' block,
the 'finally' block is executed.

The purpose of the 'finally' block is to provide a way to perform any cleanup operations. For example, if you are opening a file and
performing some file operations within the 'try' block,
you can do the file closing within the 'finally' block. This will ensure that the file is closed even if there is an exception during file
operations.

Dynamically creating
ASP.NET controls from the Author: Tony
John
code behind files
HP GDIC
Posted Date: 15 Dec,
2004
This article demonstrates how you can dynamically generate
ASP.NET controls in runtime using the code behind code and
access the properties of the dynamically created controls.
.NET Classes used :

Dynamically creating ASP.NET


controls
ASP.NET is a very powerful and flexible technology, allowing programmers to develop
sophisticated web applications within a short period of time. It is so easy to drag and drop
controls in a web form and start writing the business logic in the code behind file.
Ofcourse, dragging and dropping controls from the toolbox is the easiest approach. But
sometimes we may need to generate ASP.NET controls in the server side using the
VB.NET or C# code. For example, consider a case where you are developing an
application where you want to display a list of checkboxes to the user, depending on the
number of records in a database table. In this case, you cannot drag and drop few
checkbox controls, because you will not know how many checkboxes you are going to
need until you retrieve the records from the database.

In this article, I will discuss how you can create ASP.NET controls at runtime using C#
syntax. You can easily convert this to VB.NET syntax with little effort.
Create a new ASP.NET web application using Visual Studio.NET. It will create a sample
web page with the name webform1.aspx. Let us use this page for our experimentation.
Drag and drop a panel control into the webform. We will dynamically generate a
checkbox and add to this panel.

Double click on the webform1.aspx page. This will add a page load event handler in the
code behind file. Add few lines of code in the Page_Load event handler as shown below:
private void Page_Load(object sender, System.EventArgs e)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "chkDynamicCheckBox";
_checkbox.Text = "This is a dynamically generated checkbox";

Panel1.Controls.Add (_checkbox);
}

The above code will create a checkbox dynamically and add to the panel in the form.
Using this approach, you can create any other ASP.NET control during runtime and add
to the form.

How to specify a position for the


dynamically dynamically created
ASP.NET control?
The most common method is to use <table> to position controls and text in html. In our
case, since we are dynamically generating the controls, we may want to use ASP.NET
table control to dynamically create rows and cells in the table and add our dynamic
controls into it.
Drag and drop an ASP.NET table control into the form and give it the name 'tblDynamic'.
Now, go back to the Page_Load event handler in the code behind file. The following code
sample will create 5 textboxes and labels. We will create 5 rows and 2 cells in each row
dynamically and add our dynamicaly created textbox/label controls to the table so that
they will be aligned properly and will appear in the page in proper format.
private void Page_Load(object sender, System.EventArgs e)
{
for ( int i = 0; i < 5; i++ )
{
TableRow tr = new TableRow();
// Create column 1
TableCell td1 = new TableCell();
// Create a label control dynamically
Label _label = new Label();
_label.ID = "lbl" + i.ToString();
_label.Text = "Enter Value " + i.ToString();
// Add control to the table cell
td1.Controls.Add(_label);

// Create column 2
TableCell td2 = new TableCell();
TextBox _text = new TextBox();
_text.ID = "txt_" + i.ToString();
// Add control to the table cell
td2.Controls.Add(_text);
// Add cell to the row
tr.Cells.Add(td1);
tr.Cells.Add(td2);
// Add row to the table.
tblDynamic.Rows.Add(tr);
}
}

How to access the dynamically created


ASP.NET controls?
If we drag and drop controls to the web form, the designer automatically generates some
code in the aspx page, gives an id to the control and creates the required declarations in
the code behind file. This allows us to easily access the control from code behind file and
set/get any of it's properties.

But what will happen to the controls created during runtime? How can we access it's
properties?

The easiest way to access these dynamically created textboxes is, iterate through all
controls in the form and check if it is textbox. In the above example, we have prefixed the
ID with "txt_" and then appended the serial number to it for all dynamically generated
controls.

Use the following recursive function to iterate through the list of all controls in the form.
We are passing the form itself as parameter to the the function. The function will iterate
through all children of the passed control and checks if the child control is a textbox and
if the id starts with "txt_". If it matches, it sets the Text property to "You Got It!"
void IterateControls(Control parent)
{
foreach (Control child in parent.Controls)
{
if
(child.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
&& child.ID.IndexOf("txt_") == 0)
{
TextBox textbox = (TextBox)child;
textbox.Text = "You Got It !";
}

if (child.Controls.Count > 0)
{
IterateControls(child);
}
}
}

How to test it?


Add the above method to your code behind file. Drag and drop a button control to the
form and double click on it to create a button clicked event handler. Call the above
method from the button click event handler as shown below:
IterateControls(this);

Now, run the application and see. When you launch the application, it will dynamically create 5 textboxes
and when you click on the button, it will populate the value 'You Got It !" in all the dynamically created
textboxe controls.

SQL Example: Stored Procedure with


Input and Output Parameters

Code Sample Category: SQL


Language: SQL
Author: Venkatesan Prabu Jayakantham

HCL Technologies

Posted Date: 29 Sep, 2007 Import Namespaces :


.NET Classes used :
Stored Procedure with Input and
Output Parameters
Below is the stored procedure which holds two parameters as input and one parameter as
output. Based on the count variable the return value is taken off.

CREATE PROCEDURE WITHPARAMETER_AND_RETURN_VALUE


(
@EMPID INT,
@IDVAL INT,
@RETURNVALUE INT =0 OUT
)
AS
DECLARE @COUNT INT
BEGIN
SELECT @COUNT=COUNT(*) FROM JOINTABLE WHERE EMPID=@EMPID AND
IDVAL=@IDVAL
IF(@COUNT >0)
BEGIN

SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
ELSE
BEGIN
SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
END

EXEC WITHPARAMETER_AND_RETURN_VALUE 1,2


reate and Use a Hashtable

This sample demonstrates working with a very efficient and useful


collection in .Net - Hashtable.
Author: Tony John

HP GDIC

Posted Date: 02 Feb, 2004


.NET Classes used :
# System.Collections
Hashtable stores data as Key Value pairs. It is very efficient when you
have lot of data and need to search for keys.

Following sample shows how to add Key/Value pairs to the Hashtable.

Hashtable table = new Hashtable();

table.Add("John", "2003");
table.Add("Tom", "1975");
table.Add("Teena", "1988");

You can retrieve the value from hashtable using the indexer.

string val = table["John"].ToString();

Forms Authentication used


in real time Author: Pradeep

Posted Date: 14 Dec, 2006

This article explains how forms authentication implemented in real time and
how to give the permissions for users and admins. by roles

.NET Classes used :

Username:
type="text"/>

Password: <BR
/>

Text="Login"/>

Visible="false"/>
protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

// Get the stored user-data, in this case, our roles


string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}

loginUrl="login.aspx"
protection="All"
path="/"/>

Creating a Custom Pager for GridView

Introduction

The inbuilt pager of GridView control is limited to only few navigation options
(numbers, next-previous etc.). At times you need to customize the pager to suit your
applications requirement. One of the common requirements is the ability to jump to a
particular page of the grid. This is commonly achieved by showing a DropDownList in
the pager containing available pages. The user can then jump directly to the required
page. In this article I am going to illustrate how such a custom pager can be created for
your GridView control.

Requirement

To get a clear idea of our requirement let's see how the page should look like. The
following figure shows a GridView with custom pager.
As you can see the inbuilt pager of the GridView has been replaced by a DropDownList.
The DropDownList contains all the pager numbers. User can then select a particular page
number to jump to that page.

Solution

In order to create a custom pager for a GridView, you need to design its PagerTemplate.
The PagerTemplate governs the paging system of the GridView. By default the
PagerTemplate is empty. To understand how it works, create a new web site in Visual
Studio. We use Customers table from Northwind database for our example. Drag and
drop two SQL data source controls on the default web form. Configure one of the SQL
data source controls to select CustomerID, CompanyName, ContactName and Country
columns of the Customers table. This SQL data source will be bound with a GridView
control.
Configure the other SQL data source control to select total number of customers
(COUNT(*)) from the Customers table. This SQL data source will be used to determine
the total number of pages in the DropDownList.

Set the DataSourceID property of the GridView to SqlDataSource1. Also, set its
AllowPaging property to true. Now design the PagerTemplate of the GridView as shown
below:
The PagerTemplate consists of a Label control and a DropDownList control. Set the
AutoPostBack property of the DropDownList control to true. We need to populate this
DropDownList with available pages. We do this by handling RowCreated event of the
GridView. The RowCreated event is raised when each and every row of the GridView
(including header, footer and pager row) is being created on the server. Add the following
code in the RowCreated event handler.

protected void GridView1_RowCreated(object sender,


GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)e.Row.FindControl
("DropDownList1");
SqlDataReader reader = (SqlDataReader)SqlDataSource2.
Select(DataSourceSelectArguments.Empty);
if (reader.HasRows)
{
reader.Read();
int recordcount = reader.GetInt32(0);
int pagecount = recordcount / GridView1.PageSize;
for (int i = 1; i <= pagecount; i++)
{
ddl.Items.Add(i.ToString());
}
}
ddl.SelectedValue=(GridView1.PageIndex+1).ToString();
}
}

The code first checks the type of row being created using RowType property. The
RowType property is of type DataControlRowType and the value of Pager indicates that
the pager is being created. It then gets a reference of the DropDownList from the
PagerTemplate using FindControl() method. Then the total number of customer records
are obtained using SqlDataSource2 control. Recollect that we configured SqlDataSource2
to execute COUNT(*) query against the Customers table. The Select() method of SQL
data source control executes the SELECT query and returns its results as an
SqlDataReader. The return value of the Select() method is determined by
DataSourceMode property of the SQL data source control. The two possible return types
are - DataReader and DataSet. If the SqlDataReader contains any rows the total number
of customers are fetched. The total number of pages are then calculated based on the
PageSize property of the GridView (default is 10). Then items are added to the
DropDownList depending on the total number of pages. Finally, SelectedValue property
of the DropDownList is set to the current page index. Note that GridView page index
starts from 0 but we display page numbers starting from 1 and hence we need to adjust
the SelectedValue property by 1.

When the user selects a page number in the DropDownList we need to change the current
page displayed in the GridView. This is done by handling SelectedIndexChanged event of
the DropDownList.
protected void DropDownList1_SelectedIndexChanged
(object sender, EventArgs e)
{
int index = int.Parse(((DropDownList)sender).
SelectedValue) - 1;
GridView1.PageIndex = index;
}

The code retrieves the SelectedValue from the DropDownList and sets PageIndex
property of the GridView. The PageIndex property determines the current page index of
the GridView.

That's it! Run the web form and you should see the custom pager in action.

Delegates are basically type safe functional pointers.

Basically the delegates encapsulate the reference of methods/events.

Method/Events is added to the object at runtime.

Event Handling in Delegates:

Steps:

1. Declare a Delegate

public Delegate void Delegate_Name (Parameter a, Parameter b)

2. Event are created using the Delegate

Public event(keyword) EventHandler NotifyP

3. In a particular method event is fired explicitly

4. Method is attached to delegate

Obj .NotifyP += new EventHandler(MO)

Methods attached to the delegate should have the same signatures as that of the delegate.

Both static and nonstatic methods can be called.


More examples

Grd.mousedown += MouseEventHandler (this.mouse_down)

Here the MouseEventHandler is a delegate.

When the mouse down event fires mouse_down method is called. Here when the mousedown event is fired
new object of delegate is created and function that is required to be called is passed in it.

Methods:

Example:

BaseClass

1. create a delegate

public Delegate bool DelegateD(object a1,object b1)

2. Method that is using a delegate.(delegate object)

3. method using the delegate object is actually using the method of child class.

Child class:

1 create the object of base class.

2 create the object of delegate.


Delegated obj = new delegated(MethodToAttach)

3 MethodToAttach (object A,object b)

Sql Server Transaction Isolation Levels

This article explains about Transaction Isolation Level in Sqlserver and their types and how to set the
suitable Transaction Isolation Level

Author: Padma

MNC

Posted Date: 19 Jan, 2008

.NET Classes used :

This article explains about Transaction Isolation Level in Sqlserver and their types and how to set the
suitable Transaction Isolation Level

This article explains about Transaction Isolation Level in Sqlserver and their types and how to set the
suitable Transaction Isolation Level

When we need to isolate a data for a transaction and shield that data from other transaction we will go for
maintaining isolation level. This shielding is done by attaining locks. What locks should we set and how to
do it for the transaction is determined by maintaining the isolation level.

There are four Isolation levels


Read Uncommitted

Read Committed

Repeatable Read

Serializable

In Sql Server 2005, there are two new isolation levels have been introduced. They are

Read_Committed_Snapshot

Allow_SnapShot_Isolation

Read Uncommitted

This isolation level is also called dirty read , because this is the lowest isolation level and it could ensure
only that a physically corrupt data will not be read. It creates all concurrency problems, non repeatable reads
.

You can expect higher level of concurrency by setting the Isolation Level to Read Uncommitted but you
may face all concurrency related problems.

Read Committed:

This is the default Isolation level of Sql Server. It prevents dirty reads and concurrent related problems
because it make ensures that the statements cant read data that has been modified but not committed by
other transactions and it doesn’t ensure that the data will not be changed before the end of the transaction.

Repeatable Read:

It won’t release the shared lock once the record is read unlike Read Committed. Shared lock will be sited on
all the data read in the transaction and will be there till the transaction is over. It prevents from other
transactions by modifying the rows that have been used by the current transaction.

It allows phantom reads but doesn’t permit dirty reads and non repeatable reads.
SERIALIZABLE

It ensures that other transaction can not modify data that has been read by the current transaction till the
current transaction is over. Range Locks will be placed based on the search criteria that have been used. It
avoids all concurrency related problems.

This is the highest Transaction Isolation Level

When this isolation level is maintained the phantom read won’t happen

Please have look into the following sample for Serializable Read

Create PROCEDURE SP_Insert_Material_Master

@MAT_Code as nvarchar(20),

@MAT_Name as nvarchar(50),

AS

BEGIN
SET NOCOUNT ON

DECLARE @intError_Count AS INTEGER

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRANSACTION

SET @intError_Count = 0

Insert Into [Material_Master]

[MAT_Code] ,

[MAT_Name] ,

VALUES

@MAT_Code ,

@MAT_Name ,

IF @@ERROR <> 0

BEGIN

SET @intError_Count=@intError_Count+1

END
IF @intError_Count= 0

BEGIN

COMMIT TRANSACTION

END

ELSE

BEGIN

ROLLBACK TRANSACTION

END

SET NOCOUNT OFF

END

Potrebbero piacerti anche