Vous êtes sur la page 1sur 65

CONSTRAINTS Constraints: Rules defined on the table which cannot be violated by the users.

A constraint is a property assigned to a column or the set of columns in a table that prevents certain types of inconsistent data values from being placed in the column(s). Constraints are used to enforce the data integrity. This ensures the accuracy and reliability of the data in the database Types: Domain Integerity Constraints: Check: Limits the range of values or domain, checks the values which a col can have. CREATE TABLE employee( EmployeeId INT NOT NULL, LName VARCHAR(30) NOT NULL, FName VARCHAR(30) NOT NULL, Address VARCHAR(100) NOT NULL, HireDate DATETIME NOT NULL, Salary MONEY NOT NULL CONSTRAINT check_sale CHECK (salary > 0) ) -- disable the check_sale constraint in the employee table ALTER TABLE employee NOCHECK CONSTRAINT check_sale -- enable the check_sale constraint in the employee table ALTER TABLE employee CHECK CONSTRAINT check_sale Referntial Integrity Constraints: Foreign Key: Referntial integrity b/w 2 tables, one table col values based on other table col values. CREATE TABLE Books ADD CONSTRAINT fk_author FOREIGN KEY (AuthorID) REFERENCES Authors (AuthorID) ON DELETE CASCADE Entity Integrity Constraints: Default Constraint: defines the default value for a column. Null: allows null value. NOT null:Donot allow null value. Primary Key: Ensure no duplicate data and not allow nulls. --Add primary key to a table after creating ALTER TABLE employee ADD CONSTRAINT pk_employee PRIMARY KEY (EmployeeId) Unique Key: donot allow duplicate values, but allows one null per col.Can have multiple unique constraints on a table

DOTNET MATERIAL

Page 1

What are different normalization forms? 1NF: Eliminate Repeating Groups Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain. 2NF: Eliminate Redundant Data If an attribute depends on only part of a multivalued key, remove it to a separate table. 3NF: Eliminate Columns Not Dependent On Key If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key. (Read More Here) BCNF: BoyceCodd Normal Form If there are nontrivial dependencies between candidate key attributes, separate them out into distinct tables. 4NF: Isolate Independent Multiple Relationships No table may contain two or more 1:n or n:m relationships that are not directly related. 5NF: Isolate Semantically Related Multiple Relationships There may be practical constrains on information that justify separating logically related manytomany relationships. ONF: Optimal Normal Form A model limited to only simple (elemental) facts, as expressed in Object Role Model notation. DKNF: DomainKey Normal Form A model free from all modification anomalies is said to be in DKNF. Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database. ACID Properties: Atomicity is an all-or-none proposition. Consistency guarantees that a transaction never leaves your database in a half-finished state. Isolation keeps transactions separated from each other until theyre finished. Durability guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination Delete the Duplicate rows in a table ? SET ROWCOUNT 1 SELECT 'start' WHILE @@ROWCOUNT > 0 DELETE E1 FROM EMP2 E1 WHERE (SELECT count(*) FROM EMP2 WHERE EMP2.EMPID=E1.EMPID) >1 SET ROWCOUNT 0

DOTNET MATERIAL

Page 2

