Académique Documents
Professionnel Documents
Culture Documents
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.
How to perform these 2 events ..first javascript(for checking textbox's empty) has to perform and next
submit to database.
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
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>
Send Coding for to use sqlcommand builder in ASP.NET using C# with some sample C#
program
// 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;
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
string message =
"<html><body><img alt=\"image alternate text\"
src=\"cid:title\" /></body></html> ";
//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
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.
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 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.
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
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.
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 + “’”;
This will delete all the rows from the products table
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.
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
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.
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
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).
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.
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.
Example:
C:\Test\bin\Debug>peverify Test.exe
Code Sample:
//This code fails the verification
unsafe
{
int* ptr = (int*) 0;
*ptr = 1000;
}
C:\>peverify C:\Test\bin\Debug\Test.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.
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:
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.
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.
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.
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
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.
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.
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.
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.
Code Sample:
//This code fails the verification
unsafe
{
int* ptr = (int*) 0;
*ptr = 1000;
}
C:\>peverify C:\Test\bin\Debug\Test.exe
Summary
Type safety is a simple concept and it will help the developers in developing better
applications if they understand this concept well.
How CLR boxes value types to reference types... In short, Why is boxing required?
Author: Sidhartha Gundavarapu
Microsoft
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.
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...
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
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
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>
MSg.Attachments.Add(mAtt)
SmtpMail.Send(MSg)
Response.Write(" Done")
End Sub
End Class
Introduction
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.
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.
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 :
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.
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
Login ---> Authenticate with active directory users --> Authenticate with Form based
authentication with database.-->
active directory.
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
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
step 2 :
opens a dialouge box then select the System.DirectoryServices after selecting check your
web config it will shows you this
under the .
Come to your login page's code behind file then import System.DirectoryServices
Imports System.DirectoryServices
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
step 5 :
STEP 6 :
Summary
I hope this article will helps you to create more secure web applications
Thanks
Gaurav Sharma
Introduction:
Syntax:
The syntax of using generics is:
//usage with classclass MyClass< T >{ ...}
//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:
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
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
please note that only a default constructor can be used in the constraints and using any
parameterised constructor will be a compilation error.
Points to ponder
Though this list seems to be insufficient considering the complex scenarios, these can be
mixed appropriately.
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
Login ---> Authenticate with active directory users --> Authenticate with Form based
authentication with database.-->
active directory.
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
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
step 2 :
opens a dialouge box then select the System.DirectoryServices after selecting check your
web config it will shows you this
under the .
Come to your login page's code behind file then import System.DirectoryServices
Imports System.DirectoryServices
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
step 5 :
STEP 6 :
I hope this article will helps you to create more secure web applications
Thanks
Gaurav Sharma
}
}
i make the elements of the first colum as a link and on clicking that link a new popup will
open.
</SCRIPT>
}
}
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
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
http://forums.asp.net/p/1139250/1838215.aspx
Code Sample Category: C# Syntax
Language: C#
Author: Md Zafar Imam
System.Windows.Forms.Application
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.
private Program()
{
m_inputForm = new frmInputForm();
}
[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
System.Collections.Generic
Anonymous Methods in C#
LogicaCMG
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
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.
if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}
myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");
myStore.Delete(2);
}
LogicaCMG
System.IO.StreamWriter
System.Windows.Forms.Form
System.Windows.Forms.MessageBox
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.
//Static constructor
static MyEventLogManager()
{
//Intiating the stream writer
MessageBox.Show("Static constructor invoked..");
sw = new System.IO.StreamWriter("C:\\project.log",true);
}
LogicaCMG
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.
//Static constructor
static MyEventLogManager()
{
//Intiating the stream writer
MessageBox.Show("Static constructor invoked..");
sw = new System.IO.StreamWriter("C:\\project.log",true);
}
}
Code Sample Category:
Exceptions
Language:
C#
LogicaCMG
using System;
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :
# System.Exception
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox
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.
Implementing the “LoginManager” class, which is used to validate the current user
}
Code Sample Category:
Automation
Language:
C#
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 MSExcel()
{
//Gets the type of the Excel application using prorame id
ExcelType = Type.GetTypeFromProgID("Excel.Application");
}
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);
}
}
LogicaCMG
using System;
using System.Windows.Forms;
using System .NET Classes used :
# System.Attribute
# System.Windows.Forms.Form
# System.Windows.Forms.MessageBox
# System.Exception
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.
I have created following Attribute class which is inherited from “Attribute” class
The following “Store” class methods have the “AllowedRoles” attributes, with the role
name parameters.
//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.
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#
LogicaCMG
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
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
LogicaCMG
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
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
LogicaCMG
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
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.
The bellow code is used to access the properties of the Studnet class
}
Code Sample Category:
Event Handling
Language:
C#
LogicaCMG
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
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);
if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}
myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");
myStore.Delete(2);
}
LogicaCMG
using System.Windows.Forms;
using System.Windows.Forms .NET Classes used :
# System.Windows.Forms.Form
# System.Windows.Forms.Button
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();
}
LogicaCMG
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
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)
base.OnPaint(e);
}
}
//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#
LogicaCMG
using System.Diagnostics;
using System.Windows.Forms .NET Classes used :
# System.Diagnostics.EventLog
# System.Windows.Forms.Form
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.
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.
}
public static void AddEvent(string Message)
{
//Log a information to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Information);
}
//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
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.
Methods:
ShowDetails()
StartFly()
IncreaseSpeedBy(increment value)
StopFly()
Hi,
I my project how can we convert date from mm/dd/yy formate to DD/mm/yy formate
lblTime.Text = (DateTime.Now).ToShortDateString();
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
lblTime.text=DateTime.Now.ToString("dd/MM/yy");
Code Sample Category: Debug
Language: C#
Author: critic
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.
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
System.Environment
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
using System.Net.NetworkInformation;
using System.Net.NetworkInformation .NET Classes used :
System.Net.NetworkInformation.Ping
System.Net.NetworkInformation.PingReply
System.Net.NetworkInformation.PingException
This code snippet shows how to ping a computer or device in the network and check if they
are accessible.
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!
Session..Add(key,value);
Example:
Session.Add("Name",TextBox1.Text);
returnValue = Session[key];
Example:
string userName = Session["Name"].ToString();
Regards,
Zabi.
Author: shwetakeshri
infitech global.com
Hi,
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
namespace TestCollections
{
public class ListWithChangedEvent : System.Collections.ArrayList
{
public event System.EventHandler Changed;
namespace TestEvents
{
using TestCollections;
class EventListener
{
private ListWithChangedEvent m_list;
class Test
{
static void Main()
{
ListWithChangedEvent list = new ListWithChangedEvent();
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
# System.Web
using System.Web;
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
# using System.Configuration;
# using System.Data.SqlClient ;
# using System.Data.SqlTypes;
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
Sonata
# System.Data.SqlClient
Gridview : Displays the values of a data source in a table where each column represents a field and each row
represents a record.
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.
<H2><u>//Sorting Event:</u></H2>
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
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
{
class DelegateHandler
{
class Program
{
static void Main(string[] args)
{
DelegateHandler dh = new DelegateHandler();
ArrayList al = dh.Get();
Console.ReadLine();
}
}
}
C# Example: How to record voice from microphone?
CTS,Hyderabad
using Microsoft.VisualBasic;
using System.Runtime .NET Classes used :
Microsoft.VisualBasic.Devices;
Microsoft.VisualBasic;
System.Runtime.InteropServices;
using Microsoft.VisualBasic.Devices;
using Microsoft.VisualBasic;
using System.Runtime.InteropServices;
3. Create three Buttons and given the below name and text for the buttons.
1. Record
2. SaveStop
3. Read
CTS,Hyderabad
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.
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#?
CTS,Hyderabad
SpeechLib.SpVoice
Hi Guys,
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.
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;
HP GDIC
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.
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.
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;
}
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
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.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 :
stream.Close();
The above code sample will serialize the arraylist 'itemsToSerialize' into the file 'MyApplicationData.dat'.
The objects serialized using binary formatter can be deserialized the same way.
Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );
stream.Close();
The above sample will read the file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized'.
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.
How to create your own type of List & ArrayList Author: amit khosla
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];
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.
System.Xml
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
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
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
using System.Configuration;
using System.Data.SqlClient ;
using System.Data.SqlTypes;
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
' 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
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
System.Web
using System.Web;
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
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.
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.
At this point you ready with sample COM component VBClass.dll, now create Run Time Callable Wrapper
using .Net tool called TBLIMP.
Bin Directory
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.
Summary
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
Points to consider when you migarate your code from VB 6.0 to VB.Net
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 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
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:
is upgraded to:
Property MyProperty() As Short Get MyProperty = m_MyProperty End Get Set
m_MyProperty = Value End SetEnd Property
Others
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
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
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
Listing 1 - Synchronous
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:
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 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.
· 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.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.
Refer to the example code with this article to have a better understanding.
The above code uses WaitHandle.WaitAny() method and populates data asynchronously and binds 3
gridviews. If we see this line:
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.
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.
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
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)
Aspire Systems
In this section of article I will be telling about structured exception handling, try...
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
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
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
Example
In the above example if you see i have include the statement fw.writeline(a/b) where are two
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
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
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
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
{
}
}
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()));
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
# Imports System.IO
# Imports System.Xml
# Imports System.Text
# Imports System.data
# Imports System.Xml.Xsl
# Imports System.Xml.XPath
Form Design
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 also have a label which displays the status of the transformation (success or failure)
Internal Logic
Sub main()
Dim frm As New frmXML
frm.ShowDialog()
End Sub
Defining the strings needs for input, output and the style sheet
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
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 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";
}
}
}
}
}
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";
}
}
}
}
}
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 myCustomControlButton()
{
}
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);
}
}
C# Example: Multi-Cast delegates
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;
result = pgm.calci(12.2m,13.8m);
Console.WriteLine("Subtraction = " + result);
Console.ReadLine();
}
}
}
C# Example: Handling events & delegates with code 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 DelegateHandler()
{
// Registering the Changed method to event
OnAdditionToList += new AddEvent(Changed);
}
}
class Program
{
static void Main(string[] args)
{
DelegateHandler dh = new DelegateHandler();
ArrayList al = dh.Get();
Console.ReadLine();
}
}
}
Concurrency Control Using ADO.NET
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
HP GDIC
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.
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.
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.
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.
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
System.IO.FileNotFoundException
System.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.
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.
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.
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 :
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.
________________________________________________________________________________________________________
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.
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.
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.
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.
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 :
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.
// 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);
}
}
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);
}
}
}
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.
HCL Technologies
SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
ELSE
BEGIN
SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
END
HP GDIC
table.Add("John", "2003");
table.Add("Tom", "1975");
table.Add("Teena", "1988");
You can retrieve the value from hashtable using the indexer.
This article explains how forms authentication implemented in real time and
how to give the permissions for users and admins. by roles
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;
loginUrl="login.aspx"
protection="All"
path="/"/>
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.
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.
Steps:
1. Declare a Delegate
Methods attached to the delegate should have the same signatures as that of the 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
3. method using the delegate object is actually using the method of child class.
Child class:
This article explains about Transaction Isolation Level in Sqlserver and their types and how to set the
suitable Transaction Isolation Level
Author: Padma
MNC
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.
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.
When this isolation level is maintained the phantom read won’t happen
Please have look into the following sample for Serializable Read
@MAT_Code as nvarchar(20),
@MAT_Name as nvarchar(50),
AS
BEGIN
SET NOCOUNT ON
BEGIN TRANSACTION
SET @intError_Count = 0
[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
END