Вы находитесь на странице: 1из 47

Table of Contents

1. Difference between Array and ArrayList a) The capacity of an Array is fixed. Where as, ArrayList can increase and decrease size dynamically. b) An Array is a collection of similar items. Where as, ArrayList can hold item of different types. c) Array is in the System namespace. Where as, ArrayList is in the System.Collections namespace. d) An Array can have multiple dimensions. Where as, ArrayList always has exactly one dimension. e) We can set the lower bound of an Array. Where as, the lower bound of an ArrayList is always zero. ................................................................................ 3 2. What is the difference between USER CONTROLS and a CUSTOM CONTROL? ........................................................................................................................................... 3 Web user control : 1. Web user controls are easy to make, but they can be less convenient to use. 2. Web user controls are compiled dynamically at run time they cannot be added to the Toolbox 3. the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control 4. If your control has a lot of static layout, a user control might make sense web custom control : 1. Web custom controls are compiled code, which makes them easier to use but more difficult to create. 2. Once you have created the control, however, you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition, you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier. ............................................................................. 3 4. Temporary Tables vs. Table Variables and Their Effect on SQL Server Performance ..................... 4 Conclusion ........................................................................................................................................... 8 4. 7. 8. C#'s const vs. readonly ................................................................................................................ 8 Global.asax File?...................................................................................................................... 9 What is an Application Pool? .................................................................................................. 9

Open PopUp Window Update Refresh Parent Values From Child ASP.NET ................................... 9 Parent Window ............................................................................................................................... 9 9. 13. 14. State Management ............................................................................................................... 10 ASP.NET PAGE DIRECTIVE ..................................................................................................... 21 What is the difference between Web Farm and Web Garden ? October 1, 2010................ 21

Managed Code ...................................................................................................................................... 28 17. 18. Constructor types with example programs in C#.NET .............................................................. 31 AJAX Triggers ........................................................................................................................ 36

The <Triggers> Element .................................................................................................................... 36 <Triggers> Element Reference .......................................................................................................... 37 Walkthrough: Cross-UpdatePanel Triggers ...................................................................................... 37 Under the Hood ................................................................................................................................. 39 Summary ........................................................................................................................................... 43

19.

Partial Class Definitions (C# Programming Guide) .................................................................... 44

1. Difference between Array and ArrayList a) The capacity of an Array is fixed. Where as, ArrayList can increase and decrease size dynamically. b) An Array is a collection of similar items. Where as, ArrayList can hold item of different types. c) Array is in the System namespace. Where as, ArrayList is in the System.Collections namespace. d) An Array can have multiple dimensions. Where as, ArrayList always has exactly one dimension. e) We can set the lower bound of an Array. Where as, the lower bound of an ArrayList is always zero. 2. What is the difference between USER CONTROLS and a CUSTOM CONTROL?
Web user control : 1. Web user controls are easy to make, but they can be less convenient to use. 2. Web user controls are compiled dynamically at run time they cannot be added to the Toolbox 3. the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control 4. If your control has a lot of static layout, a user control might make sense web custom control : 1. Web custom controls are compiled code, which makes them easier to use but more difficult to create. 2. Once you have created the control, however, you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition, you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.

3. CTS and CLS CTS When different languages are integrated and want to communicate, it is certain that the languages have their own data types and different declaration styles. CTS define how these different variables are declared and used in run time. E.g. VB offers an Integer data type while C++ offers long data type. Using CTS, these data types are converted to System32 which itself a data type of CLS. CLS Any language(s) that intend to use the Common Language Infrastructure needs to communicate with other CLS-Compliant language. This communication is based on set of rules laid by CLS. These rules define a subset of CTS.

4. Temporary Tables vs. Table Variables and Their Effect on SQL Server Performance
By Dmitry Tsuranoff There are three major theoretical differences between temporary tables: create table #T () And table variables: declare @T table () The first difference is that transaction logs are not recorded for the table variables. Hence, they are out of scope of the transaction mechanism, as is clearly visible from this example: create table #T (s varchar(128)) declare @T table (s varchar(128)) insert into #T select old value # insert into @T select old value @ begin transaction update #T set s=new value # update @T set s=new value @ rollback transaction select * from #T select * from @T s old value # s new value @ After declaring our temporary table #T and our table-variable @T, we assign each one with the same old value string. Then, we begin a transaction that updates their contents. At this point, both will now contain the same new value string. But when we rollback the transaction, as you can see, the table-variable @T retained its value instead of reverting back to the old value string. This happened because, even though the table-variable was updated within the transaction, it is not a part of the transaction itself. The second major difference is that any procedure with a temporary table cannot be precompiled, while an execution plan of procedures with table variables can be statically compiled in advance. Pre-compiling a script gives a major advantage to its speed of execution. This advantage can be dramatic for long procedures, where recompilation can be too pricy.

Finally, table variables exist only in the same scope as variables. Contrary to the temporary tables, they are not visible in inner stored procedures and in exec(string) statements. Also, they cannot be used in an insert/exec statement. But lets compare both in terms of performance. At first, we prepare a test table with 1 million records: create table NUM (n int primary key, s varchar(128)) GO set nocount on declare @n int set @n=1000000 while @n>0 begin insert into NUM select @n,Value: +convert(varchar,@n) set @n=@n-1 end GO Now we prepare our test procedure T1: create procedure T1 @total int as create table #T (n int, s varchar(128)) insert into #T select n,s from NUM where n%100>0 and n<=@total declare @res varchar(128) select @res=max(s) from NUM where n<=@total and not exists(select * from #T where #T.n=NUM.n) GO Called with a parameter, which we will vary from 10, 100, 1,000, 10,000, 100,000 up to 1,000,000, it copies the given number of records into a temporary table (with some exceptions, as it skips records where n is divisible by 100), and then finds a max(s) of such missing records. Of course, the more records we give, the longer the execution is. To measure the execution time precisely, I use the code: declare @t1 datetime, @n int set @t1=getdate() set @n=100 (**) while @n>0 begin exec T1 1000 (*) set @n=@n-1 end