To find the nth record in a table ? SELECT * FROM Employee E1 WHERE (N-1) = (SELECT Count(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary > E1.Salary) Ex: To Find the 2nd Highest salary in the following table. 1 2 4 5 6 HELLO 100 HELLO1 Ravi kiran sand dilip 200 300 50 120

SELECT * FROM Employee E1 WHERE (2-1) = (SELECT Count(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary > E1.Salary) or SELECT TOP 1 salary FROM employee WHERE salary IN (SELECT TOP 2 salary FROM employee ORDER by salary DESC) ORDER by salary asc SQL JOINS I have used the following 2 tables Employee and Department as examples. Employee Table :- Department Table:EmployeeID EmployeeName DepartmentID DepartmentID DepartmentName ****************************************************************************** ***** Inner Join An Inner Join will take two tables and join them together based on the values in common columns ( linking field ) from each table. Example 1 :- To retrieve only the information about those employees who are assinged to a department. Select Employee.EmployeeID,Employee.EmployeeName,Department.DepartmentName From Employee Inner Join Department on Employee.DepartmentID = Department.DepartmentID

DOTNET MATERIAL

Page 3

Example 2:- Retrieve only the information about departments to which atleast one employee is assigned. Select Department.DepartmentID,Department.DepartmentName From Department Inner Join Employee on Employee.DepartmentID = Department.DepartmentID ****************************************************************************** ***** Outer Joins :Outer joins can be a left, a right, or full outer join. Left outer join selects all the rows from the left table specified in the LEFT OUTER JOIN clause, not just the ones in which the joined columns match. Example 1:- To retrieve the information of all the employees along with their Department Name if they are assigned to any department. Select Employee.EmployeeID,Employee.EmployeeName,Department.DepartmentName From Employee LEFT OUTER JOIN Department on Employee.DepartmentID = Department.DepartmentID

Right outer join selects all the rows from the right table specified in the RIGHT OUTER JOIN clause, not just the ones in which the joined columns match. (Default join is RIGHT OUTER JOIN) Example 2:- use Right Outer join to retrieve the information of all the departments along with the detail of EmployeeName belonging to each Department, if any is available. Select Department.DepartmentID,Department.DepartmentName,Employee.EmployeeName From Employee Outer Join Department on Employee.DepartmentID = Department.DepartmentID This query will result in Null value for Employee Name where no Employee is assigned to that department CROSS JOIN: A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first DOTNET MATERIAL

Page 4

table multiplied by the number of rows in the second table *** However, if a WHERE clause is added, the cross join behaves as an inner join. For example, the following Transact-SQL queries produce the same result set. SELECT p.SalesPersonID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER BY p.SalesPersonID SELECT p.SalesPersonID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t WHERE p.TerritoryID = t.TerritoryID ORDER BY p.SalesPersonID; -- OR SELECT p.SalesPersonID, t.Name AS Territory FROM Sales.SalesPerson p INNER JOIN Sales.SalesTerritory t ON p.TerritoryID = t.TerritoryID ORDER BY p.SalesPersonID SELF JOIN: Self join is just like any other join, except that two instances of the same table will be joined in the query Here is an example: SoftwareDevelopers table which contains rows for normal SoftwareDevelopers as well as Projectmanagers. So, to find out the Projectmanagers of all the SoftwareDevelopers, you need a self join. CREATE TABLE SoftwareDevelopers ( SoftwareDeveloperID int, ProjectManagerID int, DeveloperName char(10) ) SoftwareDeveloperID 1 2 3 4 4 5 ProjectManagerID 2 1 DeveloperName Amulya Chintu Keeru Neeru

Select sd.DeveloperName SoftwareDevelopers sd inner join SoftwareDevelopers pm on pm.SoftwareDeveloperID=sd.ProjectManagerID

DOTNET MATERIAL

Page 5

Answer :

Amulya Chintu.

What is Difference between Function and Stored Procedure? 1>Procedure can return zero or n values whereas function can return one value which is mandatory. 2>Procedures can have input,output parameters for it whereas functions can have only input parameters. 3>Procedure allow select as well as DML statement in it whereas function allow only select statement in it. 4>Functions can be called from procedure whereas procedures cannot be called from function. 5>Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function. 6>We can go for transaction management in procedure whereas we can't go in function. 7>Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.

Index: An index can be created by selecting one or more columns in a table that is being searched. What are the difference between clustered and a nonclustered 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 non clustered 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 non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

What's the difference between a primary key and a unique key? Both primary key and unique key enforces uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a non clustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. (Read More Here) What is difference between DELETE & TRUNCATE commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. TRUNCATE 1 TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. 2 TRUNCATE removes the data by deallocating the data pages used to store the tables data, and only the page deallocations are recorded in the transaction log.

DOTNET MATERIAL

Page 6

3 TRUNCATE removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column. 4 You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. 5 TRUNCATE cannot be rolled back. 6 TRUNCATE is DDL Command. 7 TRUNCATE Resets identity of the table DELETE 1 DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. 2 If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. 3 DELETE Can be used with or without a WHERE clause 4 DELETE Activates Triggers. 5 DELETE can be rolled back. 6 DELETE is DML Command. 7 DELETE does not reset identity of the table.

What is the difference between UNION and UNION ALL ? UNION: The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected. UNION ALL The UNION ALL command is equal to the UNION command,except that UNION ALL selects all values. The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

VIEW: A view is a virtual table that consists of columns from one or more tables. Though it is similar to a table, it is stored in the database. It is a query stored as an object. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as base or underlying tables. Once you have defined a view, you can reference it like any other table in a database. A view serves as a security mechanism. This ensures that users are able to retrieve and modify only the data seen by them. Users cannot see or access the remaining data in the underlying tables. A view also serves as a mechanism to simplify query execution. Complex queries can be stored in the form as a view, and data from the view can be extracted using simple queries.

DOTNET MATERIAL

Page 7

A view consists of a SELECT statement that stored with a database. Because views are stored as part of the database, they can be managed independently of the applications that use them. A view behaves like a virtual table. Since you can code a view name anywhere you can code a table name. a view is sometimes called a viewed table. Views can be used to restrict the data that a user is allowed to access or to present data in a form that is easy for the user to understand. In some database users may be allowed to access data only through views.

Stored Procedure A stored procedure is a set of one or more SQL statements that are stored together in database. To create a stored procedure use CREATE PROCEDURE statement. To use the stored procedure you send a request for it to be executed. When server receives the request, it executes the stored procedure. Stored procedures assist in achieving a consistent implementation of logic across applications. The SQL statements and logic needed to perform a commonly performed task can be designed, coded, and tested once in a stored procedure. Each application needing to perform that task can then simply execute the stored procedure. Coding business logic into a single stored procedure also offers a single point of control for ensuring that business rules are correctly enforced. Stored procedures can also improve performance. Many tasks are implemented as a series of SQL statements. Conditional logic applied to the results of the first SQL statements determines which subsequent SQL statements are executed. If these SQL statements and conditional logic are written into a stored procedure, they become part of a single execution plan on the server. The results do not have to be returned to the client to have the conditional logic applied; all of the work is done on the server. There are some concepts of stored procedures. A stored procedure is one or more SQL statements that have been compiled and stored with database. A stored procedure can be started by application code on the client. Stored procedure can improve database performance because the SQL statements in each procedure are only compiled and optimized the first time they are executed. In sontrast SQL statements that are sent from a client to the server have to be compiled and optimized everytime ther are executed. In addition to SELECT statement, a stored procedure can contain othe SQL statements such as INSERT,UPDATE,DELETE. It also contain control-of-flow language. A trigger is a special type of procedure that executes when rows are inserted, updated or deleted from table. A user defined function(UDF) is a special type of procedure that can return a value or a table.

Example:

DOTNET MATERIAL

Page 8

SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= CREATE PROCEDURE spVendorByState @VendorState varchar(50) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here SELECT VendorId,VendorFName,VendorLName,VendorCity,VendorState,VendorCountry,PostedDate,Vendor Description FROM Vendor Where VendorState = @VendorState ORDER BY PostedDate END CURSORS

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable For example, you can use a single UPDATE statement to update many rows of data. There are times when you want to loop through a series of rows a perform processing for each row. In this case you can use a cursor

What is cursor in SQL Server? A Cursor is a database object that represents a result set and is used to manipulate data row by row. When a cursor is opened, it is positioned on a row and that row is available for processing. SQL Server supports three types of cursor namely Transact-SQL server cursor, API server cursor, and client cursor. Transact-SQL Server cursors use Transact-SQL statements and are declared using DECLARE CURSOR statement. Transact-SQL Server cursors can be used in Transact-SQL scripts, stored procedures, and triggers. DOTNET MATERIAL

Page 9

Transact-SQL cursors are implemented on the server. You can fetch only one row at a time in Transact-SQL Server cursors. You can use FETCH statements with Transact-SQL cursors to retrieve rows from a cursors result set. API server cursors support the API cursor functions. API server cursors are implemented on the server. API server cursors support fetching blocks of rows with each fetch. A cursor fetches multiple rows at a time is called a block cursor.

Define the steps to use Transact-SQL Cursor. Declare the cursor, Open the cursor, Fetch record row by row, Close cursor, Deallocate cursor. Example of a cursor Declare @EmpId int Declare curEmp CURSOR READ_ONLY FOR SELECT EmpId FROM Employee Open curEmp Fetch next from curEmp into @EmpId While @@FETCH_STATUS = 0 Begin Print @EmpId Fetch next from curEmp into @EmpId End Close curEmp Deallocate curEmp

Explain the cursor types. DYNAMIC: It reflects changes happened on the table while scrolling through the row. STATIC: It works on snapshot of record set and disconnects from the server. This kind doesnt reflects changes happened on the table while scrolling through the row. KEYSET: In this kind, new record is not reflected, but data modification can be seen.

TRIGGERS A trigger is a special kind of stored procedure that is invoked whenever an attempt is made to modify the data in the table it protects. Modifications to the table are made ussing INSERT,UPDATE,OR DELETE statements.Triggers are used to enforce data integrity and business rules such as automatically updating summary data. It allows to perform cascading delete or update operations. If constraints exist on the trigger table,they are checked prior to the trigger execution. If constraints are violated statement will not be executed and trigger will not run.Triggers are associated with tables and they are automatic . Triggers are automatically invoked by SQL SERVER. Triggers prevent incorrect , unauthorized,or inconsistent changes to data DOTNET MATERIAL

Page 10

CREATE TABLE emp(Empid int,EmpName VARCHAR(50),Salary decimal(10,2)) INSERT INTO EMP(Empid,EmpName,Salary) VALUES(101,'TEST',2000) TRIGGERS TWO TYPES 1.DML -- INSERT ,UPDATE DELETE 2.DDL --CREATE ,ALTER or DROP tables /* INSERT TRIGEER */ ALTER TRIGGER TR_EMPINSERT ON EMP FOR INSERT AS SELECT * FROM EMP /* UPDATE TRIGEER */ CREATE TRIGGER TR_EMPUPDATE ON EMP FOR UPDATE AS PRINT @@ROWCOUNT --GET THE ROWCOUNT /* DELETE TRIGEER */ CREATE TRIGGER TR_EMPDELETE ON EMP FOR DELETE AS PRINT @@ROWCOUNT --GET THE ROWCOUNT /* UPDATE TRIGGER WITH COULUMN VALUE */ ALTER TRIGGER TR_EMPUPDATEEMPID ON EMP FOR UPDATE AS IF UPDATE(SALARY) BEGIN ROLLBACK TRANSACTION END --Example :update emp set salary=salary+10 where empid=102 /* DROP TRIGGER EXAMPLE */ ALTER TRIGGER TR_EMPDROP ON DATABASE DOTNET MATERIAL

Page 11

FOR DROP_TABLE AS BEGIN PRINT 'Please don''t drop this table' ROLLBACK TRANSACTION END --Example :DROP TABLE EMP -- command to disable the triggers --DISABLE TRIGGER TriggerName ON EMP /* CREATE TABLE TRIGGER EXAMPLE */ CREATE TRIGGER TR_CREATETABLE ON DATABASE FOR CREATE_TABLE AS BEGIN PRINT 'Please don''t create any new tables ' ROLLBACK TRANSACTION END --Example :CREATE TABLE empdummy(Empid int,EmpName VARCHAR(50),Salary decimal(10,2))

What is the difference between ExecuteScalar and ExecuteNonQuery? What is ExecuteReader? ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required. ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands. Example: SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con); //note that con is the connection object con.Open(); cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed ExecuteReader - This method returns a DataReader which is filled with the data that is retrieved using the command object. This is known as a forward-only retrieval of records. It uses our SQL statement to read through the table from the first to the last record.

DOTNET MATERIAL

Page 12

What is the difference between a DataReader and Dataset in ADO.NET? A DataReader works in a connected environment, whereas DataSet works in a disconnected environment. A DataReader object represents a forward only, read only access to data from a source. It implements IDataReader & IDataRecord interfaces. For example, The SQLDataReader class can read rows from tables in a SQL Server data source. It is returned by the ExecuteReader method of the SQLCommand class, typically as a result of a SQL Select statement. The DataReader class' HasRows property can be called to determine whether the DataReader retrieved any rows from the source. This can be used before using the Read method to check whether any data has been retrieved. Example Dim objCmd as New SqlCommand("Select * from t_Employees", objCon) objCon.Open() Dim objReader as SqlDataReader objReader = objCom.ExecuteReader(CommandBehavior.CloseConnection) If objReader.HasRows = True then Do While objReader.Read() ListBox1.Items.Add(objReader.GetString(0) & vbTab & objReader.GetInt16(1)) Loop End If objReader.Close() (NOTE: XmlReader object is used for Forward only Read only access of XML). A DataSet represents an in-memory cache of data consisting of any number of inter-related DataTable objects. A DataTable object represents a tabular block of in-memory data. Further, a DataRow represents a single row of a DataTable object. A Dataset is like a mini-database engine, but its data is stored in the memory. To query the data in a DataSet, we can use a DataView object. Example Dim objCon as SqlConnection = New SqlConnection("server=(local);database=NameOfYourDb;user id=sa; password=;) Dim da as New SqlDataAdapter Dim ds as DataSet = New DataSet da.SelectCommand.Connection = objCon 'The Data Adapter manages on its own, opening & closing of connection object da.SelectCommand.CommandText = "Select * from t_SomeTable" da.Fill(ds,"YourTableName") Suppose you want to bind the data in this dataset to a gridview Gridview1.DataSource = ds Gridview1.DataMember = "YourTableName" Gridview1.Databind()

DOTNET MATERIAL

Page 13

ASP.NET How many Directives r in ASP.NET? There are 11 types directives in asp.net, 1)@ Assembly Links an assembly to the current page or user control declaratively. 2)@ Control Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls). 3)@ Implements Indicates that a page or user control implements a specified .NET Framework interface declaratively. 4)@ Import Imports a namespace into a page or user control explicitly. 5)@ Master Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files. 6)@ MasterType Defines the class or virtual path used to type the Master property of a page. 7)@ OutputCache Controls the output caching policies of a page or user control declaratively. 8)@ Page Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files. 9)@ PreviousPageType Creates a strongly typed reference to the source page from the target of a cross-page posting. 10)@ Reference Links a page, user control, or COM control to the current page or user control declaratively. 11)@ Register Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control

DOTNET MATERIAL

Page 14

