Tuesday, 18 December 2012

Define Maximum Value of a multiline TextBox in Asp.net Application

Asp.Net gives invariably a cool and very good built properties in controls like MaxLength property for a TextBox which doesn’t allows a user to enter more than the specified length. But this property do not work well with a MultiLine TextBox (TextMode= MultiLine).

To resolve this problem one can either use a JavaScript function to check the number of characters entered in the MultiLine TextBox and then return false in case the value exceeds the developers expected length.

The other and a much simpler way to do this is to use a RegularExpressionValidator Control.

This can be done in following steps:-
1. Drag and drop a RegularExpressionValidator and set its ControlToValidate property to the multiline TextBox.

2. In the ExpressionValidation write the expression :
^[\s\S]{“Your Minimum Length,”Your Maximum Length”}$

Example:- ^[\s\S]{3,10}$

where ^ denotes start of string, \s\S denotes spacial and non-spacial characters and {3,10} denotes minimum of three and a maximum of 10 characters can be entered. $ represents the end of string

Friday, 14 December 2012

Disable browser back button after authentication in asp.net application

To disable back button After login 
Place this code in the HTML head section of  Login.aspx  page

    <script type="text/javascript" language="javascript">
        function preventBack() { window.history.forward(); }
        setTimeout("preventBack()", 0);
        window.onunload = function () { null };


Tuesday, 4 December 2012

Monday, 19 November 2012

Debugging Stored Procedures in Visual Studio 2005

This article walks through the basics of debugging stored procedures using Visual Studio 2005. It covers breakpoints, watches and stepping through code. It was written by Chris Rock and includes his very unique sense of humor.
One of my favorites activities while working is debugging. A little weird yes, but I’ve always had an affinity towards taking things apart and putting them back together. I haven’t always had success. As a kid I destroyed many toys and pieces of furniture (office chairs) just to find out how they work. I am a curious person by nature and like to figure out how something works OR why something isn't working. Alright, enough about my lame personality.
Before I was enlightened to this world of debugging stored procedures I used the archaic "print" statements to debug stored procedures. When I found out that I didn't have to do that anymore I cried tears of joy. Ok... I didn't actually "cry" but I did mutter something like "That's cool..." (I told you I was lame!) That was when Query Analyzer added the ability to debug stored procedures. Debugging stored procedures has come a long way since the early versions and I'd like to show how to accomplish this very cool feature in Visual Studio 2005.
I suggest that you take a look at http://msdn2.microsoft.com/en-us/library/s4sszxst(VS.80).aspx to verify that you meet the minimum requirements to debug on your SQL server. If you have control of your SQL server box (or SQL is running locally) then you're in good shape and can make any necessary changes. If you're not in control I suggest you buy something for your favorite DBA from thinkgeek.com to get in their good graces and have them assist you in anyway they can! (Note: This probably won't work)
Without further ado let's get started.
The first thing you want to do is add a data connection in the Visual Studio 2005 Servers windows. Right click on "Data Connections" and click on "Add New Connection":
Enter the required connection info in the "Add Connection" dialog and click "Test Connection" to test the connection. If that succeeds, click OK:
After you add the data connection you will be able to see the connection in the Data Connections tree:
We're going to debug "usp_contact_add" in this example (any proc will do, it really doesn't matter what proc YOU use). Drill down until you can see the proc you're debugging under the "Stored Procedures" folder:
Right click on the proc and click "Open". You will see the proc code in the code window:

"Now we debug"