select datediff(ms,@t1,getdate()) GO (*) The parameter to our procedure is varied from 10 to 1,000,000. (**) If an execution time is too short, I repeat the same loop 10 or 100 times. I run the code several times to get a result of a warm execution. The results can be found in Table 1 below. Now lets try to improve our stored procedure by adding a primary key to the temporary table: create procedure T2 @total int as create table #T (n int primary key, s varchar(128)) insert into #T select n,s from NUM where n%100>0 and n<=@total declare @res varchar(128) select @res=max(s) from NUM where n<=@total and not exists(select * from #T where #T.n=NUM.n) GO Then, lets create a third one. With a clustered index, it works much better. But lets create the index AFTER we insert data into the temporary tableusually, it is better: create procedure T3 @total int as create table #T (n int, s varchar(128)) insert into #T select n,s from NUM where n%100>0 and n<=@total create clustered index Tind on #T (n) declare @res varchar(128) select @res=max(s) from NUM where n<=@total and not exists(select * from #T where #T.n=NUM.n) GO Surprise! Large amounts of data take longer; merely adding 10 records takes an additional 13 milliseconds. The problem is that create index statements force SQL server to recompile stored procedures, and slows down the execution significantly. Now lets try the same using table variables:

create procedure V1 @total int as declare @V table (n int, s varchar(128)) insert into @V select n,s from NUM where n%100>0 and n<=@total declare @res varchar(128) select @res=max(s) from NUM where n<=@total and not exists(select * from @V V where V.n=NUM.n) GO To our surprise, this version is not significantly faster than the version with the temporary table. This is a result of a special optimization SQL server has for the create table #T statements in the very beginning of a stored procedure. For the whole range of values, V1 works better or the same as T1. Now lets try the same with a primary key: create procedure V2 @total int as declare @V table (n int primary key, s varchar(128)) insert into @V select n,s from NUM where n%100>0 and n<=@total declare @res varchar(128) select @res=max(s) from NUM where n<=@total and not exists(select * from @V V where V.n=NUM.n) GO The result is much better, but T2 outruns this version. Records 10 100 1000 10000 100000 T1 0.7 1.2 7.1 72 T2 1 1.7 5.5 57 T3 13.5 14.2 27 82 580 V1 0.6 1.2 7 71 840 V2 0.8 1.3 5.3 48 510

883 480

1000000 45056 6090 15220 20240 12010 Table 1: Using SQL Server 2000, time in ms. But the real shock is when you try the same on SQL Server 2005:

N 10 100 1000 10000 100000

T1 0.5 2 9.3

T2 0.5 1.2

T3 5.3 6.4

V1 0.2 61.8 168 17133

V2 0.2 2.5 140 13910

8.5 13.5

67.4 79.2 71.3

700 794 659 Too long! Too long!

1000000 10556 8673 6440 Too long! Too long! Table 2: Using SQL Server 2005 (time in ms). In some cases, SQL 2005 was much faster then SQL 2000 (marked with green). But in many cases, especially with huge amounts of data, procedures that used table variables took much longer (highlighted with red). In four cases, I even gave up waiting.

Conclusion
1. There is no universal rule for when and where to use temporary tables or table variables. Try them both and experiment. 2. In your tests, verify both sides of the spectrumsmall numbers of records and huge data sets. 3. Be careful with migrating to SQL 2005 when you use complicated logic in your stored procedures. The same code can run 10-100 times slower on SQL server 2005!

4. C#'s const vs. readonly


A quick synopsis on the differences between 'const' and 'readonly' in C#:
'const':

Can't be static. Value is evaluated at compile time. Initiailized at declaration only.

'readonly':

Can be either instance-level or static. Value is evaluated at run time. Can be initialized in declaration or by code in the constructor.

5. What is Reflection? It extends the benefits of metadata by allowing developers to inspect and use it at runtime. For example, dynamically determine all the classes contained in a given assembly and invoke their methods. Reflection provides objects that encapsulate

assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. Namespace: System.Reflection 6. What is a Web Service? A web service is a software component that exposes itself through the open communication channels of the Internet. Applications running on remote machines, on potentially different platforms, can access these components in a language and platform-independent manner. A Web Service is a group of functions, packaged together for use in a common framework throughout a network.

7. Global.asax File?
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules. The Global.asax file resides in the root directory of an ASP.NET application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. ASP.NET is configured so that any direct URL request for the Global.asax file is automatically rejected; external users cannot download or view the code in it. The Global.asax file is optional. You create it only if you want to handle application or session events.

8. What is an Application Pool?


An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications. For example, if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool. Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need. When you configure application pools for optimum availability, you also should consider how to configure application pools for application security. For example, you might need to create separate application pools for applications that require a high level of security, while allowing applications that require a lower level of security to share the same application pool. In the later part of this article, we will see how to configure identities at the application pool level.