FORMS AUTHENTICATION Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie. However, ASP.NET version 2.0 supports cookieless forms authentication, which results in the ticket being passed in a query string. ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication with the forms element. Login.aspx.cs: { protected void btnLogin_Click(object sender, EventArgs e) if (ValidateUser(txtUserName.Text, txtPwd.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true); //true: means it will create a cookie in the client machine. } else Response.Redirect("login.aspx", true);

private bool ValidateUser(string UserName,string Password) { //validate user from database. return true; } private void btnSignOut_Click(object sender, System.EventArgs e) { } FormsAuthentication.SignOut(); Response.Redirect("logon.aspx", true);

RedirectFrom Login Page method will perform: // Redirects an authenticated user back to the originally requested URL or the // default URL. // // Parameters: // userName: // The authenticated user name. // // createPersistentCookie: // true to create a durable cookie (one that is saved across browser sessions); // otherwise, false. // // Exceptions: // System.Web.HttpException: // The return URL specified in the query string contains a protocol other than // HTTP: or HTTPS:.

DOTNET MATERIAL

Page 15

Web.Config: <authentication mode="Forms"> <forms name=".ASPXFORMSDEMO" loginUrl="login.aspx" protection="All" path="/" timeout="30" /> </authentication> <authorization> <deny users ="?" /> <allow users = "*" /> </authorization> Steps to Create a Custom Cookie using Forms Authentication: protected void btnLogin_Click(object sender, EventArgs e) { if (ValidateUser(txtUserName.Text, txtPwd.Text)) { FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now,DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (chkPersistCookie.Checked) ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); string strRedirect; strRedirect = Request["ReturnUrl"]; if (strRedirect == null) strRedirect = "default.aspx"; Response.Redirect(strRedirect, true);

} else Response.Redirect("login.aspx", true); } Important Notes:

You may want to store passwords securely in a database. You can use the FormsAuthentication class utility function named HashPasswordForStoringInConfigFile to encrypt the passwords before you store them in the database or configuration file.

Forms-based authentication requires that your client accept or enable cookies on their browser. Convert the password into a secured format string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPwd.Text, "SHA1");

DOTNET MATERIAL

Page 16

SESSION MANAGEMENT Session state is a server side tool for managing state. Every time your web app goes to the server to get the next request, the server has to know how much of the last web page needs to be "remembered" when the new information is sent to the web page. The process of knowing the values of controls and variables is known as state management. When a page postback occurs, ASP.Net has many techniques to remember state information. Some of these state management information methods are on the client side and others are on the server side. Client side methods for maintaining state include query strings, cookies, hidden fields and view state. Most client side state management modes can be read by users and other programs, meaning that user ids and passwords can be stolen. But session state sits on the server and the ability for other users to capture this information is reduced and in some cases eliminated. Session State is Server Side Session state is server side. In session state, a special session id is stored on the server. This session id identifies a specific ASP.Net application. The session id is assigned to the calling browser. The importance of this method is the server, especially in a web farm, can know if a particular user is a new user or has already visited this web page. Imagine in a web farm, where you have multiple servers serving the same web page. How do the servers recognize unique visitors? It is through the session id. Even if server one gets the initial request, server two and server three can recognize user A as already having a session in process. Now the server can store session specific information about the current user. Is there highly critical sensitive information about the user that needs to be remembered? Like credit card information or name, address and phone number? This information can be kept out of the prying eyes of internet identity thieves with session state. How to Set Session State To set session state, it is as easy as setting a key value pair: Session["Name"] = txtName.Text; or Session.Add("Name",txtName.Text); Then to retrieve session state after the postback txtName.Text = Session["Name"].ToString(); You can store simple objects like strings into the session state and you can also store more complex objects like arrays and structs and any object derived from System.Object. Here is a list of supported methods of the HttpSessionState class. Abandon Cancels the current session Add Adds a new item to session state Clear Clears all values from session state

DOTNET MATERIAL

Page 17

CopyTo Copies the collection of session state values to a one dimensional array, starting at the specified index in the array. Equals Determines if the specified object is equal to the current session state object GetEnumerator Gets an enumerator of all session state values in the current session GetType Gets the System.Type of the current instance Remove Deletes an item from the session-state collection RemoveAll Clears all session state values RemoveAt Deletes an item at a specified index from the session state collection. ToString Returns a System.String that represents the current System.Object

As you can see by looking at the supported methods, you can add, remove, remove all, convert to a string and detrmine type. There are 3 ways to store session state. 1. In Process 2. Session State Service 3. Storing it in MSSQL server The default location is in the ASP.Net process. This is known as in-process. Whenever you stop the Web Server or restart IIS you will lose all of your session state information. State Service runs in a different process than ASP.Net, so you don't have to worry about losing information when ASP.net goes down. State Service also enables you to share your state across multiple servers (web farm) and multiple processors on one server (web garden). A disadvantage to using session state is because it is stored on the server you must go to the server to get the information which is slower than if it was stored on the client side. For the greatest safety and security of your session state use MSSQL server to store session state. Then even if the SQL server dies, you still maintain the info needed for session state. A great methodology to use if you are running an eCommerce shopping cart. Users dislike it when their session dies and they don't know if they have pruchased something or not. DOTNET MATERIAL

Page 18

Since it is stored outside of the web server and the client, then you don't lose information if the web garden or web farm go down either. To use session state on the SQL server alter your web.config file: <sessionState mode="SqlServer" sqlConnectionString="data source=NameOfSQLServer; user id=Kenno;password=mypassword" /> This allows you to connect to the database server and store the required information for session state into the SQL server. So to store required information outside of the client and to persist the information pass each page load use Session State. It is part of the HttpSessionState class and comes from the Page class. It is easy to use, but does require resources on the server, which could slow response time. You can store sessionState in-process, state server or in SQL server. You don't need to store everything in sessionState, but you add a level of trust to the items stored in sessionState. CLIENT SIDE STATE MANAGEMENT In ASP.Net there are four ways to manage client side state. What does that mean client side state management? When your user clicks on an URL or button or server side control, the information goes from your page to the server and then back again to the users web browser. How do you remember the information that is currently on the page. These are the techniques to save the information on the client side and not the server side. Unlike a client server application, there is no automatic storage of information from the previous browser page. Therefore the ASP.Net developer has to take steps to save important information from the postback to the server. The four methods of client side state management are: 1. Query String 2. Cookies 3. Hidden Fields 4. View State This article will discuss the advantages and disadvantages of each method of state management. This is a continuation of an article on client side state management. This section will discuss hidden fields and ASP.Net viewstate. Hidden Fields The next client side state management technique for ASP.Net is hidden fields. Hidden fields have been around for a long time. This is where you place a text field control on your html page. Then you set the control to hidden. That means that your user cannot see the control or its value on the page when the page loads. It is sitting silently in the background undetected. Well, not exactly. Hidden fields are not displayed on the web browser, but if you view source, you can see both the hidden field and it's value. Not very secure. They do allow you to post information to other pages, or back to the same page. DOTNET MATERIAL

Page 19

The disadvantages of hidden fields? 1. Increases the HTML size of the page. 2. You still cannot store structured data 3. Because you can view page of an HTML page, there is no security 4. There is no way to persist the data So even though hidden fields provide some value to your web page, there are still serious limitations that have to be overcome to make it viable as a safe and secure way to store sensitive data from your app. ViewState Next on our list of client side state management methods is Viewstate. This is an ASP.Net tool that allows you to maintain the state of your controls like textbox and listbox across page postbacks. Viewstate has advantages the other 3 methods don't have. One of the most important is the ability of viewstate to support structured data. This means that control values are maintainable across page postbacks. Using viewstate can be easy for nonpostback controls. //use a keyvalue pair to save an object to viewstate. ViewState["sName"] = strName; //Then to retrieve viewstate you have to convert to the object type //by unboxing the object using an explicit conversion. string sRetrieve; sRetrieve = (string) ViewState["sName"]; Disadvantages of viewstate 1. The more controls you have on the form the larger the size of viewstate and the larger the size of the HTML you send back and forth to the server. 2. Only works when pages postback to themselves. 3. You can't persist data to other pages. Even though the viewstate data is encrypted, it would be easy to hack the encrypted data. So you still don't want to save connection strings, passwords or credit card information in viewstate. The really cool thing about viewstate is it's ability to save structured data. Makes it very valuable to pass structured data back to itself on a page instead of going back to the database and reretrieving the info or recreating the information each time. Since viewstate is saved as HTML, ASP.Net gives you the ability to disable viewstate for individual controls, for entire pages, for an entire application and even for an entire machine. Very powerful. For an individual control, just change the EnableViewState property to false to disable the control's viewstate. When a page doesn't postback to itself, meaning it is always sent to a new page, you can disable the page viewstate by addding a page directive. DOTNET MATERIAL

Page 20

<%@ Page EnableViewState="false" %> At the application level you turn off view state in the web.config file. By disabling viewstate here, you disable the ability of any page to postback to itself and remember it's control's values. <pages enableViewState="false" > Query String The query string is a holdover from the ASP days of web programming. You will see this alot when you are surfing around the internet. Basically, it is passing information to the next page with the URL. In it's simplest form it is an URL, with a question mark ?, followed by a key value pair. So let's say you wanted to pass the user's name to the next page requested. Your redirected URL is http:/www.youcanlearnseries.com?name=Joe+Smith. When the user goes to the next page, the developer only needs to capture the query string in the page postback and you have successfully "saved" information from the previous page. To read the query string you use the HttpRequest object. string sName = Request.QueryString["name"]; To pass two or more key value pairs through the querystring property use an ampersand between keyvalue pairs. It would look like this: myURL.com?name=joe+smith&state=Illinois To pass a value to the querystring use: Request.QueryString["state"] = sState.ToString(); One of the advantages to using querystring is it requires no postback operation from the server. The limitations and disadvantages include: 1. There is a limit to the number of characters browsers will allow the length of the querystring to be. 2. There is virtually no security with querystring. Any information you send in a querystring can be read by anybody else. 3. There is no persistence. There is no way to remember the information in a querystring after the user leaves the page. 4. You are limited to using only strings. There is no support for storing structured data, such as ArrayLists, controls, structures or classes. There is still a lot of uses of querystring, because it is simple to read and send the key value pair between pages, you just have to careful what you send and you have to know the limitations of the querystring. Cookies Next is the ASP classic cookies. You are aware of cookies. When you go to a website and the website leaves a txt file on your computer that contains information for the website to use the next time you come to the site. The Advantages of cookies include the fact that the information can be persisted on the user's computer. You can set the cookies expire property to automatically expire the cookie after a certain time. The disadvantages of Cookies DOTNET MATERIAL

Page 21

1. Users can disable cookies in their browsers 2. Size restriction by browser around 4kb to 8kb 3. Cannot store structured data in cookies 4. can't leave sensitive information in cookies Since the cookies reside on the client's computer, any web browser can read the cookies you leave on others' computers. So it is critical you don't leave mission critical information where any smart guy with a browser can pick up your cookies and cause trouble. The cookies property comes from the HttpReponse object. Here is the C# code to set a cookie. //Create a cookie HttpCookie cCookie = new HttpCookie("UserName"); cCookie.Value = txtUserName.Text; //To set expiration time of cookie to 30 minutes from now. cCookie.Expires = DateTime.Now + new TimeSpan(0,0,30,0); //Add the cookie to users computer Response.Cookies.Add(cCookie); You have just added the cookie to the user's computer. When you need to get that information you do the following. //First check to see if the cookie is available anymore. Many power users delete //their cookies on a regular basis to improve performance. if (Request.Cookies["UserName"] == null) { //The cookie is not available go on without it. } else { //Cookie is still there let's read it. string sUserName = Request.Cookies["UserName"].Value; } Cookies have their place in the internet world. I go to a site on a regular basis. They place a cookie on my computer and know who I am when I arrive. It saves me the time of having to login when I want to comment in their forum.

What is the difference between Trace and Debug? Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds. Tracing is actually the process of collecting information about the program's execution. Debugging is the process of finding & fixing errors in our program. Tracing is the ability of an application to generate information about its own execution. The idea is that subsequent analysis of this inforDOTNET MATERIAL

Page 22

mation may help us understand why a part of the application is not behaving as it should and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in .NET via the System.Web.TraceContext class via the System.Diagnostics.Trace and System.Diagnostics.Debug classes. Tracing can be thought of as a better alternative to the response.writes we used to put in our classic ASP3.0 code to help debug pages. If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output is appended in the web form output. Messeges can be displayed in the Trace output using Trace.Warn & Trace.Write. NOTE The only difference between Trace.Warn & Trace.Write is that the former has output in red color. If the trace is false, there is another way to enable tracing. This is done through the application level. We can use the web.config file and set the trace attribute to true. Here we can set <trace enabled=false .../> Note that the Page Directive Trace attribute has precedence over th application level trace attribute of web.config. While using application level tracing, we can view the trace output in the trace.axd file of the project. What is the difference between Server.Transfer and Response.Redirect? Both "Server" and "Response" are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is an underlying difference. //Usage of Server.Transfer & Response.Redirect Server.Transfer("Page2.aspx"); Response.Redirect("Page2.aspx"); The Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this established standard works very well. By the time Page2 is requested, Page1 has been flushed from the servers memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc. The more efficient Server.Transfer method simply renders the next page to the browser without an extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because its still in memory. This technique would be ideal if it wasnt for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still show Page1.aspx even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. This may occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of touch with the server. Say, the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing. In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may be the deciding factor in choosing. What is the difference between Server.Transfer and Server.Execute? Both Server.Transfer and Server.Execute were introduced in Classic ASP 3.0 (and still work in ASP.NET). DOTNET MATERIAL

Page 23

When Server.Execute is used, a URL is passed to it as a parameter, and the control moves to this new page. Execution of code happens on the new page. Once code execution gets over, the control returns to the initial page, just after where it was called. However, in the case of Server.Transfer, it works very much the same, the difference being the execution stops at the new page itself (means the control is'nt returned to the calling page). In both the cases, the URL in the browser remains the first page url (does'nt refresh to the new page URL) as the browser is'nt requested to do so. What is the difference between Authorization and Authentication? Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement. Authentication is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system. Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. When a user logs on to an application/system, the user is first Authenticated, and then Authorized. ASP.NET has 3 ways to Authenticate a user: 1) Forms Authentication 2) Windows Authentication 3) Passport Authentication (This is obsolete in .NET 2.0) The 4th way is "None" (means no authentication) The Authentication Provider performs the task of verifying the credentials of the user ans decides whether a user is authenticated or not. The authentication may be set using the web.config file. Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS. There are 4 types of Windows Authentication methods: 1) Anonymous Authentication - IIS allows any user 2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure). 3) Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above 4) Integrated Windows Authentication - Relies on Kerberos technology, with strong credential encryption Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information. Authorization in .NET - There are two types: FileAuthorization - this depends on the NTFS system for granting permission DOTNET MATERIAL

Page 24

UrlAuthorization - Authorization rules may be explicitly specified in web.config for different web URLs.

WEBSERIVCES SECURITY Default.aspx.cs: private void Page_Load(object sender, System.EventArgs e) { //simple client localhost.WebService MywebService = new localhost.WebService(); localhost.AuthHeader authentication = new localhost.AuthHeader(); authentication.Username = "test"; authentication.Password = "test"; MywebService.AuthHeaderValue = authentication; //Bind the results - do something here DataSet dsData = MywebService.SensitiveData(); dgData.DataSource = dsData; dgData.DataBind(); } AuthHeader.cs : public class AuthHeader: SoapHeader { public string Username; public string Password; } WebService.asmx.cs : public AuthHeader Authentication; [SoapHeader("Authentication",Required=true)] [WebMethod(Description = "Returns some sample data")] public DataSet SensitiveData() { DataSet data = new DataSet(); //Do our authentication //this can be via a database or whatever if (Authentication.Username == "test" && Authentication.Password == "test") { DataTable dtTable1 = new DataTable(); DataColumn drCol1 = new DataColumn("Data", System.Type.GetType("System.String")); dtTable1.Columns.Add(drCol1); DataRow drRow = dtTable1.NewRow(); drRow["Data"] = "Sensitive Data"; dtTable1.Rows.Add(drRow); dtTable1.AcceptChanges(); data.Tables.Add(dtTable1); DOTNET MATERIAL

Page 25

} else { data = null; } } return data;

