Beruflich Dokumente
Kultur Dokumente
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
DOTNET MATERIAL
Page 2
HELLO 100
HELLO1
Ravi kiran
sand
dilip
200
300
50
120
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
ProjectManagerID
2
1
2
3
4
DeveloperName
Amulya
Chintu
Keeru
4
5
Neeru
DOTNET MATERIAL
Page 5
Answer :
Amulya
Chintu.
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.
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.
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
Page 9
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
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))
DOTNET MATERIAL
Page 12
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:
{
FormsAuthentication.SignOut();
Response.Redirect("logon.aspx", true);
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
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
Page 20
Page 21
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
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.
Page 32
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
=
=
=
=
new
new
new
new
Line();
Circle();
Square();
DrawingObject();
return 0;
}
DOTNET MATERIAL
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
DOTNET MATERIAL
Page 42
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.
DOTNET MATERIAL
Page 44
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
Raised after all controls have been initialized and any skin settings have
been applied. Use this event to read or initialize control properties.
InitComplete
Raised by the Page object. Use this event for processing tasks that require
all initialization be complete.
PreLoad
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.
Load
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.
DOTNET MATERIAL
Page 45
Control events
LoadComplete
Use this event for tasks that require that all other controls on the page be
loaded.
PreRender
The Page object calls EnsureChildControls for each control and for
the page.
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.
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.
Unload
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.
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");
}
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
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
Minimum Value
Maximum Value
Storage
Size
tinyint
255
1 byte
smallint
-2^15 (-32,768)
2^15 - 1 (32,767)
2 bytes
int
-2^31 (-2,147,483,648)
2^31 - 1 (2,147,483,647)
4 bytes
bigint
-2^63 (9,223,372,036,854,775,808)
2^63 - 1
(9,223,372,036,854,775,807)
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
Minimum Value
Maximum Value
Storage
Size
smallmoney
-214,748.3648
214,748.3647
4 bytes
money
-2^63 (922,337,203,685,477.5808)
2^63 - 1
(+922,337,203,685,477.5807)
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
Minimum Value
Maximum Value
Precision
Storage Size
float [(n)]
1-24
-1.79E + 308
1.79E + 308
7 digits
4 bytes
25-53
-1.79E + 308
1.79E + 308
15 digits
8 bytes
-3.40E + 38
3.40E + 38
7 digits
4 bytes
real
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
Which methods are used to execute javascript code from code behind file?
RegisterStartupScript and RegisterClientScriptBlock
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
DOTNET MATERIAL
Page 54
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 convert a sentence into Title Case (Capitalize first character of every word)?
Use ToTitleCase method.
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("dotnetfunda.com is a
very good website");
The output will be "Dotnetfunda.Com Is A Very Good Website"
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
DOTNET MATERIAL
Page 57
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?
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