Open PopUp Window Update Refresh Parent Values From Child ASP.NET Parent Window
protected void Page_Load(object sender, EventArgs e) { string updateValuesScript = @"function updateValues(popupValues)

{ document.getElementById('lblFirstName').innerHTML=popupValues[0]; document.getElementById('lblLastName').innerHTML=popupValues[1]; }"; this.ClientScript.RegisterStartupScript(Page.GetType(), "UpdateValues", updateValuesScript.ToString(), true); btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')"); }

PopUp Window
protected void Page_Load(object sender, EventArgs e) { string updateParentScript = @"function updateParentWindow() { var fName=document.getElementById('txtPopFName').value; var lName=document.getElementById('txtPopLName').value; var arrayValues= new Array(fName,lName); window.opener.updateValues(arrayValues); window.close(); }"; this.ClientScript.RegisterStartupScript(this.GetType(), "UpdateParentWindow", updateParentScript, true); if (!IsPostBack) { txtPopFName.Text = Request["fn"]; txtPopLName.Text = Request["ln"]; } Button1.Attributes.Add("onclick", "updateParentWindow()"); }

9. State Management
State Management Techniques in ASP.NET This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested. Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user. Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client

side state management options. Client side State management Options: ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options. Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request. Cookie: A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. Let's see an example which makes use of cookies to customize web page. if (Request.Cookies["UserId"] != null) lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!"; else lbMessage.text = "Guest,welcome to our website!"; If you want to store client's information use the below code Response.Cookies["UserId"].Value=username; Advantages: Simplicity

Disadvantages: Cookies can be disabled on user browsers Cookies are transmitted for each HTTP request/response causing overhead on bandwidth Inappropriate for sensitive data

Hidden fields: Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field Hidden1.Value="Create hidden fields"; //to retrieve a value string str=Hidden1.Value; Advantages: Simple to implement for a page specific data Can store small amount of data so they take less size.

Disadvantages: Inappropriate for sensitive data Hidden field values can be intercepted(clearly visible) when passed over a network

View State: View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page. // Add item to ViewState ViewState["myviewstate"] = myValue; //Reading items from ViewState Response.Write(ViewState["myviewstate"]);

Advantages:
Simple for page level data Encrypted Can be set at the control level

Disadvantages: Overhead in encoding View State values Makes a page heavy

Query strings: Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep

in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode. Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4). When product details page is being requested, the product information can be obtained by using the following codes: string productid; productid=Request.Params["productid"]; Advantages: Simple to Implement

Disadvantages: Human Readable Client browser limit on URL length Cross paging functionality makes it redundant Easily modified by end user

Control State: Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page Server Side State management: As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server. Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage of sessions object for state management can create load on server causing performance degradation Application object: Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object. In classic ASP, application object is used to store connection strings. It's a great place to

store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea Application.Lock(); Application["mydata"]="mydata"; Application.UnLock(); Session object: Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file. Configuration information: <sessionState mode = <"inproc" | "sqlserver" | "stateserver"> cookieless = <"true" | "false"> timeout = <positive integer indicating the session timeout in minutes> sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode> server = <The server name that is only required when the mode is State Server> port = <The port number that is only required when the mode is State Server> Mode: This setting supports three options. They are InProc, SQLServer, and State Server Cookie less: This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one. Timeout: This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes SqlConnectionString: This identifies the database connection string that names the database used for mode SQLServer. Server: In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state. Port: This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application. Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability In process mode (in-memory)- State information is stored in memory of web server Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service. Database mode session state is maintained on a SQL Server database.

In process mode: This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server Configuration information: <sessionState mode="Inproc" sqlConnectionString="data source=server;user id=freelance;password=freelance" cookieless="false" timeout="20" /> Advantages: Fastest mode Simple configuration

Disadvantages: Session data will be lost if the worker process or application domain recycles Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode): This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line. Net start aspnet_state Configuration information: <sessionState mode="StateServer" StateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance" cookieless="false" timeout="20"/> Advantages: Supports web farm and web garden configuration Session data is persisted across application domain recycles. This is achieved by

using separate worker process for maintaining state Disadvantages: Out-of-process mode provides slower access compared to In process Requires serializing data

SQL-Backed Session state: ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts. SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state. Configuration Information: <sessionState mode="SQLServer" sqlConnectionString="data source=server;user id=freelance;password=freelance" cookieless="false" timeout="20" /> Advantages: Supports web farm and web garden configuration Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.

Disadvantages: Requires serialization of objects

Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications. When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests. Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

10.Asp .net Page Life Cycle


Stage Page request Description The page request occurs before the page life cycle begins. When the page is

requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an Postback event exception to this sequence: the handler for the event that caused validation is handling called after validation.)

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Update Panel

If you have been following my articles, you would have realised how easy it is to implement partial page refreshing in ASP.NET AJAX where we explored a single UpdatePanel and multiple Update Panel examples. Let us now consider a more complex scenario where we want to nest Update Panels.

Page UpdatePanel 1 (Parent) UpdatePanel 2 (Child) The thumb rule with nested update panels is as follows:Parent Update Panel refreshes all the contents including Child Update Panel's contents even if the Child Update Panel's update mode is set to Conditional Child Update Panel refreshes only its contents and doesnt refresh that of the Parent Update Panel unless, the update mode for the parent update panel is not set to Conditional Kind of confusing eh? Let us see it in action. Copy paste the following HTML and the subsequent source code to see it in action. <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div> <table width="80%" border="3"> <tr> <td> Label outside all the Update Panels <asp:Label ID="Label3" runat="Server" FontBold="true"></asp:Label> <br /> <br /> <asp:Button ID="Button3" runat="Server" Text="Refresh" /> <br /> <br /> </td> </tr> <tr> <td> <table width="65%" border="2"> <tr> <td> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> Label within the Parent Update Panel <asp:Label ID="Label1" runat="server" FontBold="true"></asp:Label> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Refresh" /> <table width="40%" border="1">