Explain the access specifiers Public, Private, Protected, Friend, Internal, Default The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers. 1. PUBLIC As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods. 2. PRIVATE As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class. 3. FRIEND/INTERNAL Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly. 4. PROTECTED Protected variables can be used within the class as well as the classes that inherites this class. 5. PROTECTED FRIEND/PROTECTED INTERNAL The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself. 6. DEFAULT A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly Whats the difference betweeen Structure, Class and Enumeration ? Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory. Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a DOTNET MATERIAL

Page 26

structure, but, remember, A No-argument constructor for a structure is not possible. The structure's constructor should always have a parameter. So if we define the following structure struct MyStruct { public int y,z; } and we create a structure type MyStruct st = new MyStruct(); In case of a class, no-argument constructors are possible. Class is defined using the class keyword. A struct cannot initialize the value in structure, whereas a class can. class A { int x = 5; //No error ... } struct { int x = 5; //Syntax Error } A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure. Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1. enum colors {red, green, blue, yellow}; Here, red is 0, green is 1, blue is 2 and so on. An explicit casting is required to convert an enum value to its underlying type int x = (int)colors.yellow; What is the difference between abstract class and interface? If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below: abstract public class Vehicle { } Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an inDOTNET MATERIAL

Page 27

stance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created. Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method. Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below Example: Abstract Class with Abstract method namespace Automobiles { public abstract class Vehicle { public abstract void Speed() //No Implementation here, only definition } } Example: Abstract Class with Virtual method namespace Automobiles { public abstract class Vehicle { public virtual void Speed() //Can have an implementation, that may be overriden in child class { ... } } Public class Car : Vehicle { Public override void Speed() //Here, we override whatever implementation is there in the abstract class { ... //Child class implementation of the method Speed() } } } An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below: Public interface IVehicle //As a convention, an interface is prefixed by letter I { DOTNET MATERIAL

Page 28

Boolean HasFourWheels() } Time to discuss the Difference between Abstract Class and Interface 1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle; it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe. 2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier. 3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation. What is the difference between Overriding and Shadowing? Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two. When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class , by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class. In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class. Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default Whats the difference between a class and an object? In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class. Example Lets create a class named Laptop public class Laptop { private string sbrand; public Laptop() {} public Laptop(string name) { sbrand = name; } DOTNET MATERIAL

Page 29

} From our code that references this class, we write... Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code. What is the difference between value type and reference type? Can a value type contain NULL values? In simple words, all value based types are allocated on the stack, while all reference based types are allocated on the heap. What does this mean? A value type contains the actual value. A reference type contains a reference to the value. When a value type is assigned to another value type, it is copied. When a reference type is assigned to another reference type, a reference is assigned to the value. By saying stack, we mean things are kept one on top of the other. We keep track of each value at the top. By saying heap, we mean things are kept in a mashed order. We keep track of each value by its address, that is referenced by a pointer to it. All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in System.Object, the base class for all objects which is a reference type itself. Data types like integers, floating point numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes, Strings, Arrays are examples of Reference Types. A value type may not contain NULL values. Reference types may contain NULL values. It is not possible to derive new types from Value Types. This is possible in Reference types. However, Value Types like Structures can implement interfaces. What is the difference between a DLL and an EXE? In .NET, an assembly may become a DLL or an EXE. Yet, there is a major underlying difference between the two. An EXE is an executable file that may run on its own. Its independent. Where as a DLL is a Dynamic Link Library, that binds to an exe, or another DLL at runtime. A DLL has an exposed interface, through which members of the assembly may be accessed by those objects that require it. A DLL runs in tandem with the application space in memory, as the application references it. Whereas an EXE is independent, and runs as an independent process.

DOTNET MATERIAL

Page 30

What is the difference between String and StringBuilder? Both String and StringBuilder are classes used to handle strings. The most common operation with a string is concatenation. This activity has to be performed very efficiently. When we use the "String" object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted. This process is a little long. Hence we say "Strings are immutable". When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed. What is the difference between Web Services and Remoting? Both Remoting and Web Services are ways of communication between applications. Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application. Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created. Here are some of the major differences: * ASP.NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP * Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation * ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex. * Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability. * In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET. * Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized. What is the difference between a Public Assembly and a Private Assembly? An assembly is the basic building block in .NET. It is the compiled format of a class, that contains Metadata, Manisfest & Intermediate Language code. An assembly may be either Public or Private. A public assembly means the same as Shared Assembly. Private Assembly - This type of assembly is used by a single application. It is stored in the application's directory or the applications sub-directory. There is no version constraint in a private assembly.

DOTNET MATERIAL

Page 31

Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named. In order to share an assembly with many applications, it must have a strong name. A Strong Name assembly is an assembly that has its own identity, through its version and uniqueness. In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below... 1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following... sn -k C:\samplekey.snk This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute. Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file... <assembly: assemblykeyfileattribute("C:\samplekey.snk")> We may write this in our code as well, like this... Imports System.Reflection <assembly: assemblykeyfileattribute("C:\samplekey.snk")> Namespace StrongName Public class Sample End Class End Namespace 3) Build your project. Your assembly is now strongly named. Installing the Shared assembly in GAC... Go to .NET command interpreter, use the tool gacutil.exe Type the following... gacutil /i sampleclass.dll To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC.

What is the difference between System.Array.CopyTo and System.Array.Clone in .NET? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. DOTNET MATERIAL

Page 32

PARTIAL CLASS & METHOD 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. *At compile time, attributes of partial-type definitions are merged. To split a class definition, use the partial keyword modifier, as shown below With C# 2.0 it is possible to split definition of classes, interfaces and structures over more than one files. This feature allows you to do a couple of fancy things like: 1- More than one developer can simultaneously write the code for the class. 2- You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code. There are a few things that you should be careful about when writing code for partial classes: 1- All the partial definitions must preceede with the key word "Partial". 2- All the partial types meant to be the part of same type must be defined within a same assembly and module. 3- Method signatures (retrn type, name of the method, and parameters) must be unique for the agregated typed (which was defined partially). i.e. you can write default constructor in two separate definitions for a particular partial classe. Restrictions: There are several rules to follow when working with partial class definitions: All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules. The class name and generic-type parameters must match on all partial-type definitions. Generic types can be partial. Each partial declaration must use the same parameter names in the same order. The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same DOTNET MATERIAL

Page 33

type public private protected internal abstract sealed base class