Now that we've figured out how to open the proc we're going to get into actually debugging it. Right click on the proc and click "Step Into Stored Procedure":
A window with all of the parameters for the proc will pop up:
Notice it says "The stored procedure ... REQUIRES the following parameters:" That means you are REQUIRED to fill in the values. Otherwise the debugger will quit right away. That said; click the OK button to step into the procedure. The debugger will automatically stop execution on the first line of code in the stored procedure. When the debugger has stopped execution you'll see a yellow arrow to the left of the line of code:
Depending on how you have your Visual Studio settings you will click either F8 (VB) or F11(C#) to go to the next line of code. The debugger will execute the previous line of code and move to the next line:
Now "nocount" is "set" to "on". Click F8 or F11 again and the insert statement (or whatever line of code the yellow arrow is pointing) will be executed.

Ok... So can we doing anything except watch the debugger work?

Yes, in fact there are several things you can do but I'm going to concentrate on what I use most in VS2005 while debugging stored procedures.
While you're debugging you can view / edit the value of the variables in scope using a few different methods. The first way to view/edit a variable is simply hovering your mouse over the variable:

Ref: http://www.sqlteam.com/article/debugging-stored-procedures-in-visual-studio-2005

Saturday, 17 November 2012

C#.Net Interview Question and Answers

C#.Net Interview Question and Answers
1. What is C#?
C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe programming language.
It will immediately be familiar to C and C++ programmers.
C# combines the high productivity of Rapid Application Development (RAD) languages.
2. What are the types of comment in C#?
There are 3 types of comments in C#.
Single line (//)

ti (/* */)
Page/XML Comments (///).
3. What are the namespaces used in C#.NET?
Namespace is a logical grouping of class.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
4. What are the characteristics of C#?
There are several characteristics of C# are :
Type safe
Object oriented
5. How does C# differ from C++?
C# does not support #include statement. It uses only using statement.
In C# , class definition does not use a semicolon at the end.
C# does not support multiple code inheritance.
Casting in C# is much safer than in c++.
In C# switch can also be used on string values.
Command line parameters array behave differently in C# as compared to C++.
6. What are the basic concepts of object oriented programming?
It is necessary to understand some of the concepts used extensively in object oriented programming.These include
Data abstraction and encapsulation
Dynamic Binding
Message passing.
7. Can you inherit multiple interfaces?
Yes. Multiple interfaces may be inherited in C#.
8. What is inheritance?
Inheritance is deriving the new class from the already existing one.
9. Define scope?
Scope refers to the region of code in which a variable may be accessed.
10. What is the difference between public, static and void?
public :The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.
static :The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.
void : The keyword void is a type modifier that states that the Main method does not return any value.
11. What are the modifiers in C#?
12. What are the types of access modifiers in C#?
Access modifiers in C# are :
internal protect
13. What is boxing and unboxing?
Implicit conversion of value type to reference type of a variable is known as BOXING, for example integer to object type conversion.
Conversion of reference type variable back to value type is called as UnBoxing.
14. What is object?
An object is an instance of a class. An object is created by using operator new. A class that creates an object in memory will contain the information about the values and behaviours (or methods) of that specific object.
15. Where are the types of arrays in C#?
Jagged arrays.
16. What is the difference between Object and Instance?
An instance of a user-defined type is called an object. We can instantiate many objects from one class.
An object is an instance of a class.
17. Define destuctors?
A destructor is called for a class object when that object passes out of scope or is explicitly deleted.A destructors as the name implies is used to destroy the objects that have been created by a constructors.Like a constructor , the destructor is a member function whose name is the same as the class name but is precided by a tilde.
18. What is the use of enumerated data type?
An enumerated data type is another user defined type which provides a way for attaching names to numbers thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2, and so on.
19. Define Constructors?
A constructor is a member function with the same name as its class. The constructor is invoked whenever an object of its associated class is created.It is called constructor because it constructs the values of data members of the class.
20. What is encapsulation?
The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.
21. Does c# support multiple inheritance?
No,its impossible which accepts multi level inheritance.
22. What is ENUM?
Enum are used to define constants.
23. What is a data set?
A DataSet is an in memory representation of data loaded from any data source.
24. What is the difference between private and public keyword?
Private : The private keyword is the default access level and most restrictive among all other access levels. It gives least permission to a type or type member. A private member is accessible only within the body of the class in which it is declared.
Public : The public keyword is most liberal among all access levels, with no restrictions to access what so ever. A public member is accessible not only from within, but also from outside, and gives free access to any member declared within the body or outside the body.
25. Define polymorphism?
Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviours in different instances.
26. What is Jagged Arrays?
A jagged array is an array whose elements are arrays.
The elements of a jagged array can be of different dimensions and sizes.
A jagged array is sometimes called an array–of–arrays.
27. what is an abstract base class?
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.
28. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
29. What is the difference between ref & out parameters?
An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
30. What is the use of using statement in C#?
The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.
31. What is serialization?
Serialization is the process of converting an object into a stream of bytes.
De-serialization is the opposite process of creating an object from a stream of bytes.
Serialization / De-serialization is mostly used to transport objects.
32. What are the difference between Structure and Class?
Structures are value type and Classes are reference type
Structures can not have contractors or destructors.
Classes can have both contractors and destructors.
Structures do not support Inheritance, while Classes support Inheritance.
33. What is difference between Class And Interface?
Class : is logical representation of object. It is collection of data and related sub procedures with defination.
Interface : is also a class containg methods which is not having any definations.Class does not support multiple inheritance. But interface can support.
34. What is Delegates?
Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it.
35. What is Authentication and Authorization?
Authentication is the process of identifying users. Authentication is identifying/validating the user against the credentials (username and password).
Authorization performs after authentication. Authorization is the process of granting access to those users based on identity. Authorization allowing access of specific resource to user.
36. What is a base class?
A class declaration may specify a base class by following the class name with a colon and the name of the base class. omitting a base class specification is the same as deriving from type object.
37. Can “this” be used within a static method?
No ‘This’ cannot be used in a static method. As only static variables/methods can be used in a static method.
38. What is difference between constants, readonly and, static ?
Constants: The value can’t be changed.
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
39. What are the different types of statements supported in C#?
C# supports several different kinds of statements are
Block statements
Declaration statements
Expression statements
Selection statements
Iteration statements
Jump statements
Try catch statements
Checked and unchecked
Lock statement
40. What is an interface class?
It is an abstract class with public abstract methods all of which must be implemented in the inherited classes.
41. what are value types and reference types?
Value types are stored in the Stack.
Examples : bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort.

Reference types are stored in the Heap.
Examples : class, delegate, interface, object, string.
42. What is the difference between string keyword and System.String class?
String keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.
43. What are the two data types available in C#?
Value type
Reference type
44. What are the different types of Caching?
There are three types of Caching :
Output Caching: stores the responses from an asp.net page.
Fragment Caching: Only caches/stores the portion of page (User Control)
Data Caching: is Programmatic way to Cache objects for performance.
45. What is the difference between Custom Control and User Control?
Custom Controls are compiled code (Dlls), easier to use, difficult to create, and can be placed in toolbox. Drag and Drop controls. Attributes can be set visually at design time. Can be used by Multiple Applications (If Shared Dlls), Even if Private can copy to bin directory of web application add reference and use. Normally designed to provide common functionality independent of consuming Application.

User Controls are similar to those of ASP include files, easy to create, can not be placed in the toolbox and dragged - dropped from it. A User Control is shared among the single application files.
46. What is methods?
A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class.
47. What is fields?
A field is a variable that is associated with a class or with an instance of a class.
48. What is events?
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.
49. What is literals and their types?
Literals are value constants assigned to variables in a program. C# supports several types of literals are
Integer literals
Real literals
Boolean literals
Single character literals
String literals
Backslash character literals
50. What is the difference between value type and reference type?
Value types are stored on the stack and when a value of a variable is assigned to another variable.
Reference types are stored on the heap, and when an assignment between two reference variables occurs.
51. What are the features of c#?
C# is a simple and powerful programming language for writing enterprise edition applications.
This is a hybrid of C++ and VB. It retains many C++ features in the area statements,expressions, and operators and incorporated the productivity of VB.
C# helps the developers to easily build the web services that can be used across the Internet through any language, on any platform.
C# helps the developers accomplishing with fewer lines of code that will lead to the fewer errors in the code.
C# introduces the considerable improvement and innovations in areas such as type safety,versioning. events and garbage collections.
52. What are the types of errors?
Syntax error
Logic error
Runtime error
53. What is the difference between break and continue statement?
The break statement is used to terminate the current enclosing loop or conditional statements in which it appears. We have already used the break statement to come out of switch statements.
The continue statement is used to alter the sequence of execution. Instead of coming out of the loop like the break statement did, the continue statement stops the current iteration and simply returns control back to the top of the loop.
54. Define namespace?
The namespace are known as containers which will be used to organize the hierarchical set of .Net classes.
55. What is a code group?
A code group is a set of assemblies that share a security context.
56. What are sealed classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.
57. What is the difference between static and instance methods?
A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only access static members.

A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.
58. What are the different types of variables in C#?
Different types of variables used in C# are :
static variables
instance variable
value parameters
reference parameters
array elements
output parameters
local variables
59. What is meant by method overloading?
Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. When compiling an invocation of an overloaded method, the compiler uses overload resolution to determine the specific method to invoke
60. What is parameters?
Parameters are used to pass values or variable references to methods. The parameters of a method get their actual values from the arguments that are specified when the method is invoked. There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.
61. Is C# is object oriented?
YEs, C# is an OO langauge in the tradition of Java and C++.
62. What is the difference between Array and Arraylist?
An array is a collection of the same type. The size of the array is fixed in its declaration. A linked list is similar to an array but it doesn’t have a limited size.
63. What are the special operators in C#?
C# supports the following special operators.
is (relational operator)
as (relational operator)
typeof (type operator)
sizeof (size operator)
new (object creator)
.dot (member access operator)
checked (overflow checking)
unchecked (prevention of overflow checking)
64. What is meant by operators in c#?
An operator is a member that defines the meaning of applying a particular expression operator to instances of a class. Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. All operators must be declared as public and static.
65. What is a parameterized type?
A parameterized type is a type that is parameterized over another value or type.
66. What are the features of abstract class?
An abstract class cannot be instantiated, and it is an error to use the new operator on an abstract class.
An abstract class is permitted (but not required) to contain abstract methods and accessors.
An abstract class cannot be scaled.
67. What is the use of abstract keyword?
The modifier abstract is a keyword used with a class, to indicate that this class cannot itself have direct instances or objects, and it is intended to be only a 'base' class to other classes.
68. What is the use of goto statement?
The goto statement is also included in the C# language. This goto can be used to jump from inside a loop to outside. But jumping from outside to inside a loop is not allowed.
69. What is the difference between console and window application?
A console application, which is designed to run at the command line with no user interface.
A Windows application, which is designed to run on a user’s desktop and has a user interface.
70. What is the use of return statement?
The return statement is associated with procedures (methods or functions). On executing the return statement, the system passes the control from the called procedure to the calling procedure. This return statement is used for two purposes :
to return immediately to the caller of the currently executed code
to return some value to the caller of the currently executed code.
71. What is the difference between Array and LinkedList?
Array is a simple sequence of numbers which are not concerned about each others positions. they are independent of each others positions. adding,removing or modifying any array element is very easy. Compared to arrays ,linked list is a comlicated sequence of numbers.
72. Does C# have a throws clause?
No, unlike Java, C# does not require the developer to specify the exceptions that a method can throw.
73. Does C# support a variable number of arguments?
Yes, uisng the params keyword. The arguments are specified as a list of arguments of a specific type.
74. Can you override private virtual methods?
No, private methods are not accessible outside the class.
75. What is a multi cast delegates?
It is a delegate that points to and eventually fires off several methods.

Wednesday, 3 October 2012

ASP.NET State Management Recommendations

Reference from http://msdn.microsoft.com/en-us/library/z1hkazw7%28VS.80%29.aspx

 State management is the process by which you maintain state and page information over multiple requests for the same or different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. Furthermore, pages are destroyed and re-created with each round trip to the server; therefore, page information will not exist beyond the life cycle of a single page. For more information about server round trips and the life cycle of Web Forms pages, see ASP.NET Page Life Cycle Overview.
ASP.NET provides multiple ways to maintain state between server round trips. Which of these options you choose depends heavily upon your application, and it should be based on the following criteria:
  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

Client-Side State Management Options

Storing page information using client-side options doesn't use server resources. These options typically have minimal security but fast server performance because the demand on server resources is modest. However, because you must send information to the client for it to be stored, there is a practical limit on how much information you can store this way.
The following are the client-side state management options that ASP.NET supports:
  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings

View State

Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for the same page. View state is maintained as a hidden field in the page. For more information, see ASP.NET State Management Overview.
You can use view state to store your own page-specific values across round trips when the page posts back to itself. For example, if your application is maintaining user-specific information — that is, information that is used in the page but is not necessarily part of any control — you can store it in view state.
Advantages of using view state are:
  • No server resources are required   The view state is contained in a structure within the page code.
  • Simple implementation   View state does not require any custom programming to use. It is on by default to maintain state data on controls.
  • Enhanced security features   The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.
Disadvantages of using view state are:
  • Performance considerations   Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
  • Device limitations   Mobile devices might not have the memory capacity to store a large amount of view-state data.
  • Potential security risks   The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.
For more information about using view state, see View State Overview.

Control State

The ASP.NET page framework provides the ControlState property as way to store custom control data between server trips. For example, if you have written a custom control that has different tabs showing different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. View state can be used for this purpose, but developers can turn view state off at the page level, effectively breaking your control. Unlike view state, control state cannot be turned off, so it provides a more reliable way to store control-state data.
Advantages of using control state are:
  • No server resources are required   By default, control state is stored in hidden fields on the page.
  • Reliability   Because control state cannot be turned off like view state, control state is a more reliable method for managing the state of controls.
  • Versatility   Custom adapters can be written to control how and where control-state data is stored.
Disadvantage of using control state are:
  • Some programming is required   While the ASP.NET page framework provides a foundation for control state, control state is a custom state-persistence mechanism. To fully utilize control state, you must write code to save and load control state.

Hidden Fields

You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page. For more information about hidden fields, see ASP.NET State Management Recommendations.
If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.
If you use hidden fields, you must submit your pages to the server using the HTTP POST method rather than requesting the page via the page URL (the HTTP GET method).
Advantages of using hidden fields are:
  • No server resources are required   The hidden field is stored and read from the page.
  • Widespread support   Almost all browsers and client devices support forms with hidden fields.
  • Simple implementation   Hidden fields are standard HTML controls that require no complex programming logic.
Disadvantages of using hidden fields are:
  • Potential security risks   The hidden field can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. You can manually encrypt and decrypt the contents of a hidden field, but doing so requires extra coding and overhead. If security is a concern, consider using a server-based state mechanism so that no sensitive information is sent to the client. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.
  • Simple storage architecture   The hidden field does not support rich data types. Hidden fields offer a single string value field in which to place information. To store multiple values, you must implement delimited strings and the code to parse those strings. You can manually serialize and de-serialize rich data types to and from hidden fields, respectively. However, it requires extra code to do so. If you need to store rich data types on the client, consider using view state instead. View state has serialization built-in, and it stores data in hidden fields.
  • Performance considerations   Because hidden fields are stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
  • Storage limitations   If the amount of data in a hidden field becomes very large, some proxies and firewalls will prevent access to the page that contains them. Because the maximum amount can vary with different firewall and proxy implementations, large hidden fields can be sporadically problematic. If you need to store many items of data, consider doing one of the following:
    • Put each item in a separate hidden field.
    • Use view state with view-state chunking turned on, which automatically separates data into multiple hidden fields.
    • Instead of storing data on the client, persist the data on the server. The more data you send to the client, the slower the apparent response time of your application will be because the browser will need to download or send more data.


Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server. For details about creating and reading cookies, see ASP.NET Cookies Overview.
Advantages of using cookies are:
  • Configurable expiration rules   The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
  • No server resources are required   The cookie is stored on the client and read by the server after a post.
  • Simplicity   The cookie is a lightweight, text-based structure with simple key-value pairs.
  • Data persistence   Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.
Disadvantages of using cookies are:
  • Size limitations   Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.
  • User-configured refusal   Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
  • Potential security risks   Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.
    Cookies are often used for personalization, where content is customized for a known user. In most of these cases, identification is the issue rather than authentication. Thus, you can typically secure a cookie that is used for identification by storing the user name, account name, or a unique user ID (such as a GUID) in the cookie and then using the cookie to access the user personalization infrastructure of a site.

Query Strings

A query string is information that is appended to the end of a page URL. For more information, see ASP.NET State Management Overview.
You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information. For example, query strings are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed.
Advantages of using query strings are:
  • No server resources are required   The query string is contained in the HTTP request for a specific URL.
  • Widespread support   Almost all browsers and client devices support using query strings to pass values.
  • Simple implementation   ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.
Disadvantages of using query strings are:
  • Potential security risks   The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings. For more information, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.
  • Limited capacity   Some browsers and client devices impose a 2083-character limit on the length of URLs.

Client-Side Method State Management Summary

The following table lists the client-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State management option Recommended usage
View state
Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Control state
Use when you need to store small amounts of state information for a control between round trips to the server.
Hidden fields
Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
You can use a hidden field only on pages that are submitted to the server.
Use when you need to store small amounts of information on the client and security is not an issue.
Query string
Use when you are transferring small amounts of information from one page to another and security is not an issue.
You can use query strings only if you are requesting the same page, or another page via a link.

Server-Side State Management Options

Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management. For more information, see ASP.NET State Management Overview.
The following are the server-side state management options that ASP.NET supports:
  • Application state
  • Session state
  • Profile properties
  • Database support

Application State

ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific information that is visible to the entire application. Application-state variables are, in effect, global variables for an ASP.NET application. For more information, see ASP.NET Application State Overview
You can store your application-specific values in application state, which is then managed by the server. For more information, see ASP.NET State Management Overview.
Data that is shared by multiple sessions and does not change often is the ideal type of data to insert into application-state variables.
Advantages of using application state are:
  • Simple implementation   Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  • Application scope   Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information (for instance, as opposed to keeping copies of information in session state or in individual pages).
Disadvantages of using application state are:
  • Application scope   The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.
  • Limited durability of data   Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.
  • Resource requirements   Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.
Careful design and implementation of application state can increase Web application performance. For example, placing a commonly used, relatively static dataset in application state can increase site performance by reducing the overall number of data requests to a database. However, there is a performance trade-off. Application state variables containing large blocks of information reduce Web server performance as server load increases. The memory occupied by a variable stored in application state is not released until the value is either removed or replaced. Therefore, it is best to use application-state variables only with small, infrequently changed datasets. For more information, see Developing High-Performance ASP.NET Applications.

Session State

ASP.NET provides a session state, which is available as the HttpSessionState class, as a method of storing session-specific information that is visible only within the session. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session. For more information, see ASP.NET State Management Overview and Session State Overview.
You can store your session-specific values and objects in session state, which is then managed by the server and available to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.
Advantages of using session state are:
  • Simple implementation   The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
  • Session-specific events   Session management events can be raised and used by your application.
  • Data persistence   Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
  • Platform scalability   Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  • Cookieless support   Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic. For more information about using session state without cookies, see Configuring ASP.NET Applications.
  • Extensibility   You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service. For more information, see Implementing a Session-State Store Provider.
Disadvantage of using session state are:
  • Performance considerations   Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.

Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner. For more information, see ASP.NET Profile Properties Overview.
Advantages of using profile properties are:
  • Data persistence   Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.
  • Platform scalability   Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.
  • Extensibility   In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service. For more information, see ASP.NET Profile Providers and Implementing a Profile Provider.
Disadvantages of using profile properties are:
  • Performance considerations   Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.
  • Additional configuration requirements   Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store. For more information, see ASP.NET Profile Properties Overview and Defining ASP.NET Profile Properties.
  • Data maintenance   Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.

Database Support

In some cases, you might want to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state information by using a relational database for the following reasons:
  • Security
  • Personalization
  • Consistency
  • Data mining
The following are typical features of a cookie-supported database Web site:
  • Security   The visitor types an account name and password into a site logon page. The site infrastructure queries the database with the logon values to determine whether the user has rights to utilize your site. If the database validates the user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer. The site grants access to the user.
  • Personalization   With security information in place, your site can distinguish each user by reading the cookie on the client computer. Typically, sites have information in the database that describes the preferences of a user (identified by a unique ID). This relationship is known as personalization. The site can research the user's preferences using the unique ID contained in the cookie, and then place content and information in front of the user that pertains to the user's specific wishes, reacting to the user's preferences over time.
  • Consistency   If you have created a commerce Web site, you might want to keep transactional records of purchases made for goods and services on your site. This information can be reliably saved in your database and referenced by the user's unique ID. It can be used to determine whether a purchase transaction has been completed, and to determine the course of action if a purchase transaction fails. The information can also be used to inform the user of the status of an order placed using your site.
  • Data mining   Information about your site usage, your visitors, or your product transactions can be reliably stored in a database. For example, your business development department might want to use the data collected from your site to determine next year's product line or distribution policy. Your marketing department might want to examine demographic information about users on your site. Your engineering and support departments might want to look at transactions and note areas where your purchasing process could be improved. Most enterprise-level relational databases, such as Microsoft SQL Server, contain an expansive toolset for most data mining projects.
By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her personally.
Advantages of using a database to maintain state are:
  • Security   Access to databases requires rigorous authentication and authorization.
  • Storage capacity   You can store as much information as you like in a database.
  • Data persistence   Database information can be stored as long as you like, and it is not subject to the availability of the Web server.
  • Robustness and data integrity   Databases include various facilities for maintaining good data, including triggers and referential integrity, transactions, and so on. By keeping information about transactions in a database (rather than in session state, for example), you can recover from errors more readily.
  • Accessibility   The data stored in your database is accessible to a wide variety of information-processing tools.
  • Widespread support   There is a large range of database tools available, and many custom configurations are available.
Disadvantages of using a database to maintain state are:
  • Complexity   Using a database to support state management requires that the hardware and software configurations be more complex.
  • Performance considerations   Poor construction of the relational data model can lead to scalability issues. Also, leveraging too many queries to the database can adversely affect server performance.

Server-Side Method State Management Summary

The following table lists the server-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State management option Recommended usage
Application state
Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state
Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Profile properties
Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database support
Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

Differences between Cache,Session and ViewState in Asp.Net

  • memory.
  • allow you to store difficult and complex constructed data which can be reused.
  • is available to be accessed from global/application level where one reference to memory is updated. Each request will use the same cache for different users.
  • a period of time that is shared between the web application and the user.
  • Each user that is using the web application has their own session.
  • The Session variables will be cleared by the application which can clear it, as well as through the timeout property in the web config file.
  • Session variables will use different session variables for each different user.
  • hidden data that is kept by ASP.NET pages.
  • track the changes to a web site during post backs.
  • All server controls contain a view state. [EnableViewState property - enable/disable if the control properties will be held in hidden fields.]
  • Having a large ViewState will cause a page to download slowly from the user’s side.- When a user clicks on a button and a post back occurs, all the view state information has to be posted back to the server which causes a slower request.
  • ViewState should be limited to what is needed.- Data can also be written into the ViewState. – The ViewState only persists for the life cycle of the page.
  • If the page redirects to another page, or even to itself, the ViewState will be reset.
  • ViewState should be used to hold small amounts of data, which will be only used on the current page

Monday, 3 September 2012

Iterating items in XML using cursor in sql server


SET @XML = '
      <contacts >

 SELECT  convert(VARCHAR(20),contact.ITEM.query('./names').value('.','VARCHAR(20)')) names
                                            FROM @XML.nodes('/contacts/contact') AS contact(ITEM)

PRINT '------------------------------------------------'

Above is the sample used to iterating item in xml using cursor in sql server

Thursday, 28 June 2012

Call Page Method from JavaScript

Call Page Method from JavaScript

Write Page Method that You want to call (Method Must be Static):

public partial class PageMethod : System.Web.UI.Page
    public static string GetMenuItem()
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat(“<li>{0}</li>”, “Second”);
        sb.AppendFormat(“<li>{0}</li>”, “Third”);
sb.AppendFormat(“<li>{0}</li>”, “Forth”);
        sb.AppendFormat(“<li>{0}</li>”, “Fifth”);
        return sb.ToString();

Write JavaScipt to call Page Method :

    <script type=”text/javascript” language=”javascript”>
        function CallWebServiceMethod() {
        PageMethods.GetMenuItem(GetMenuItemComplete, errormethod);

       function GetMenuItemComplete(val) {   /// Called When page method execute successfully
            $get(“divItem”).innerHTML = val;

        function errormethod(val) {    ///  called when error occurs in execution
        alert(“Error” + val)

At last Write HTML for display result :

<body onload=”CallWebServiceMethod();”>
    <form id=”form1? runat=”server”>
    <asp:ScriptManager ID=”ScriptManager1? EnablePageMethods=”true” runat=”server”>
/// Bold written Attribute required for calling Page  method
    <div id=”divItem”>


Session in Javascript

<script type=”text/javascript”>
 //To set Session
function Setsession() {
    if (window.sessionStorage) {
       sessionStorage.setItem(“key1″, document.getElementById(‘<%= Write.ClientID %>’).value);               

//To get Session
function GetSession() {
     if (window.sessionStorage) {
         document.getElementById(‘<%= Get.ClientID %>’).value = sessionStorage.getItem(“key1″);


To get Session Value using javascript

 <script type=”text/javascript”>
var session = '<%= Session["VALUE"] %>'; 


Thursday, 29 March 2012

How to create a database backup using visual studio

I am going to create a backup using a C# Windows forms project. The project is simple. You will have a button to create a database backup in the windows form. Every time that you click the button, a new backup is created.

This project includes the following components:
  • A database backup: test.zip
  • The Windows form project: backup.zip
  • A script with the backup stored procedure: createBackup.sql


The requirements to build this are:
  • Visual Studio 2008 or later
  • SQL Server 2005 or later

Getting started

Let’s start. We are going to create a stored procedure first that creates a backup of the test database (you can create a test database or restore from the test.bak attached manually).
The following T-SQL will do this:
create procedure [dbo].[backupdb]

BACKUP DATABASE [test] TO  DISK = N'C:\backup\test.bak'
     , NOINIT
     , NAME = N'test copy'
     , SKIP
     , STATS = 10
Peace of cake, isn’t it? We are creating the test database backup in the c:\backup folder and the backup name is test.bak. Subsequent backups are all written to the same file. Everything to do this is in the stored procedure named dbo.backupdb.
To execute the stored procedure use the following command:
exec [dbo].[backupdb]
The stored procedure will create a backup inside the test.bak file. 
Now, let’s start with the Visual Studio application. Open the backup.sln in the backup.zip file. In the Solution Explorer, double click in the app.config item.  The content of the file should be the following:
<?xml version="1.0" encoding="utf-8" ?>
    <add name="connectionStringName"
         connectionString="Data Source=.\SQLEXPRESS
         ;Initial Catalog=test;Integrated Security=True;async=true "/>
Let me explain this part of the app.config:
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;async=true "/>
This file contains the connection to the SQL Server. In this case, it is a local SQL Server Express Edition. The initial catalog is the database test and it is using integrated security (Windows authentication).
To use the app.config file it is necessary to add the System.configuration:

The system configuration references needs to be added. To do this, in the Solution Explorer, in references right click the button mouse and select add references.
In the references window, select the System Configuration.

In the design pane, double click the backup button to see the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace backup
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
                string ConnectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ToString();
                SqlConnection cnn = new SqlConnection(ConnectionString);

                SqlCommand cmd = new SqlCommand("backupdb", cnn);
                cmd.CommandType = CommandType.StoredProcedure;



                MessageBox.Show("Backup completed successfully");

            catch (Exception ex)

Note that the following lines are not created by default. These lines of code need to be added in order to connect to SQL Server and to use the App.config file.
using System.Data.SqlClient;
using System.Configuration;
Let me explain these lines of code:
string ConnectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ToString();
This line of code will save the connection data created in the app.config file in the connectionString.
The following lines of code are used to call the stored procedure backupdb and execute the stored procedure using Visual Studio.
SqlCommand cmd = new SqlCommand("backupdb", cnn);

cmd.CommandType = CommandType.StoredProcedure;


These lines of code will call the stored procedure created and execute it.
That’s it !. You have a button to create a backup.
In the project, just press F5 in order to start the project. In the Windows form press the backup button. You will create the database backup in the c:\backup\test.bak. If the file was created, you successfully created a Project in Visual Studio to generate SQL Server backups !. 


Total Pageviews