<tr> <td>

<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"> <ContentTemplate> <br /> <br /> Label within the Child Update Panel <asp:Label ID="Label2" runat="server" FontBold="True"></asp:Label> <br /> <br /> <asp:Button ID="Button2" runat="server" Text="Refresh" /> </ContentTemplate> </asp:UpdatePanel> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel> </td> </tr> </table> </td> </tr> </table> </div> </form> Code behind protected void Page_Load(object sender, EventArgs e) { Label1.Text = System.DateTime.Now.ToString(); Label2.Text = System.DateTime.Now.ToString(); Label3.Text = System.DateTime.Now.ToString(); } When you run the above page, you will notice that I have put nice looking (??) tables to clearly indicate the label outside the Update Panels, the parent update panel contents and the child update panel contents.

When you click on the top most button, it refreshes the whole page and subsequently, all the labels get refreshed with the new date time. However, when you click on the second refresh button which is marked inside the Parent Update Panel you will notice that the top most label doesnt get refreshed but both the Label 2 and Label 3 gets refreshed, although I have marked UpdateMode as conditional for the Child UpdatePanel. The reason being, the parent updates all the child update panels nested within. Finally, when you click on the last Refresh button which is marked inside the Child Update Panel, you will notice that only the respective label gets refreshed. Note that, if I remove the property UpdateMode=Conditional for the UpdatePanel1 (parent), both the labels will get refreshed. 11. What is the difference between clustered and a non-clustered index? A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. 12. Difference between data set and data reader? Data Set is a connectionless service and Data reader is a connection oriented service. Dataset is used to store the data, it contains collections of Datatable. Datareader is used to connect to the database for retrieving data. Data Reader - Forward only where as Dataset - Can loop through dataset. Data Reader - Connected Recordset where as DataSet - Disconnected Recordset Data Reader - Less Memory Occupying where as DataSet - It occupies more memory Data Reader - Only Single Table can be used where as Dataset - Datatable Concept allows data to be stored in multiple tables. Data Reader - Read only where as DataSet - Can add/update/delete using the dataset Data Reader - No relationship can be maintained where as DataSet - Relationship can be maintained. Data Reader - No Xml Storage available where as DataSet - Can be stored as XML. The Dataset is a core of disconnected architecture. Disconnected architecture means once you have retrieved the data from the database the data source is dropped. The disconnected data become very commonly. The dataset for the disconnected data from the Dataset object. The DataReader is a readonly, forward only stream from the database. While using the datareader can improve the application performance reduces the system overhead because only one buffer row at a time in memory.

13. ASP.NET PAGE DIRECTIVE page directive, register directive, master directive,mastertype directive, control directive, import directive, implements directive, outputcache directive, assembly directive, previouspagetype directive, reference directive.
ASP.NET provides the number of directives with the help of it we can control the behavior of ASP.NET Pages. We have 11 directives that we can use in our ASP.NET pages or user controls. We can use these directives regardless we are using Inline Coding Model or Code-Behind Model. These directives are the commands that complier uses when the page is compiled. Format to write the directive is given below <%@ Directive attribute= value %> Now lets talk about the number of directives that are provided in ASP.NET one by one

14. What is the difference between Web Farm and Web Garden ? October 1, 2010
Posted by Abhijit Jana in ASP.NET, ASP.NET 4.0, IIS. Tags: ASP.Net, Beginners, codeproject, Difference between Web Farm and Web Garden, IIS, Web Farm Vs Web Garden trackback

I have been asked this question many times by different readers of my blog. They wanted to know about the fundamentals of Web Farms and Web Garden . In this blog post I am going to explain the what is the exact difference between web farm and web garden, what are the advantages and disadvantages of using them. I have also described how to create web garden in different version of IIS. Overview : Visual Studio having its own integrated ASP.NET engine which is used to run the ASP.NET Web application from Visual Studio. ASP.NET Development Server is responsible for execute all the request and response from client. Now after the end of development, when you want to host the site on some server to allow other peoples to access, concept of web servers comes in between. A web server is responsible for provide the response for all the requests that are coming from clients. Below diagram showing the typical deployment structure of a ASP.NET Web application with a single IIS.

Clients request for resources and IIS Process the request and send back to clients. If you want to know more details on How IIS Process the request please read one of my article over How IIS Process ASP.NET Request ? . Web Farm : This is the case, where you have only one web server and multiple clients requesting for the resources from the same server. But when there is huge numbers of incoming traffic for your web sites, one standalone server is not sufficient to process the request. You may need to use multiple server to host the application and divide the traffic among them. This is called Web Farm . So when you are hosting your single web site on multiple web server over load balancer called Web Farm. Below diagram showing the over all representation of Web Farms.

In general web farm architecture, a single application is hosted on multiple IIS Server and those are connected with the VIP ( Virtual IP ) with Load Balancer. Load Balancer IPs exposed to external worlds to access. So whenever some request will come to server from clients, it will first hit the Load Balancer, then based on the traffic on each server LB distributed the request to corresponding web server. These web server may share same DB server or may be they can use replicated server in the back end. So, In a single statement, When we host a web application over multiple web server to distributed the load among them is called Web Farm. Web Garden :