Partial Method: A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time. even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. **A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method. Must be declared inside a partial class. 1.Must be declared as a void return type. 2.Must be declared with the partial. 3.Cannot be marked as extern. 4.Can be marked static or unsafe. 5.Can be generic. 6.Can have ref but not out parameters. 7.Cannot be referenced as a delegate until they are implemented 8.Cannot have access modifiers such as public, private or internal. 9.Cannot be declared as virtual. // Definition in file1.cs partial void onNameChanged(); // Implementation in file2.cs partial void onNameChanged() { // method body }

DOTNET MATERIAL

Page 34

Class Inheritance This lesson teaches about C# Inheritance. Our objectives are as follows: Implement Base Classes. Implement Derived Classes. Initialize Base Classes from Derived Classes. Learn How to Call Base Class Members. Learn How to Hide Base Class Members. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming. Listing 8-1. Inheritance: BaseClass.cs using System; public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } Output: Parent Constructor. Child Constructor. I'm a Parent Class. Listing 8-1 shows two classes. The top class is named ParentClass and the main class is called ChildClass. What we want to do is create a child class, using existing code from ParentClass. First we must declare our intention to use ParentClass as the base class of ChildClass. This is accomplished through the ChildClass declaration public class ChildClass : ParentClass. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name. Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance, a subject covered in a later DOTNET MATERIAL }

Page 35

lesson. ChildClass has exactly the same capabilities as ParentClass. Because of this, you can also say ChildClass "is" a ParentClass. This is shown in the Main() method of ChildClass when the print() method is called. ChildClass does not have its own print() method, so it uses the ParentClass print() method. You can see the results in the 3rd line of output. Base classes are automatically instantiated before derived classes. Notice the output from Listing 8-1. The ParentClass constructor executed before the ChildClass constructor. Listing 8-2. Derived Class Communicating with Base Class: BaseTalk.cs using System; public class Parent { string parentString; public Parent() { Console.WriteLine("Parent Constructor."); } public Parent(string myString) { parentString = myString; Console.WriteLine(parentString); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class Child : Parent { public Child() : base("From Derived") { Console.WriteLine("Child Constructor."); } public new void print() { base.print(); Console.WriteLine("I'm a Child Class."); } public static void Main() { Child child = new Child(); child.print(); ((Parent)child).print(); } } Output: From Derived Child Constructor. I'm a Parent Class. I'm a Child Class. I'm a Parent Class. Derived classes can communicate with base classes during instantiation. Listing 8-2 shows how this is done at the child constructor declaration. The colon, ":", and keyword base call the base DOTNET MATERIAL

Page 36

class constructor with the matching parameter list. If the code had not appended base("From Derived") to the Derived constructor, the code would have automatically called Parent(). The first line of output shows the base class constructor being called with the string "From Derived". Sometimes you may want to create your own implementation of a method that exists in a base class. The Child class does this by declaring its own print() method. The Child print() method hides the Parent print() method. The effect is the Parent print() method will not be called, unless we do something special to make sure it is called. Inside the Child print() method, we explicitly call the Parent print() method. This is done by prefixing the method name with "base.". Using the base keyword, you can access any of a base class public or protected class members. The output from the Child print() method is on output lines 3 and 4. Another way to access base class members is through an explicit cast. This is done in the last statement of the Child class Main() method. Remember that a derived class is a specialization of its base class. This fact allows us to perform a cast on the derived class, making it an instance of its base class. The last line of output from Listing 8-2 shows the Parent print() method was indeed executed. Notice the new modifier on the Child class print() method. This enables this method to hide the Parent class print() method and explicitly states your intention that you don't want polymorphism to occur. Without the new modifier, the compiler will produce a warning to draw your attention to this. See the next lesson for a detailed discussion of polymorphism. In summary, you know how to create a derived/base class relationship. You can control instantiation of your base class and call its methods either implicitly or explicitly. You also understand that a derived class is a specialization of its base class. Polymorphism This lesson teaches about Polymorphism in C#. Our objectives are as follows: Learn What Polymorphism Is. Implement a Virtual Method. Override a Virtual Method. Use Polymorphism in a Program. Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this. Listing 9-1. A Base Class with a Virtual Method: DrawingObject.cs using System; public class DrawingObject { public virtual void Draw() { Console.WriteLine("I'm just a generic drawing object."); } } Listing 9-1 shows the DrawingObject class. This will be the base class for other objects to inherit from. It has a single method named Draw(). The Draw() method has a virtual modifier. The virtual modifier indicates to derived classes that they can override this method. The Draw() method of the DrawingObject class performs a single action of printing the statement, "I'm just a generic drawing object.", to the console. Listing 9-2. Derived Classes With Override Methods: Line.cs, Circle.cs, and Square.cs using System; DOTNET MATERIAL

Page 37

public class Line : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Line."); } }

public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Circle."); } } public class Square : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Square."); } } Listing 9-2 shows three classes. These classes inherit the DrawingObject class. Each class has a Draw() method and each Draw() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding. Listing 9-3. Program Implementing Polymorphism: DrawDemo.cs using System; public class DrawDemo { public static int Main( ) { DrawingObject[] dObj = new DrawingObject[4]; dObj[0] dObj[1] dObj[2] dObj[3] = = = = new new new new Line(); Circle(); Square(); DrawingObject();

foreach (DrawingObject drawObj in dObj) { drawObj.Draw(); } } } DOTNET MATERIAL return 0;

Page 38

Listing 9-3 shows a program that uses the classes defined in Listing 9-1 and Listing 9-2. This program implements polymorphism. In the Main() method of the DrawDemo class, there is an array being created. The type of object in this array is the DrawingObject class. The array is named dObj and is being initialized to hold four objects of type DrawingObject. Next the dObj array is initialized. Because of their inheritance relationship with the DrawingObject class, the Line, Circle, and Square classes can be assigned to the dObj array. Without this capability, you would have to create an array for each type. Inheritance allows derived objects to act like their base class, which saves work. After the array is initialized, there is a foreach loop that looks at each element of the array. Within the foreach loop the Draw() method is invoked on each element of the dObj array. Because of polymorphism, the run-time type of each object is invoked. The type of the reference object from the dObj array is a DrawingObject. However, that doesn't matter because the derived classes override the virtual Draw() method of the DrawingObject class. This makes the overriden Draw() methods of the derived classes execute when the Draw() method is called using the DrawingObject base class reference from the dObj array. Here's what the output looks like: Output: I'm a Line. I'm a Circle. I'm a Square. I'm just a generic drawing object. The override Draw() method of each derived class executes as shown in the DrawDemo program. The last line is from the virtual Draw() method of the DrawingObject class. This is because the actual run-time type of the fourth array element was a DrawingObject object. Delegates .Net: A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method and a class such as a windows control can call your method when a certain event occurs. The following example shows a delegate declaration:Let us have a look at the following sample code. class Figure { public Figure(float a, float b, float c) { m_xPos = a; m_yPos = b; m_zPos = c; } public void InvertX() { m_xPos = - m_xPos; } public void InvertY() { m_yPos = - m_yPos; } public void InvertZ() { m_zPos = - m_zPos; DOTNET MATERIAL

Page 39

} private float m_xPos = 0; private float m_yPos = 0; private float m_zPos = 0; } Now, we have a class named Figure and it has three private fields that use to store position and three methods to invert this position by every axis. In main class we declare delegate as follows: public delegate void FigureDelegate(); And now in the main function we should use it like this: Figure figure = new Figure(10,20,30); FigureDelegate fx = new FigureDelegate(figure.InvertX); FigureDelegate fy = new FigureDelegate(figure.InvertY); FigureDelegate fz = new FigureDelegate(figure.InvertZ); MulticastDelegate f_del = fx+fy+fz; In this example we create three delegates of FigureDelegate type and attach to these elements our three methods from Figure class. Now every delegate keeps the address of the attached function. The last line of code is very interesting, here we create a delegate of base type (MulticastDelegate) and attach three of our already created delegates. As all our methods are of void return type they are automatically of type MutlticastDelegate and a MulticastDelegate can support multiple methods invocation also. Hence we can write Figure figure = new Figure(10,20,30); FigureDelegate fMulti = new FigureDelegate(figure.InvertX); fMulti += new FigureDelegate(figure.InvertY); fMulti(); Events: Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net. Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.) or any event triggered by the program. To understand the usage of delegates for event model, the previous examples are used here. We should add to our Figure class next things: public delegate void FigureHandler(string msg); public static event FigureHandler Inverted; public void InvertZ() { m_zPos = - m_zPos; Inverted("inverted by z-axis"); } Now we have a delegate declared and event that uses this delegate's type. In every function we should call our event. The next code snippet should explain it clearly: static void Main(string[] args) { Figure figure = new Figure(10,20,30); Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted); figure.InvertX(); figure.InvertZ(); } private static void OnFigureInverted(string msg) { Console.WriteLine("Figure was {0}",msg); } DOTNET MATERIAL

Page 40

So, in the main function we should create an object of figure class and attach event handler to the method OnFigureInverted. And when we call any of invert methods the event is fired and it calls our event handler. The application will print the following string into the console: Figure was inverted by x-axis Figure was inverted by z-axis There was simple examples of using delegates and events and should be treated as a starting point to learn it more yourself. Download the C# Delegates source files from the link. To compile and run it need to run .NET command line. Just type: csc TestClass.cs. It creates TestClass.exe that can be run as standard executable file. sealed class: Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET, NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error. If you have ever noticed, structs are sealed. You cannot derive a class from a struct. The following class definition defines a sealed class in C#: // Sealed class sealed class SealedClass { .... } In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error. using System; class Class1 { static void Main(string[] args) { SealedClass sealedCls = new SealedClass(); int total = sealedCls.Add(4, 5); Console.WriteLine("Total = " + total.ToString()); } } // Sealed class sealed class SealedClass { public int Add(int x, int y) { return x + y; } } Why Sealed Classes? We just saw how to create and use a sealed class. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members.

DOTNET MATERIAL

Page 41

