Thursday, 14 July 2016

Web.Config

What is Web.Config File?
Configuration file is used to manage various settings that define a website. The settings are stored in XML files that are separate from your application code. In this way you can configure settings independently from your code. Generally a website contains a single Web.config file stored inside the application root directory. However there can be many configuration files that manage settings at various levels within an application.

Usage of configuration file

ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of ASP.NET applications. Configuration files help you to manage the many settings related to your website. Each file is an XML file (with the extension .config) that contains a set of configuration elements. Configuration information is stored in XML-based text files.

Benefits of XML-based Configuration files
  • ASP.NET Configuration system is extensible and application specific information can be stored and retrieved easily. It is human readable.
  • You need not restart the web server when the settings are changed in configuration file. ASP.NET automatically detects the changes and applies them to the running ASP.NET application.
  • You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.
What Web.config file contains?

There are number of important settings that can be stored in the configuration file. Some of the most frequently used configurations, stored conveniently inside Web.config file are:

  • Database connections
  • Caching settings
  • Session States
  • Error Handling
  • Security
Configuration file looks like this:

<
configuration>
    <
connectionStrings>
      <
add name ="myCon"
          
connectionString ="server=MyServer;database=puran;
           uid=puranmehra;pwd=mydata1223
"/>
    </
connectionStrings>
  </
configuration/>
Different types of Configuration files

Machine.config: Server or machine-wide configuration file

Web.config: Application configuration files which deal with a single application

Machine.config File

Configuration files are applied to an executing site based on a hierarchy. There is a global configuration file for all sites in a given machine which is called Machine.config. This file is typically found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG directory.

The Machine.config file contains settings for all sites running on the machine provided another .config further up the chain does not override any of these settings. Although Machine.config provides a global configuration option, you can use .config files inside individual website directories to provide more granular control. Between these two poles you can set a number of other .config files with varying degree of applicable scope.

Application Configuration file (Web.config)

Each and Every ASP.NET application has its own copy of configuration settings stored in a file called Web.config. If the web application spans multiple folders, each sub folder has its own Web.config file that inherits or overrides the parent's file settings.

Processing of a Web.config file

When you initially run your web application, the runtime builds a cache of the configuration settings for your web application by flattening the layer of configuration files as below:

  1. The Machine.config file settings are retrieved.
  2. The settings from the root Web.config files are added to the caches, overwriting any conflicting settings that were earlier while reading the Machine.config file.
  3. If there is a Web.config file at the root of the website, this file is read into the cache, all overwriting any existing settings. The resulting cache contains the setting for this website.
  4. If you have subdirectories in your web application, each subdirectory can have a Web.config file that includes settings that are specific to the files and folders that are contained within the subdirectory. To calculate the effective setting for the folders, the website settings are read (step 1-4) and then this Web.config file is read into cache for this folder, overwriting (and thereby overriding) any existing settings.

Monday, 11 July 2016

Collection

1.What is collection.
Collection is nothing but they are given group of records which can be treated as one logical unit .
.Net Collection divided four category.
1.Indexed based
  Array ,list
2. key value pair
Hash table ,sorted list
3.prioritized collection
Stack ,Queue
4. specialized collection
String collection,Hybrid directory 

Friday, 8 July 2016

Session






1).What is state management?

State management is the process that maintain state and page information over multiple requests for the same or different pages.

State Management

2).Http is stateless, What does this mean?

Stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request
so that the communication consists of independent pairs of requests and responses.

3).What is Session?

Http is stateless, means when we open a webpage and fill some information and then move to next page then the data which we have entered will lost.It happed do to Http protocol stateless nature. So here session come into existence, Session provide us the way of storing data in server memory. So you can store your page data into server memory and retrieve it back during page postbacks.

4).What are the Advantage and disadvantage of Session?

Advantages:
1.    Session provide us the way of maintain user state/data.
2.    It is very easy to implement.
3.    session  store any kind of object in it. :eg, datatabe, dataset.. etc
4.    By using session we don't need to worry about data collesp, because it store every client data separately.
5.    Session is secure and transparent from the user.

Disadvantages:
1.    Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
2.    Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.

5).What is Session ID in Asp.net?

Asp.Net use 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When client communicate with server, only session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data.

6).By default where the sessions ID's are stored ?

By default, the unique identifier for a session is stored in a non-expiring session cookie in the browser. You can specify that session identifiers not be stored in a cookie by setting the cookieless attribute to true in the sessionState configuration element. We can also configure our application to store it in the url by specifying a "cookieless" session


7).Where does session stored if cookie is disabled on client’s machine?