Now, lets have a look, what is Web Garden ? Both the terms sounds same, but they are totally different with each other. Before starting with Web Garden, I hope you have fundamental idea of what is Application Pool and what is Worker Process. If you have already read the article How IIS Process ASP.NET Request ? article then I can expect that you have now good idea on both of them. Just to recall, When we are talking about requesting processing with in IIS, Worker Process (w3wp.exe ) takes care all of these. Worker Process runs the ASP.Net application in IIS. All the ASP.Net functionality inside IIS runs under the scope of worker process. Worker Process is responsible for handling all kind of request, response, session data, cache data. Application Pool is the container of worker process. Application pools is used to separate sets of IIS worker processes and enables a better security, reliability, and availability for any web application.

Now, by default each and every Application pool contains a single worker process. Application which contains the multiple worker process called Web Garden. Below is the typical diagram for a web garden application.

In the above diagram you can see, on of the application containing the multiple worker process, which is now a web garden. So, a Web application hosted on multiple server and access based on the load on servers is called Web Farms and When a single Application pool contain multiple Worker process is called web garden. Create Web Garden in IIS 6 and IIS 7 Now, I am going to show how you can change the Number of Worker process In both IIS 6 and IIS 7. For IIS 6, Right Click on Application Pool > Properties > Goto Performance Tab.

In the Performance Tab Section you would have one option called Web Garden where worker process sets to 1, you can set the number of worker process that you required. For IIS 7, Right Click on Application Pool > Go To Advance Settings > In Process Model section, you will have Maximum Worker Processes . You can change it more than 1 to make it as web garden.

In the above image you can also check the definition of Web Garden also. You can find one of my previous article on the basic of same over here Advantages of Web Farm and Web Garden : Now, lets have a look in to the advantages of both the Web farms and Web Garden. Advantages of Web Farm

It provides high availability. If any of the server in the farm goes down, Load balancer can redirects the requests to other servers. Provides high performance response for client requests. Provides Better scalability of the web application and reduce the failure of application. Session and other resource can be stored in a centralized location to access by the all server.

Advantages of Web Garden:


provides better application availability by sharing request between multiple worker process. Web garden use processor affinity where application can swapped out based on preference and tag setting. Less consumption of physical space for web garden configuration.

How to manage session in Web Farm Mode ? While using session, requests are distributed among different servers. By default session mode is set to In Proc where session data stored inside worker process memory. But, In Web farm mode we can share the session among all the server using a single session store location my making it Out proc (State Server or SQL Server Mode). So, if some of the server goes down and request transferred to the other server by the Load balancer session data should be available for that request.

In the above diagram, you can see we can both the IIS server sharing the same session data which is stored in out of worker process. You can read one of my previous article Exploring Session in ASP.NET where I have explained how you can configure session mode for Out Process mode. How to manage session in Web Garden Mode ? When we are using Web garden where request is being taking care by different worker process we have to make the session mode as out process session mode as described earlier. For Web Garden we have configure the out process with in same server but for different worker process.

While using Web garden with your application you need do couple of configuration settings in web.config in <process Model> section where you need to set certain properties like cpuMask, RequestLimit, webGarden, ClientConnectCheck etc. Summary : When we host a web application over multiple web server to distributed the load among them is called Web Farm and when One application having multiple worker worker process called Web garden. In this blog post I have explained the very basics of what Web Farm is and what Web Garden is. As this blog post contains the basic information to understand the fundamentals of web farms and web garden concept, I will be posting a separate article with details configuration setting for web garden and web farm. You can read those below articles for more information

15. Garbage Collection in .Net framework


The garbage collection (GC) is new feature in Microsoft .net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in the memory. The earlier releases of Microsoft products have used a method like once the process of that object get finished then it will be cleared from the memory. For instance Visual Basic, An object get finishes that work then there we have to define a "nothing" to that object. So, it clears the memory space to the processors. Microsoft was planning to introduce a method that should automate the cleaning of unused memory space in the heap after the life time of that object. Eventually they have introduced a new technique "Garbage collection". It is very important part in the .Net framework. Now it handles this object clear in the memory implicitly. It overcomes the existing explicit unused memory space clearance. Garbage Collection The heap memory is divided into number of generations. Normally it is three generations. The Generation 0 is for short live objects, Generation 1 is for medium live objects which are moved from Generation 0. Generation 3 is mostly stable objects.

When an object is created then it will allocate the memory space which will be higher. It will be in the Generation 0 and the memory allocation will be continuous without any space between the generations of garbage collectors. How it works Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation. The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process. Exception Handling The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory. If we want to forces to collect unused objects or explicitly release particular object from the momory.The code allows us to clear the object from the heap immediately.

When it happens
The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory. When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor. If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects. Example code to know more about Garbage Collection The Microsoft framework System namespace have the GC class, which exposes more method and property about garbage collection. MaxGeneration This property in the GC class returns the total number of generations. .NET supports two kind of coding

16.

Managed Code and Unmanaged Code

Managed Code Unmanaged Code

Managed Code

The resource, which is with in your application domain is, managed code. The resources that are within domain are faster.

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.

Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

Unmanaged Code The code, which is developed outside .NET, Framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code. Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged code is executed with help of wrapper classes.

Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper). Wrapper is used to cover difference with the help of CCW and RCW.

COM callable wrapper unmanaged code execution

Runtime Callable Wrapper unmanaged code execution