What is the difference between a.Equals(b) and a == b? Ans: None Description : 1. Both are used for comparison and boll returns the boolean value (true/false) but in case a and b both are different datatype then also a.Equals(b) can be used to compare but incase of == we cant event compaile the code if a and b are different data type Example : int a=0; string b="o"; if(a.Equals(b)) { //do some thing } //above code will compile successfully and internally the int b will convert to object type and compare if(a==b) { //do some thing } //above code will give you the compilation error 2. by using == we cant compare two object but Equals method will able to compare both the object internally What is the difference between DirectCast and CType ? Ans: If you're totally sure that the expression is the same type that it's being cast to, use DirectCast. If there is any doubt, use CType. The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type and DirectCast requires that the run-time type of an object variable to be the same as the specified type that it's being cast to. Really the same, not just that one can be converted to the other. Use DirectCast if you're absolutely positively sure that an object is the specified type and the runtime type of the expression are the same. If you're not sure but expect that the conversion will work, use CType. The run-time performance of DirectCast is better than that of CType. However, DirectCast throws an InvalidCastException error if the argument types do not match, so you must be sure. .

DOTNET MATERIAL

Page 42

Difference between IS and AS keyword in C#? Ans: AS operator: The as operator is similar to a cast but on any conversion failure null is returned as oppose to raising an exception. IS operator: used to check whether the run-time type of an object is compatible with a given type. How will you copy the structure of a table without data ? the table without data in another table ? Ans: select * Into newtable from oldtable WHERE 1=2 How will you copy the structure of a table with data? Ans: select * Into newtable from oldtable Object Pooling: Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. This article will try to explain this in detail. The example is for an Employee object, but you can make it general by using Object base class. What does it mean? Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool. Connection Pooling Basics or write a query to replicate

Opening a database connection is a resource intensive and time consuming operation. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections. When a new connection requests come in, the pool manager checks if the pool contains any unused connections and returns one if available. If all connections currently in the pool are busy and the maximum pool size has not been reached, the new connection is created and added to the pool. When the pool reaches its maximum size all new connection requests are being queued up until a connection in the pool becomes available or the connection attempt times out. Connection pooling behavior is controlled by the connection string parameters. The following are four parameters that control most of the connection pooling behavior: Connect Timeout - controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds.

DOTNET MATERIAL

Page 43

Max Pool Size - specifies the maximum size of your connection pool. Default is 100. Most Web sites do not use more than 40 connections under the heaviest load but it depends on how long your database operations take to complete. Min Pool Size - initial number of connections that will be added to the pool upon its creation. Default is zero; however, you may chose to set this to a small number such as 5 if your application needs consistent response times even after it was idle for hours. In this case the first user requests won't have to wait for those database connections to establish. Pooling - controls if your connection pooling on or off. Default as you may've guessed is true. Read on to see when you may use Pooling=false setting.

Common Language Runtime The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier. In This Section Common Language Runtime Overview Introduces managed code, managed data, and metadata, and describes key features of the common language runtime. Managed Execution Process Describes the steps required to take advantage of the common language runtime. Automatic Memory Management Describes how the garbage collector allocates and releases memory. Related Sections Hosting the Common Language Runtime Describes runtime hosts, which are sections of code that load the runtime into a process, create the application domains within the process, and load and run user code within those application domains. Common Type System Describes and defines how types are declared, used, and managed in the runtime in support of cross-language integration.

DOTNET MATERIAL

Page 44

ASP.NET Page Life Cycle: Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code. Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true (or if it is not defined, since by default it is true), page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model. The following table lists the page life-cycle events that you will use most frequently. There are more events than those listed; however, they are not used for most page processing scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If you want to write your own ASP.NET server controls, you need to understand more about these stages. For information about creating custom controls, see Developing Custom ASP.NET Server Controls. Page Event PreInit Typical Use Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is being processed. Create or re-create dynamic controls. Set a master page dynamically. Set the Theme property dynamically. Read or set profile property values. Note: If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event. Init InitComplete PreLoad Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties. Raised by the Page object. Use this event for processing tasks that require all initialization be complete. Use this event if you need to perform processing on your page or control before the Load event. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance. The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections.

Load

DOTNET MATERIAL

Page 45

Control events

Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event. Note: 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. Use this event for tasks that require that all other controls on the page be loaded. Before this event occurs: The Page object calls EnsureChildControls for each control and for the page. Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic. The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

LoadComplete PreRender

SaveStateComplete Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls. Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser. If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls. A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code. This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing controlspecific database connections. For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks. Note: During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Unload

Explain Params KeyWord ?

DOTNET MATERIAL

Page 46

The params keyword allows methods to have a variable length parameter list. For example, the following class defines a method called "MultiPrint", which can have any number of string's passed to it. using System; public class MyApplication { public static void MultiPrint(params string[] list) { for ( int i = 0 ; i < list.Length ; i++ ) Console.WriteLine(list[i]); } public static void Main() { MultiPrint("First", "Second", "Third"); MultiPrint("Fourth"); MultiPrint("Fifth", "Sixth"); } }

Running this program prints out: First Second Third Fourth Fifth Sixth There can only be one params keyword per method declaration, and it can only be on the final parameter in the list CLR: The .NET Framework provides a Runtime environment called the Common Language Runtime or (CLR) that handles the execution of the code and provides useful services for the implementation of the application. CLR takes care of code management upon program execution and provides various services such as memory management, thread management, security management and other system services. The managed code targets CLR benefits by using useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging. Common Type System (CTS) describes how types are declared, used and managed. CTS facilitates cross-language integration, type safety, and high performance code execution. The CLS DOTNET MATERIAL

Page 47

is a specification that defines the rules to support language integration. This is done in such a way, that programs written in any language (.NET compliant) can interoperate with one another. This also can take full advantage of inheritance, polymorphism, exceptions, and other features. What is the difference between temp table and table variable? Ans: If we use Temporary Table in a stored procedure, We should drop it at the end. It is not necessary in the case of Table variable. 2. In Table variable we can hold maximum of 20000 records only. If it exceeds, we can use temporary table Difference between Session object and Application object ? Ans: Session id can be created individually for individual clients,so for each client there will be a seperate session id For Application objects we can use globally....means there is only one application id will be created What is a DLL Hell Problem in .Net? DLL Hell, is kind of conflict that occured previously, due to lack of version supportability of dll for(within) an application. Previously, if u had deployed any dll for particular application, and in between u made some changes or provide some more functionality within that application or u enhance your application and you deploy new dll or override existing dll, in this case ur old module which was/were running fine with previous dll, may behaves improperly because of new dll deployed.This called dll Hell. This is no more exist in dot net because of different version supportability of dll, it means old process worked with old dll only and respond in exact manner, and new process which starts after new dll deployed uses(executes with) new dll and respond to user. 2. System.Exception vs application.Exceptionm Ans: There r 2 important classes in the hierarchy that r derived from System.Exception: 1) System.SystemException -> This class is for exceptions that r usually thrown by the .net runtime, or which r considered to be of a generic nature and must be thrown by almost any application. For example, StackOverflowException will be thrown by the .net runtime if it detects the stack is full. On the other hand, u might choose to throw ArgumentException or its subclasses in ur code, if u detect that a method has been called with inappropriate arguments. Subclasses of System.SystemException includes classes that represent both fatal and non-fatal errors. 2) System.ApplicationException-> This class is important, becoz it is the intended base for any class of exception defined by third parties. Hence, if u define any exceptions covering error DOTNET MATERIAL

Page 48

conditions unique to ur application, u should derive these directly or indirectly from System.ApplicationException 3. What is the difference between static and dynamic polymorphism? Ans: Static polymorphism is used the concept of early binding or we can say compile time binding where as dynamic polymorphism used the concept of late binding or run time binding. As per speed concern, dynamic polymorphism is faster then static polymorphism. Function overloading (Static polymorphism / early binding). Function overriding (dynamic polymorphism / late binding).

4. Difference between Overloading and Overidding ? Ans: When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. Example for overriding Clas A { Virtual void hi(int a) { } } Class B:A { public overrid void hi(int a) { } } Example for Over loading Class A { class a() { } class a(int a) { } }

DOTNET MATERIAL

Page 49

The difference between char and varchar are in both storage and performance: 1. Storage wise: char columns have fixed length. If the user supplied value for the column is less than the fixed length defined in the schema, the column is padded with 0 at end to make the total length fixed. varchar doesn't have a fixed length thus no padding is needed. But as the result varchar columns have to store the size of the data together with the column data, which takes an extra 2 bytes per varchar column. 2. Performance wise locating char is a little faster than varchar. Since char columns have fixed length, they are stored in fixed location in a row. This means locating a char column can directly jump to the fixed location in a row to read. For varchar column since the size of the data is variable, they can't be stored in fixed location in a row and rather there is soem kind of lookup table in the row format to store the location of each varchar column. This means locating a varchar column has to lookup the location of the column in the lookup table stored in the row first before jumping to the location to read. Referencing the lokup table introduces some perofrmance overhead, especially ifthe lookup table reference causes cache line miss. In summary, it is a matter of trade-off between padding+faster locate and 2-bytes-overhead-per-column+slower locate when choosing char v.s. varchar. What's the difference between CHAR and NCHAR ? Ans: The difference is that nchar is used to store unicode data, i.e u can store multilingual data in your database tables.Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. where as char reperesents the ascii code of the character What's the difference between TINYINT, SMALLINT, INT and BIGINT data types and when do I use them? TINYINT, SMALLINT, INT and BIGINT are all the same in the sense that they are all exact number data types that use integer data. The difference between these data types are in the minimum and maximum values that each can contain as well as the storage size required by each data type, as shown in the following table: Data Type tinyint smallint int bigint Minimum Value 0 -2^15 (-32,768) -2^31 (-2,147,483,648) -2^63 (9,223,372,036,854,775,808) Maximum Value 255 2^15 - 1 (32,767) 2^31 - 1 (2,147,483,647) 2^63 - 1 (9,223,372,036,854,775,807) Storage Size 1 byte 2 bytes 4 bytes 8 bytes

DOTNET MATERIAL

Page 50

Choosing which of these data types to use depends on the value you want to store for the column or variable. The rule of thumb is to always use the data type that will require the least storage size. Don't always use INT as your data type for whole numbers if you don't need to. If you simply need to store a value between 0 and 255 then you should define your column as TINYINT. The basic difference between Decimal and Numeric : They are the exactly same. Same thing different name. The basic difference between Decimal/Numeric and Float : Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly. Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type reane can be represented exactly with precision and scale. Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(2,2) and DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types. Difference Between SmallDateTime and DATETIME ? Ans: Go for smalldatetime, which takes only 4 bytes while the datetime requires 8 bytes What's the difference between SMALLMONEY and MONEY data types and when do I use them? MONEY and SMALLMONEY are both monetary data types for representing monetary or currency values. The differences between these 2 data types are in the minimum and maximum values each can hold as well as in the storage size required by each data type, as shown in the following table: Data Type smallmoney money Minimum Value -214,748.3648 -2^63 (922,337,203,685,477.5808) Maximum Value 214,748.3647 2^63 - 1 (+922,337,203,685,477.5807) Storage Size 4 bytes 8 bytes