If you want to disable the use of cookies in your ASP.NET application and still make use of session state, you can configure your application to store the session identifier in the URL instead of a cookie by setting the cookieless attribute of the sessionState configuration element to true, or to UseUri, in the Web.config file for your application. The following code example shows a Web.config file that configures session state to use cookieless session identifiers.

<configuration>
  <system.web>
    <sessionState
      cookieless="true"
      regenerateExpiredSessionId="true"
      timeout="50" />
  </system.web>
</configuration>



8).Can you describe all the property set in web.config under session state?


<configuration>
  <sessionstate
      mode="inproc"
      cookieless="false"
      timeout="20"
      sqlconnectionstring="data source=127.0.0.1;user id=<userid>;password=<password>"
      server="127.0.0.1"
      port="8080"/>
</configuration>


Mode: The mode setting supports three options: inproc, sqlserver, and stateserver.

As stated earlier, ASP.NET supports two modes: in process and out of process.

There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly.
1.    Cookieless: The cookieless option for ASP.NET is configured with this simple Boolean setting.
2.    Timeout: This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value
3.    Sqlconnectionstring: The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.
4.    Server: In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.
5.    Port: The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.

9).What are Session Events?

There are two types of session events available in ASP.NET:
1.    Session_Start
2.    Session_End

You can handle both these events in the global.asax file of your web application. When a new session initiates, the session_start event is raised, and the Session_End event raised when a session is abandoned or expires.

10).How you can disable session?

 If we set session Mode="off" in web.config, session will be disabled in the application. For this, we need to configure web.config the following way:

<configuration>
  <sessionstate  Mode="off"/>
</configuration>

Wednesday, 6 July 2016

Asp .net Page Life cycle

Asp .net Page Life cycle


