Tuesday, 30 May 2017

ASP.NET State Management Overview

A  new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:
View state
Control state
Hidden fields
Cookies
Query strings
Application state
Session state
Profile Properties
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.

Client-Based State Management Options
The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.

View State
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
You can store values in view state as well. For more information on using View State, see ASP.NET View State Overview. For recommendations about when you should use view state, see ASP.NET State Management Recommendations.

Control State
Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields
ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.

Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly. For more information, see ASP.NET State Management Recommendations.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. For more information, see HiddenField Web Server Control Overview.
In order for hidden-field values to be available during page processing,

Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Security Note
The browser can only send the data back to the server that originally created the cookie. However, malicious users have ways to access cookies and read their contents. It is recommended that you do not store sensitive information, such as a user name or password, in a cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look up the sensitive information on the server.
For more information about using cookies, see Cookies and ASP.NET State Management Recommendations.

Query Strings
A query string is information that is appended to the end of a page URL. A typical query string might look like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
Security Note
Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or send the URL to other users, thereby passing that information along with it. For more information, see ASP.NET State Management Recommendations and How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings.
In order for query string values to be available during page processing, you must submit the page using an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST command. For usage recommendations, see ASP.NET State Management Recommendations.
Server-Based State Management Options
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state management features: application state, session state, and profile properties.
Application State
ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. For more information, see ASP.NET Application State Overview.
Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Once you add your appl

Monday, 29 May 2017

Difference between value types and reference types

Value types, as name tells, are values stored in memory; referencer types are (a kind of) pointer to an object (a class, an object, etc...)

From Microsoft:

A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data.

Value Types
Value types include the following:

All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
Reference Types
Reference types include the following:

String
All arrays, even if their elements are value types
Class types, such as Form
Delegates

Tuesday, 16 May 2017

Page Life Cycle With Examples in ASP.Net

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. The following are the various stages or events of ASP.Net page life cycle.

PreInit

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.

Note: If the request is a postback then the values of the controls have not yet been restored from the view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init

This event fires after each control has been initialized.
Each control's UniqueID is set and any skin settings have been applied.
Use this event to read or initialize control properties.
The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

InitComplete

Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback.
Raised by the Page object.
Use this event for processing tasks that require all initialization to be complete.

OnPreLoad

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.
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.
Loads ViewState: ViewState data are loaded to controls.
Loads Postback data: Postback data are now handed to the page controls.

Load

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
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 call Validate and check the value of IsValid in this method.
You can also create dynamic controls in this method.
Use the OnLoad event method to set properties in controls and establish database connections.

Control PostBack Event(s)

ASP.NET now calls any events on the page or its controls that caused the PostBack to occur.
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
This is just an example of a control event. Here it is the button click event that caused the postback.

LoadComplete

Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.

OnPreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
The PreRender event of individual controls occurs after the PreRender event of the page.
Allows final changes to the page or its control.
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.
Each data bound control whose DataSourceID property is set calls its DataBind method.
Use the event to make final changes to the contents.

Wednesday, 10 May 2017

Get Master Page Control Value On content page

Hello To All
I have a Master Page Like

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <asp:ContentPlaceHolder ID="head" runat="server">
  </asp:ContentPlaceHolder>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:Label ID="Label1" runat="server" Text="Kshama"></asp:Label>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
  </div>
  </form>
</body>
</html>
And content page Like

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
  CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  <telerik:RadGrid ID="RadGrid1" runat="server">
  </telerik:RadGrid>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server">
    <InsertParameters>
      <asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />
      <asp:Parameter Name="classname" Type="String" />
      <asp:Parameter Name="section" Type="String" />
    </InsertParameters>
  </asp:SqlDataSource>
</asp:Content>
Now Problem is that I need Master Page Label1 Text In

<asp:ControlParameter ControlID="Label1" Name="Branch_code" PropertyName="Text" />
in InsertParameter How Can I get Label1 Text in sqldatasource insertparameters......

Reply

shree_ars
Member
Jul 20, 2012 03:39 AM

yes..u can..

try putting script manager in ur master page.. and in the content page

from the scriptmanger u can able to retrive the control object and get the values of what ever control u need it.

If you win, you need not have to explain...If you lose, you should not be there to explain!
Reply

kshama
Member
Jul 20, 2012 03:41 AM

How Can I do this

any example.

Reply

shree_ars
Member
Re: Get Master Page Control Value On content page
Jul 20, 2012 06:42 AM

string str = ((TextBox)ScriptManager.GetCurrent(this).FindControl("textBox1")).Text;

in the above code..."textBox1" is placed in maser page.

and the above code u just place in ur content page and check it.

If you win, you need not have to explain...If you lose, you should not be there to explain!
Reply

Damn Code
Participant
Re: Get Master Page Control Value On content page
Jul 21, 2012 06:21 PM

Hi, friend

if you wanna get control value from master page

use to write this on content page

string str = ((Label)Master.FindControl("Label1")).Text;
Reply

Frank Jiang...
All-Star
Re: Get Master Page Control Value On content page
Jul 25, 2012 03:47 AM

kshama
Now Problem is that I need Master Page Label1 Text In

<asp:ControlParameter ControlID="Label1" Name="Branch_code" PropertyName="Text" />
in InsertParameter How Can I get Label1 Text in sqldatasource insertparameters......

  protected void insert_OnCLick(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        Label lblMaster = (Label)this.Master.FindControl("LabelID");
        if (lblMaster != null)
        {
            SqlDataSource1.InsertParameters("classname").DefaultValue = lblMaster.Text;
        }   
        SqlDataSource1.Insert();
    }

Tuesday, 9 May 2017

How can I remove duplicate rows from table in Sql Server?


down vote
I would prefer CTE for deleting duplicate rows from sql server table

strongly recommend to follow this article ::http://dotnetmob.com/sql-server-article/delete-duplicate-rows-in-sql-server/

by keeping original
WITH CTE AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY col1,col2,col3 ORDER BY col1,col2,col3) AS RN
FROM MyTable
)

DELETE FROM CTE WHERE RN<>1
without keeping original
WITH CTE AS
(SELECT *,R=RANK() OVER (ORDER BY col1,col2,col3)
FROM MyTable)

DELETE CTE
WHERE R IN (SELECT R FROM CTE GROUP BY R HAVING COUNT(*)>1)




Yet another easy solution can be found at the link pasted here. This one easy to grasp and seems to be effective for most of the similar problems. It is for SQL Server though but the concept used is more than acceptable.

Here are the relevant portions from the linked page:

Consider this data:

EMPLOYEE_ID ATTENDANCE_DATE
A001    2011-01-01
A001    2011-01-01
A002    2011-01-01
A002    2011-01-01
A002    2011-01-01
A003    2011-01-01
So how can we delete those duplicate data?

First, insert an identity column in that table by using the following code:

ALTER TABLE dbo.ATTENDANCE ADD AUTOID INT IDENTITY(1,1) 
Use the following code to resolve it:

DELETE FROM dbo.ATTENDANCE WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
    FROM dbo.ATTENDANCE GROUP BY EMPLOYEE_ID,ATTENDANCE_DATE)