Both SMALLMONEY and MONEY data types has an accuracy to a ten-thousandths of a monetary unit. The rule of thumb is to always use the data type that will require the least storage size. If the monetary value that you will store is less than 214,748.3647 then you should use SMALLMONEY; otherwise use the MONEY data type. How do I store a boolean value in SQL Server? In SQL Server, there's no boolean data type. The nearest data type that can be used in place of boolean data is the BIT data type, which is an integer data type that can accept a value of 1, 0 or NULL value only. DOTNET MATERIAL

Page 51

What's the difference between FLOAT and REAL data types and when do I use them? FLOAT and REAL data types are both approximate number data types for use with floating point numeric data. Floating point data is approximate; not all values in the data type range can be precisely represented. The differences between these 2 data types are in the minimum and maximum values each can hold as well as the storage size required, as specified in the following table: Data Type float [(n)] n 1-24 25-53 real Minimum Value -1.79E + 308 -1.79E + 308 -3.40E + 38 Maximum Value 1.79E + 308 1.79E + 308 3.40E + 38 Precision 7 digits 15 digits 7 digits Storage Size 4 bytes 8 bytes 4 bytes

For FLOAT data type, the n is the number of bits used to store the mantissa in scientific notation and thus dictates the precision and storage size and it must be a value from 1 through 53. If not specified, this defaults to 53. In SQL Server, the synonym for REAL data type is FLOAT(24). If your data requires only a maximum of 7 digits precision, you can either use the REAL data type or FLOAT data type with 24 as the parameter (FLOAT(24)). what is reference parameter? what is out parameters? what is difference these two? a ref parameter must first be initialized before being passed from the calling function to the called function. but a out parameter need not be initialized, we can pass it directly class Program { static void Main(string[] args) { int a = 0, b, c = 0, d = 0; Console.WriteLine("a is normal parameter will not affect the changes after the function call"); Console.WriteLine("b is out parameter will affect the changes after the function call but not necessary to initialize the variable b but should be initialized in the function ParamTest "); Console.WriteLine("c is ref parameter will affect the changes after the function call and is compulsory to initialize the variable c before calling the function ParamTest"); Console.WriteLine("d is used to store the return value"); d = ParamTest(a, out b, ref c); Console.WriteLine("a = {0}", a); Console.WriteLine("b = {0}", b); Console.WriteLine("c = {0}", c); Console.WriteLine("d = {0}", d); } DOTNET MATERIAL

Page 52

public static int ParamTest(int a, out int b, ref int c) { a = 10; b = 20; c = 30; return 40; } }

Which methods are used to execute javascript code from code behind file? RegisterStartupScript and RegisterClientScriptBlock

What is CharEnumerator in C#? CharEnumerator is an object in C# that can be used to enumerate through all the characters of a string. Below is the sample to do that

string str = "my name"; CharEnumerator chs = str.GetEnumerator(); while(chs.MoveNext()) { Response.Write(chs.Current); }

What do you mean by properties in C#? Posted by: Abhisek | Show/Hide Answer Property acts as a cross link between the field and the method . Actually it behaves as a field. We can retrieve and store data from the field using property. The compiler automatically translates the field like property into a call like special method called as 'accessor" . In property there are two accessor and that are used to save value and retrieve value from the field. The two properties are 'get' and 'set'. The get property is used to retrieve a value from the field and the set property is used to assign a value to a field . Depending on there use properties are categorised into three types, ReadWrite Property :- When both get and set properties are present it is called as ReadWrite Property. DOTNET MATERIAL

Page 53

ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property. WriteOnly Property :- When there is only set accessor, it is called as WriteOnly Property

What is the use of ?? operator in C#? Posted by: Abhisek | Show/Hide Answer This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.