I hope that this article would have helped you in understanding managed and unmanaged .NET.

17.

Constructor types with example programs in C#.NET

A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor. Constructors can be classified into 5 types 1. 2. 3. 4. 5. Default Constructor Parameterized Constructor Copy Constructor Static Constructor Private Constructor

Default Constructor : A constructor without any parameters is called as default constructor. Drawback of default constructor is every instance of the class will be initialized to same values and it is not possible to initialize each instance of the class to different values. Example for Default Constructor Parameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values. Example for Parameterized Constructor
using System; namespace ProgramCall { class Test1 { //Private fields of class int A, B; //default Constructor public Test1() { A = 10; B = 20; } //Paremetrized Constructor public Test1(int X, int Y) { A = X; B = Y; }

//Method to print public void Print() { Console.WriteLine("A } = {0}\tB = {1}", A, B);

class MainClass { static void Main() { Test1 T1 = new Test1(); //Default Constructor is called Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called T1.Print(); T2.Print(); Console.Read(); } } }

Output A = 10 A = 80 B = 20 B = 40

Copy Constructor : A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Example for Copy Constructor
using System; namespace ProgramCall { class Test2 {

int A, B; public Test2(int X, int Y) { A = X; B = Y; } //Copy Constructor public Test2(Test2 T) { A = T.A; B = T.B; }

public void Print() { Console.WriteLine("A } = {0}\tB = {1}", A, B);

class CopyConstructor { static void Main() {

Test2 T2 = new Test2(80, 90); //Invoking copy constructor Test2 T3 = new Test2(T2); T2.Print(); T3.Print(); Console.Read(); } } }

Output A = 80 A = 80 B = 90 B = 90

Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once. Example for Static Constructor
using System; namespace ProgramCall { class Test3 { public Test3() { Console.WriteLine("Instance } static Test3() { Console.WriteLine("Static } Constructor");

Constructor");

} class StaticConstructor { static void Main() { //Static Constructor and instance constructor, both are invoked for first instance. Test3 T1 = new Test3(); //Only instance constructor is invoked. Test3 T2 = new Test3();

Console.Read(); } } }

Output Static Constructor Instance Constructor Instance Constructor


Private Constructor : You can also create a constructor as private. When a class contains at least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static.

Some unique points related to constructors are as follows


A class can have any number of constructors. A constructor doesnt have any return type even void. A static constructor can not be a parameterized constructor. Within a class you can create only one static constructor.

18.

AJAX Triggers

Triggers for a given UpdatePanel, by default, automatically include any child controls that invoke a postback, including (for example) TextBox controls that have their AutoPostBack property set to true. However, triggers can also be included declaratively using markup; this is done within the <triggers> section of the UpdatePanel control declaration. Although triggers can be accessed via the Triggers collection property, it is recommended that you register any partial render triggers at run-time (for instance, if a control is not available at design time) by using the RegisterAsyncPostBackControl(Control) method of the ScriptManager object for your page, within the Page_Load event. Remember that Pages are stateless, and so you should re-register these controls every time they are created. Automatic child trigger inclusion can also be disabled (so that child controls that create postbacks do not automatically trigger partial renders) by setting the ChildrenAsTriggers property to false. This allows you the greatest flexibility in assigning which specific controls may invoke a page render, and is recommended, so that a developer will opt-in to respond to an event, rather than handling any events that may arise. Note that when UpdatePanel controls are nested, when the UpdateMode is set to Conditional, if the child UpdatePanel is triggered, but the parent is not, then only the child UpdatePanel will refresh. However, if the parent UpdatePanel is refreshed, then the child UpdatePanel will also be refreshed.

The <Triggers> Element


When working in the markup editor in Visual Studio, you may notice (from IntelliSense) that there are two child elements of an UpdatePanel control. The most-frequently seen element is

the <ContentTemplate> element, which essentially encapsulates the content that will be held by the update panel (the content for which we are enabling partial rendering). The other element is the <Triggers> element, which specifies the controls on the page (or the user control, if you are using one) that will trigger a partial render of the UpdatePanel control in which the <Triggers> element resides. The <Triggers> element can contain any number each of two child nodes: <asp:AsyncPostBackTrigger> and <asp:PostBackTrigger>. They both accept two attributes, ControlID and EventName, and can specify any Control within the current unit of encapsulation (for instance, if your UpdatePanel control resides within a Web User Control, you should not attempt to reference a Control on the Page on which the User Control will reside). The <asp:AsyncPostBackTrigger> element is particularly useful in that it can target any event from a Control that exists as a child of any UpdatePanel control in the unit of encapsulation, not just the UpdatePanel under which this trigger is a child. Thus, any control can be made to trigger a partial page update. Similarly, the <asp:PostBackTrigger> element can be used to trigger a partial page render, but one that requires a full round-trip to the server. This trigger element can also be used to force a full page render when a control would otherwise normally trigger a partial page render (for instance, when a Button control exists in the <ContentTemplate> element of an UpdatePanel control). Again, the PostBackTrigger element can specify any control that is a child of any UpdatePanel control in the current unit of encapsulation.

<Triggers> Element Reference


Markup Descendants:
Tag Description

<asp:AsyncPostBackTrigger> Specifies a control and event that will cause a partial page update for the UpdatePanel that contains this trigger reference. <asp:PostBackTrigger> Specifies a control and event that will cause a full page update (a full page refresh). This tag can be used to force a full refresh when a control would otherwise trigger partial rendering.

Walkthrough: Cross-UpdatePanel Triggers


1. Create a new ASP.NET page with a ScriptManager object set to enable partial rendering. Add two UpdatePanels to this page - in the first, include a Label control ( Label1 ) and two Button controls ( Button1 and Button2 ). Button1 should say Click to Update Both and Button2 should say Click to Update This, or something along those lines. In the second UpdatePanel, include only a Label control ( Label2 ), but set its ForeColor property to something other than the default to differentiate it. 2. Set the UpdateMode property of both UpdatePanel tags to Conditional.

Listing 1: Markup for default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager EnablePartialRendering="true" ID="ScriptManager1" runat="server"></asp:ScriptManager> <div> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label1" runat="server" /><br /> <asp:Button ID="Button1" runat="server" Text="Update Both Panels" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="Update This Panel" OnClick="Button2_Click" /> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label2" runat="server" ForeColor="red" /> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" /> </Triggers> </asp:UpdatePanel> </div> </form> </body> </html>

1. In the Click event handler for Button1, set Label1.Text and Label2.Text to something timedependent (such as DateTime.Now.ToLongTimeString()). For the Click event handler for Button2, set only Label1.Text to the time-dependent value.

Listing 2: Codebehind (trimmed) in default.aspx.cs:


public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToLongTimeString(); Label2.Text = DateTime.Now.ToLongTimeString(); } protected void Button2_Click(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToLongTimeString(); } }

1. Press F5 to build and run the project. Note that, when you click Update Both Panels , both labels change text; however, when you click Update This Panel, only Label1 updates.

(Click to view full-size image)

Under the Hood


Utilizing the example we just constructed, we can take a look at what ASP.NET AJAX is doing and how our UpdatePanel cross-panel triggers work. To do so, we will work with the generated page source HTML, as well as the Mozilla Firefox extension called FireBug - with it, we can easily examine the AJAX postbacks. We will also use the .NET Reflector tool by Lutz Roeder. Both of these tools are freely available online, and can be found with an internet search. An examination of the page source code shows almost nothing out of the ordinary; the UpdatePanel controls are rendered as <div> containers, and we can see the script resource includes provided by the <asp:ScriptManager>. There are also some new AJAX-specific calls to the PageRequestManager that are internal to the AJAX client script library. Finally, we see the two UpdatePanel containers - one with the rendered <input> buttons with the two <asp:Label> controls rendered as <span> containers. (If you inspect the DOM tree in FireBug, you will notice that the labels are dimmed to indicate that they are not producing visible content). Click the Update This Panel button, and notice the top UpdatePanel will be updated with the current server time. In FireBug, choose the Console tab so that you can examine the request. Examine the POST request parameters first:

(Click to view full-size image) Note that the UpdatePanel has indicated to the server-side AJAX code precisely which control tree was fired via the ScriptManager1 parameter: Button1 of the UpdatePanel1

control. Now, click on the Update Both Panels button. Then, examining the response, we see a pipe-delimited series of variables set in a string; specifically, we see the top UpdatePanel, UpdatePanel1, has the entirety of its HTML sent to the browser. The AJAX client script library substitutes the UpdatePanel's original HTML content with the new content via the .innerHTML property, and so the server sends the changed content from the server as HTML. Now, click on the Update Both Panels button and examine the results from the server. The results are very similar - both UpdatePanels receive new HTML from the server. As with the previous callback, additional page state is sent. As we can see, because no special code is utilized to perform an AJAX postback, the AJAX client script library is able to intercept form postbacks without any additional code. Server controls automatically utilize JavaScript so that they do not automatically submit the form ASP.NET automatically injects code for form validation and state already, primarily achieved by automatic script resource inclusion, the PostBackOptions class, and the ClientScriptManager class. For instance, consider a CheckBox control; examine the class disassembly in .NET Reflector. To do so, ensure that your System.Web assembly is open, and navigate to the System.Web.UI.WebControls.CheckBox class, opening the RenderInputTag method. Look for a conditional that checks the AutoPostBack property:

(Click to view full-size image) When automatic postback is enabled on a CheckBox control (via the AutoPostBack property being true), the resultant <input> tag is therefore rendered with an ASP.NET event handling script in its onclick attribute. The interception of the form's submission, then, allows ASP.NET AJAX to be injected into the page nonintrusively, helping to avoid any potential breaking changes that might occur by utilizing a possibly-imprecise string replacement. Furthermore, this enables any custom ASP.NET control to utilize the power of ASP.NET AJAX without any additional code to support its use within an UpdatePanel container. The <triggers> functionality corresponds to the values initialized in the PageRequestManager call to _updateControls (note that the ASP.NET AJAX client script library utilizes the convention that methods, events, and field names that begin with an

underscore are marked as internal, and are not meant for use outside of the library itself). With it, we can observe which controls are intended to cause AJAX postbacks. For example, let's add two additional controls to the page, leaving one control outside of the UpdatePanels entirely, and leaving one within an UpdatePanel. We will add a CheckBox control within the upper UpdatePanel, and drop a DropDownList with a number of colors defined within the list. Here is the new markup: Listing 3: New Markup
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager EnablePartialRendering="true" ID="ScriptManager1" runat="server"></asp:ScriptManager> <div> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label1" runat="server" /><br /> <asp:Button ID="Button1" runat="server" Text="Update Both Panels" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="Update This Panel" OnClick="Button2_Click" /> <asp:CheckBox ID="cbDate" runat="server" Text="Include Date" AutoPostBack="false" OnCheckedChanged="cbDate_CheckedChanged" /> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label2" runat="server" ForeColor="red" /> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" /> <asp:AsyncPostBackTrigger ControlID="ddlColor" EventName="SelectedIndexChanged" /> </Triggers> </asp:UpdatePanel> <asp:DropDownList ID="ddlColor" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlColor_SelectedIndexChanged"> <asp:ListItem Selected="true" Value="Red" /> <asp:ListItem Value="Blue" /> <asp:ListItem Value="Green" /> </asp:DropDownList> </div> </form>

</body> </html>

And here is the new code-behind: Listing 4: Codebehind


public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { if (cbDate.Checked) { Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); Label2.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); } else { Label1.Text = DateTime.Now.ToLongTimeString(); Label2.Text = DateTime.Now.ToLongTimeString(); } } protected void Button2_Click(object sender, EventArgs e) { if (cbDate.Checked) { Label1.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); } else { Label1.Text = DateTime.Now.ToLongTimeString(); } } protected void cbDate_CheckedChanged(object sender, EventArgs e) { cbDate.Font.Bold = cbDate.Checked; } protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e) { Color c = Color.FromName(ddlColor.SelectedValue); Label2.ForeColor = c; } }

The idea behind this page is that the drop-down list selects one of three colors to show the second label, that the check box determines both whether it is bold, and whether the labels display the date as well as the time. The check box should not cause an AJAX update, but the drop-down list should, even though it is not housed within an UpdatePanel.

(Click to view full-size image) As is apparent in the above screen shot, the most-recent button to be clicked was the right button Update This Panel, which updated the top time independent of the bottom time. The date was also switched off between clicks, as the date is visible in the bottom label. Finally of interest is the bottom label's color: it was updated more recently than the label's text, which demonstrates that control state is important, and users expect it to be preserved through AJAX postbacks. However, the time was not updated. The time was automatically repopulated through the persistence of the __VIEWSTATE field of the page being interpreted by the ASP.NET runtime when the control was being re-rendered on the server. The ASP.NET AJAX server code does not recognize in which methods the controls are changing state; it simply repopulates from view state and then runs the events that are appropriate. It should be pointed out, however, that had I initialized the time within the Page_Load event, the time would have been incremented correctly. Consequently, developers should be wary that the appropriate code is being run during the appropriate event handlers, and avoid use of Page_Load when a control event handler would be appropriate.

Summary
The ASP.NET AJAX Extensions UpdatePanel control is versatile, and can utilize a number of methods for identifying control events that should cause it to be updated. It supports being updated automatically by its child controls, but can also respond to control events elsewhere on the page. To reduce potential for server processing load, it is recommended that the ChildrenAsTriggers property of an UpdatePanel be set to false, and that events be optedinto rather than included by default. This also prevents any unneeded events from causing potentially-unwanted effects, including validation, and changes to input fields. These types of bugs may be difficult to isolate, because the page updates transparently to the user, and the cause may therefore not be immediately obvious. By examining the inner workings of the ASP.NET AJAX form post interception model, we were able to determine that it utilizes the framework already provided by ASP.NET. In doing so, it preserves maximum compatibility with controls designed using the same framework, and intrudes minimally on any additional JavaScript written for the page.

19.

Partial Class Definitions (C# Programming Guide)

It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. There are several situations when splitting a class definition is desirable:

When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio. To split a class definition, use the partial keyword modifier, as shown below:

C#
public partial class Employee { public void DoWork() { } } public partial class Employee { public void GoToLunch() { } }

20.Grid View Events


Events

Name DataBinding

Description Occurs when the server control binds to a data source. (Inherited from Control.) Occurs after the server control binds to a data source. (Inherited from BaseDataBoundControl.) Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested. (Inherited from Control.) Occurs when the server control is initialized, which is the first step in its

DataBound

Disposed

Init

lifecycle. (Inherited from Control.) Load Occurs when the server control is loaded into the Page object. (Inherited from Control.) Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.) Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode. Occurs when a button is clicked in a GridView control. Occurs when a row is created in a GridView control. Occurs when a data row is bound to data in a GridView control. Occurs when a row's Delete button is clicked, but after the GridView control deletes the row. Occurs when a row's Delete button is clicked, but before the GridView control deletes the row. Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. Occurs when a row's Update button is clicked, but after the GridView control updates the row. Occurs when a row's Update button is clicked, but before the GridView control updates the row. Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation.

PageIndexChanged

PageIndexChanging

PreRender

RowCancelingEdit RowCommand RowCreated RowDataBound RowDeleted

RowDeleting

RowEditing

RowUpdated

RowUpdating

SelectedIndexChanged

SelectedIndexChanging

Sorted

Sorting

Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. Occurs when the server control is unloaded from memory. (Inherited from Control.)

Unload

21. Nth Highest Salary sql Query:


SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP 6 salary FROM employee ORDER BY salary DESC) a ORDER BY salary

Nth Highest Salary: You can change and use it for getting nth highest salary from Employee table as follows
SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP n salary FROM employee ORDER BY salary DESC) a ORDER BY salary

SELECT * FROM EMP E WHERE (1) = (SELECT COUNT(DISTINCT BASIC) FROM EMP M WHERE M.BASIC>=E.BASIC)

Difference between primary key & unique key Index Stored Procedure Triggers Joins Encapsulation Polymorphism Abstraction

Inheritance Datatable Import Export excel files Execute Nonquery Collections State management Webservice Windows service Transaction Logical Questions Self join Query

Вам также может понравиться