1. Page_PreInit Event
2. Page_Init Event 
3. Page_InitComplete 
4. Page_PreLoad Event 
5. Page_Load Event 
6. Page_LoadComplete 
7. Page_PreRender 
8. Page_Render Method 
9. Page_Unload Event  


 (1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
using System;
using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page{    protected void Page_PreInit(object sender, EventArgs e)    {        //  Use this event for the following:          //  Check the IsPostBack property to determine whether this is the first time the page is being processed.        //  Create or re-create dynamic controls.        //  Set a master page dynamically.        //  Set the Theme property dynamically.           }
------------------------------------------------------------------------
(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.  
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Init(object sender, EventArgs e)
{// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.}
 -------------------------------------------------------------------
(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_InitComplete(object sender, EventArgs e)
{       // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete. }
------------------------------------------------------------------------
(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance     
(1)Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.     
(2)Loads Postback data : postback data are now handed to the page controls            
Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreLoad(EventArgs e)
{        // Use this event if you need to perform processing on your page or control before the  Load event.        // Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.}
------------------------------------------------------------------------
(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.
 EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Load(object sender, EventArgs e)
{        // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.        // Use the OnLoad event method to set properties in controls and establish database connections.}
------------------------------------------------------------------------
(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file). 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Button1_Click(object sender, EventArgs e)
{        // This is just an example of control event.. Here it is button click event that caused the postback}
---------------------------------------------------------------------
(7)LoadComplete This event signals the end of Load. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_LoadComplete(object sender, EventArgs e)
{        // Use this event for tasks that require that all other controls on the page be loaded.}
----------------------------------------------------------------------
(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreRender(EventArgs e)
{        // Each data bound control whose DataSourceID property is set calls its DataBind method.        // The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.}
-----------------------------------------------------------------------
(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnSaveStateComplete(EventArgs e)
{        // Before this event occurs,  ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.}
------------------------------------------------------------------------
(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.
 Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
// Render stage goes here. This is not an event
------------------------------------------------------------------------
(11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on- 
     (a)Instances of classes i.e. objects
     (b)Closing opened files
     (c)Closing database connections. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_UnLoad(object sender, EventArgs e)   
{        // This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.        // During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.           //If you attempt to call a method such as the Response.Write method, the page will throw an exception.    }





Validation



  1. What are ASP.NET Validation controls?
    ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions.
    1. Did the user enter anything?
    2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
    3. Is the data within a required range?(For example age cannot be greater than 100 years)
    The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server.
  2. Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?
    ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server.

    Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.
  3. What are the 6 different validation controls provided by ASP.NET?
    RequiredFieldValidator:Checks whether a control contains data
    CompareValidator:Checks whether an entered item matches an entry in another control
    RangeValidator:Checks whether an entered item is between two values
    RegularExpressionValidator:Checks whether an entered item matches a specified format
    CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
    ValidationSummary:Displays validation errors in a central location or display a general validation error description


Validation Control
Description
RequiredFieldValidation
Makes an input control a required field
CompareValidator
Compares the value of one input control to the value of another input control or to a fixed value
RangeValidator
Checks that the user enters a value that falls between two values
RegularExpressionValidator
Ensures that the value of an input control matches a specified pattern
CustomValidator
Allows you to write a method to handle the validation of the value entered
ValidationSummary
Displays a report of all validation errors occurred in a Web page


 


  1. What property of the validation control is used to specify which control to validate?
    ControlToValidate property.
  2. Explain in simple steps how to use validation controls?
    1.Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate.
    2.If you’re using the CompareValidator control, you also need to specify the ControlToCompare property.
    3.Set the validation control’s ErrorMessage property to the error message you want displayed if the control’s data is not valid.
    4.Set the validation control’s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.
    5.Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.
    6.Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn’t start until a postback is requested.
  3. Are the validation controls fired on the client side if javascript is disabled on the client browser?
    No, validation controls are not fired on the client side if javascript is disabled on the client browser.
  4. What is the use of CausesValidation property of an ASP.NET button control?
    CausesValidation property of an ASP.NET button control is used to determine if the validation controls should be fired when the button is clicked. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done.
  5. Why we use validation controls?

    Validation is important part of any web application. User's input must always be validated before sending across different layers of the application.

    Validation controls are used to:


  • Implement presentation logic.
  • To validate user input data.
  • Data format, data type and data range is used for validation.


  1. Validation is of two types:


  1. Client Side
  2. Serve Side



Client side validation is good but we have to be dependent on browser and scripting language support.

Client side validation is considered convenient for users as they get instant feedback. The main advantage is that it prevents a page from being postback to the server until the client validation is executed successfully.

For developer point of view serve side is preferable because it will not fail, it is not dependent on browser and scripting language.

You can use ASP.NET validation, which will ensure client, and server validation. It work on both end; first it will work on client validation and than on server validation. At any cost server validation will work always whether client validation is executed or not. So you have a safety of validation check.

For client script .NET used JavaScript. WebUIValidation.js file is used for client validation by .NET


All validation controls are rendered in form as <span> (label are referred as <span> on client by server)

10. Important points for validation controls


  • ControlToValidate property is mandatory to all validate controls.
  • One validation control will validate only one input control but multiple validate control can be assigned to a input control.



11. Validation Properties
Usually, Validation is invoked in response to user actions like clicking submit button or entering data. Suppose, you wish to perform validation on page when user clicks submit button.

Server validation will only performed when CauseValidation is set to true.

When the value of the CausesValidation property is set to true, you can also use the ValidationGroup property to specify the name of the validation group for which the Button control causes validation.

Page has a Validate() method. If it is true this methods is executed. Validate() executes each validation control.

To make this happen, simply set the CauseValidation property to true for submit button as shown below:

<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />

Lets understand validation controls one by one with practical demonstration:

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks to see if the data is entered for the input control. You can have a RequiredFieldValidator control for each form element on which you wish to enforce Mandatory Field rule.

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 98px;
       
left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"
        ControlToValidate="TextBox2"></asp:RequiredFieldValidator>

CompareValidator Control

The CompareValidator control allows you to make comparison to compare data entered in an input control with a constant value or a value in a different control.

It can most commonly be used when you need to confirm password entered by the user at the registration time. The data is always case sensitive.

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;
       
left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"
        ControlToValidate="TextBox3"></asp:RequiredFieldValidator>

RangeValidator Control

The RangeValidator Server Control is another validator control, which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.


<asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 194px; left: 365px;
           
position: absolute; height: 22px; width: 105px"
       
ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100"
       
MinimumValue="18" Type="Integer"></asp:RangeValidator>

RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can be used to identify simple and complex characters sequence that would otherwise require writing code to perform.

Using RegularExpressionValidator server control, you can check a user's input based on a pattern that you define using a regular expression.

It is used to validate complex expressions. These expressions can be phone number, email address, zip code and many more. Using Regular Expression Validator is very simple. Simply set the ValidationExpression property to any type of expression you want and it will validate it.

If you don't find your desired regular expression, you can create your custom one.

In the example I have checked the email id format:


<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234px;
       
left: 366px; position: absolute; height: 22px; width: 177px"
       
ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"
       
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>


ValidationSummary

ASP.NET has provided an additional control that complements the validator controls.

The ValidationSummary control is reporting control, which is used by the other validation controls on a page.

You can use this validation control to consolidate errors reporting for all the validation errors that occur on a page instead of leaving this up to each and every individual validation control.

The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list.


<asp:ValidationSummary ID="ValidationSummary1" runat="server"
       
style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625px" />