What is the difference between Parse and TryParse method? Ans: Parse method is used to parse any value to specified data type. For example string test = "42"; int32 Result; Result = Int32.Parse(test); This will work fine bt what if when you are aware about the value of string variable test. if test="abc".... In that case if u try to use above method, .NET will throw an exception as you are trying to convert string data to integer. TryParse is a good method if the string you are converting to an interger is not always numeric. if(!Int32.TryParse(test,out iResult)) { //do something } The TryParse method returns a boolean to denote whether the conversion has been successfull or not, and returns the converted value through an out parameter.

What is the use of var keyword in C#? This is the new feature in C# 3.0. This enable us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable. eg.

DOTNET MATERIAL

Page 54

var age = 10; Because the initialization value (10) of the variable age is integer type of age will be treated as integer type of variable. There are few limitation of the var type of variables. They are: #. They can't be initialized as null. #. They need to be declared and initialized in the same statement. #. They can't be used as a member of the class.

By default which class is inherited by a class in C#? Posted by: SheoNarayan | Show/Hide Answer If no class is inhertited, by default a class inherit System.Object.

What is nested class? A Nested classes are classes within classes. OR A nested class is any class whose declaration occurs within the body of another class or interface. For more details see http://www.codeproject.com/KB/cs/nested_csclasses.aspx

What is the best way to add items from an Array into ArrayList? Use AddRange method of the ArrayList. string[] arr = new string[] { "ram", "shyam", "mohan" }; ArrayList arrList = new ArrayList(); arrList.AddRange(arr);

Write a single line of code to create a text file and write contents into it. Use following code System.IO.File.WriteAllText(@"c:\MyTextFile.txt", "MyContents");

DOTNET MATERIAL

Page 55

How to sort an array into descending order? First sort the array using Array.Sort and then use Array.Reverse Eg. int[] number = new int[] {6, 4, 7}; Array.Sort(number); // sort in ascending order foreach (int i in number) { lblMessage.Text += i + " <br />"; } // reverse ie descending order Array.Reverse(number); lblMessage.Text += "<hr />"; foreach (int i in number) { lblMessage.Text += i + " <br />"; }

How to convert a sentence into Title Case (Capitalize first character of every word)? Use ToTitleCase method. System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(&quot;dotnetfunda.com is a very good website&quot;); The output will be "Dotnetfunda.Com Is A Very Good Website"

Difference Between dispose and finalize method? Dispose is a method for realse from the memory for an object. For eg: DOTNET MATERIAL

Page 56

<object>.Dispose. Finalize is used to fire when the object is going to realize the memory.We can set a alert message to says that this object is going to dispose.

What is reflection? Reflection is the ability to find the information about types contained in an assembly at runtime. OR Reflection is the ability to find out information about objects, the application details (assemblies), its metadata at run-time. Edited: See the example: http://www.dotnetfunda.com/articles/article132.aspx

What is static constructor? Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with keyword. A static constructor does not take access modifiers or have parameters and can't access any nonstatic data member of a class. SOAP is a simple XML-based protocol to let applications exchange information over HTTP. Or more simply: SOAP is a protocol for accessing a Web Service. What is SOAP? SOAP stands for Simple Object Access Protocol SOAP is a communication protocol SOAP is for communication between applications SOAP is a format for sending messages SOAP communicates via Internet SOAP is platform independent SOAP is language independent SOAP is based on XML SOAP is simple and extensible SOAP allows you to get around firewalls

DOTNET MATERIAL

Page 57

SOAP is a W3C recommendation

Why SOAP? It is important for application development to allow Internet communication between programs. Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic. A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this. SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages. WSDL: WSDL is an XML-based language for describing Web services and how to access them. What You Should Already Know Before you continue you should have a basic understanding of the following: XML XML Namespaces XML Schema

If you want to study these subjects first, find the tutorials on our Home page. What is WSDL? WSDL stands for Web Services Description Language WSDL is written in XML WSDL is an XML document WSDL is used to describe Web services WSDL is also used to locate Web services WSDL is a W3C recommendation

WSDL Describes Web Services WSDL stands for Web Services Description Language. WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes. What is Ajax? The term Ajax was coined by Jesse James Garrett and is a short form for "Asynchronous DOTNET MATERIAL

Page 58

Javascript and XML". Ajax represents a set of commonly used techniques, like HTML/XHTML, CSS, Document Object Model (DOM), and XML/XSLT, Javascript and the XMLHttpRequest object, to create RIA's (Rich Internet Applications). Ajax gives the user, the ability to dynamically and asynchronously interact with a web server, without using a plug-in or without compromising on the users ability to interact with the page. This is possible due to an object found in browsers called the XMLHttpRequest object. What is ASP.NET AJAX? ASP.NET AJAX is a terminology coined by Microsoft for their implementation of AJAX, which is a set of extensions to ASP.NET. These components allow you to build rich AJAX enabled web applications, which consists of both server side and client side libraries. Which is the current version of ASP.NET AJAX Control Toolkit? As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008). What role does the ScriptManager play? The ScriptManager manages all ASP.NET AJAX resources on a page and renders the links for the ASP.NET AJAX client libraries, which lets you use AJAX functionality like PageMethods, UpdatePanels etc. It creates the PageRequestManager and Application objects, which are prominent in raising events during the client life cycle of an ASP.NET AJAX Web page. It also helps you create proxies to call web services asynchronously. Can we use multiple ScriptManager on a page? No. You can use only one ScriptManager on a page. What is the role of a ScriptManagerProxy? A page can contain only one ScriptManager control. If you have a Master-Content page scenario in your application and the MasterPage contains a ScriptManager control, then you can use the ScriptManagerProxy control to add scripts to content pages. Also, if you come across a scenario where only a few pages in your application need to register to a script or a web service, then its best to remove them from the ScriptManager control and add them to individual pages, by using the ScriptManagerProxy control. That is because if you added the scripts using the ScriptManager on the Master Page, then these items will be downloaded on each page that derives from the MasterPage, even if they are not needed, which would lead to a waste of resources. What are the requirements to run ASP.NET AJAX applications on a server? You would need to install ASP.NET AJAX Extensions on your server. If you are using the ASP.NET AJAX Control toolkit, then you would also need to add the AjaxControlToolkit.dll in the /Bin folder. Note: ASP.NET AJAX 1.0 was available as a separate downloadable add-on for ASP.NET 2.0. With ASP.NET 3.5, the AJAX components have been integrated into ASP.NET. Explain the UpdatePanel? The UpdatePanel enables you to add AJAX functionality to existing ASP.NET applications. It can be used to update content in a page by using Partial-page rendering. By using Partial-page rendering, you can refresh only a selected part of the page instead of refreshing the whole page with a postback. Can I use ASP.NET AJAX with any other technology apart from ASP.NET? To answer this question, check out this example of using ASP.NET AJAX with PHP, to demonstrate running ASP.NET AJAX outside of ASP.NET. Client-Side ASP.NET AJAX framework can be used with PHP and Coldfusion. How can you cancel an Asynchronous postback? Yes you can. Read my article over here. Difference between Server-Side AJAX framework and Client-side AJAX framework? DOTNET MATERIAL

Page 59

ASP.NET AJAX contains both a server-side Ajax framework and a client-side Ajax framework. The server-side framework provides developers with an easy way to implement Ajax functionality, without having to possess much knowledge of JavaScript. The framework includes server controls and components and the drag and drop functionality. This framework is usually preferred when you need to quickly ajaxify an asp.net application. The disadvantage is that you still need a round trip to the server to perform a client-side action. The Client-Side Framework allows you to build web applications with rich user-interactivity as that of a desktop application. It contains a set of JavaScript libraries, which is independent from ASP.NET. The library is getting rich in functionality with every new build released. How can you debug ASP.NET AJAX applications? Explain about two tools useful for debugging: Fiddler for IE and Firebug for Mozilla. Can we call Server-Side code (C# or VB.NET code) from javascript? Yes. You can do so using PageMethods in ASP.NET AJAX or using webservices. Can you nest UpdatePanel within each other? Yes, you can do that. You would want to nest update panels to basically have more control over the Page Refresh. How can you to add JavaScript to a page when performing an asynchronous postback? Use the ScriptManager class. This class contains several methods like the RegisterStartupScript(), RegisterClientScriptBlock(), RegisterClientScriptInclude(), RegisterArrayDeclaration(), RegisterClientScriptResource(), RegisterExpandoAttribute(), RegisterOnSubmitStatement() which helps to add javascript while performing an asynchronous postback. Explain differences between the page execution lifecycle of an ASP.NET page and an ASP.NET AJAX page? In an asynchronous model, all the server side events occur, as they do in a synchronous model. The Microsoft AJAX Library also raises client side events. However when the page is rendered, asynchronous postback renders only the contents of the update panel, where as in a synchronous postback, the entire page is recreated and sent back to the browser. Explain the AJAX Client life-cycle events Heres a good article about the same. How many types of triggers are there in update panel? There are 2 types of triggers. 1. PostBackTrigger : It does a full postback. This is useful when any such control which placed within updatePanel but it cannot work asynchronously. Like File Upload Control. 2. AsyncPostBackTrigger :- It does partial post back asynchronously. What is the DisplayAfter property in UpdateProgress control? DisplayAfter property specifies after how many seconds the loading image needs to be displayed in ajax postback. It takes values in seconds. Which control you need to place on the page to show loading image? Is it compulsory to have Script manager on the page when you are using any control of ajax control tool kit? Yes. Page needs to have a script manager for ajax control tool kit controls to work. Is it possible to use FileUpload control within the update panel? DOTNET MATERIAL

Page 60

Yes, it's possible. But we need to use Postback triggers to upload the file. Which property needs to be set for script manager control to extend the time before throwing time out expection if no response is received from the server? AsyncPostBackTimeout Property needs to set which gets or sets a value that indicates the time, in seconds, before asynchronous postback time out if no response is received from the server. <asp:scriptmanager id="scriptManager1" runat="server" asyncpostbackerrormessage="We can not serve your request at this moment.Please try later." asyncpostbacktimeout="36000"></asp:scriptmanager> The default value of this property is 90 second. We can also set the user defined error message using asyncpostbackerrormessage property (as shown in above code) for time out. Can you nest UpdatePanel within each other? Yes Can we use multiple ScriptManager in a single page? No What is AJAX AJAX = Asynchronous JavaScript and XML AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly.

DOTNET MATERIAL

Page 61

The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:

To provide a consistent object-oriented programming environment whether object code is stored and executed local-

ly, executed locally but Internet-distributed, or executed remotely. To provide a code-execution environment that minimizes software deployment and versioning conflicts. To provide a code-execution environment that promotes safe execution of code, including code created by an un-

known or semi-trusted third party. To provide a code-execution environment that eliminates the performance problems of scripted or interpreted envi-

ronments. To make the developer experience consistent across widely varying types of applications, such as Windows-based

applications and Web-based applications. To build all communication on industry standards to ensure that code based on the .NET Framework can integrate

with any other code. The .NET Framework has two main components: the common language runtime and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services. The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of third-party runtime hosts. For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services, both of which are discussed later in this topic. Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code (similar to Microsoft ActiveX controls) possible, but with significant improvements that only managed code can offer, such as semi-trusted execution and isolated file storage. The following illustration shows the relationship of the common language runtime and the class library to your applications and to the overall system. The illustration also shows how managed code operates within a larger architecture.

DOTNET MATERIAL

Page 62

.NET Framework in context

The following sections describe the main components and features of the .NET Framework in greater detail.

Features of the Common Language Runtime


The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that in clude their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application. The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally feature rich. The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety. In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references. The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that language, greatly easing the migration process for existing applications. While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs. The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of frag mented memory and increases memory locality-of-reference to further increase performance. Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft SQL Server and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industrys best enterprise servers that support runtime hosting.

.NET Framework Class Library


The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework. For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET Framework. As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition

DOTNET MATERIAL

Page 63

to these common tasks, the class library includes types that support a variety of specialized development scenarios. For example, you can use the .NET Framework to develop the following types of applications and services:

Console applications. Windows GUI applications (Windows Forms). ASP.NET applications. XML Web services.

Windows services. For example, the Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI develop ment. If you write an ASP.NET Web Form application, you can use the Web Forms classes.

Client Application Development


Client applications are the closest to a traditional style of application in Windows-based programming. These are the types of applications that display windows or forms on the desktop, enabling a user to perform a task. Client applications include applications such as word processors and spreadsheets, as well as custom business applications such as data-entry tools, reporting tools, and so on. Client applications usually employ windows, menus, buttons, and other GUI elements, and they likely access local resources such as the file system and peripherals such as printers. Another kind of client application is the traditional ActiveX control (now replaced by the managed Windows Forms control) deployed over the Internet as a Web page. This application is much like other client applications: it is executed natively, has access to local resources, and includes graphical elements. In the past, developers created such applications using C/C++ in conjunction with the Microsoft Foundation Classes (MFC) or with a rapid application development (RAD) environment such as Microsoft Visual Basic. The .NET Framework incorporates aspects of these existing products into a single, consistent development environment that drastically simplifies the development of client applications. The Windows Forms classes contained in the .NET Framework are designed to be used for GUI development. You can easily create command windows, buttons, menus, toolbars, and other screen elements with the flexibility necessary to accommodate shifting business needs. For example, the .NET Framework provides simple properties to adjust visual attributes associated with forms. In some cases the underlying operating system does not support changing these attributes directly, and in these cases the .NET Framework automatically recreates the forms. This is one of many ways in which the .NET Framework integrates the developer interface, making coding simpler and more consistent. Unlike ActiveX controls, Windows Forms controls have semi-trusted access to a users computer. This means that binary or natively executing code can access some of the resources on the users system (such as GUI elements and limited file access) without be ing able to access or compromise other resources. Because of code access security, many applications that once needed to be installed on a users system can now be deployed through the Web. Your applications can implement the features of a local application while being deployed like a Web page.

Server Application Development


Server-side applications in the managed world are implemented through runtime hosts. Unmanaged applications host the common language runtime, which allows your custom managed code to control the behavior of the server. This model provides you with all the features of the common language runtime and class library while gaining the performance and scalability of the host server. The following illustration shows a basic network schema with managed code running in different server environments. Servers such as IIS and SQL Server can perform standard operations while your application logic executes through the managed code. Server-side managed code

DOTNET MATERIAL

Page 64

ASP.NET is the hosting environment that enables developers to use the .NET Framework to target Web-based applications. However, ASP.NET is more than just a runtime host; it is a complete architecture for developing Web sites and Internet-distributed objects using managed code. Both Web Forms and XML Web services use IIS and ASP.NET as the publishing mechanism for applications, and both have a collection of supporting classes in the .NET Framework. XML Web services, an important evolution in Web-based technology, are distributed, server-side application components similar to common Web sites. However, unlike Web-based applications, XML Web services components have no UI and are not targeted for browsers such as Internet Explorer and Netscape Navigator. Instead, XML Web services consist of reusable software components designed to be consumed by other applications, such as traditional client applications, Web-based applications, or even other XML Web services. As a result, XML Web services technology is rapidly moving application development and deployment into the highly distributed environment of the Internet. If you have used earlier versions of ASP technology, you will immediately notice the improvements that ASP.NET and Web Forms offer. For example, you can develop Web Forms pages in any language that supports the .NET Framework. In addition, your code no longer needs to share the same file with your HTTP text (although it can continue to do so if you prefer). Web Forms pages execute in native machine language because, like any other managed application, they take full advantage of the runtime. In contrast, unmanaged ASP pages are always scripted and interpreted. ASP.NET pages are faster, more functional, and easier to develop than unmanaged ASP pages because they interact with the runtime like any managed application. The .NET Framework also provides a collection of classes and tools to aid in development and consumption of XML Web services applications. XML Web services are built on standards such as SOAP (a remote procedure-call protocol), XML (an extensible data format), and WSDL ( the Web Services Description Language). The .NET Framework is built on these standards to promote interoperability with non-Microsoft solutions. For example, the Web Services Description Language tool included with the .NET Framework SDK can query an XML Web service published on the Web, parse its WSDL description, and produce C# or Visual Basic source code that your application can use to become a client of the XML Web service. The source code can create classes derived from classes in the class library that handle all the underlying communication using SOAP and XML parsing. Although you can use the class library to consume XML Web services directly, the Web Services Description Language tool and the other tools contained in the SDK facilitate your development efforts with the .NET Framework. If you develop and publish your own XML Web service, the .NET Framework provides a set of classes that conform to all the underlying communication standards, such as SOAP, WSDL, and XML. Using those classes enables you to focus on the logic of your service, without concerning yourself with the communications infrastructure required by distributed software development. Finally, like Web Forms pages in the managed environment, your XML Web service will run with the speed of native machine language using the scalable communication of IIS.

DOTNET MATERIAL

Page 65