Thursday 23 February 2012

.net sFAQ

Abstraction is used for hiding the unwanted information and giving revelant information.

Eg: Three set of customers are going to buy a bike First one wants information about the style. Second one wants about the milage. Third one wants the cost and brand of the bike.So the salesperson explains about the product which customer needs what. So he hiding some information and giving the revelant information.

Encapsulation is combines one or more information into a component.

Eg: Capsule is mixed with one or more medicine and packed into the tube. so its related and acting in two moducles.


Enable single sign-on for your application


decryptionKey=""
validation="SHA1" decryption="AES" />



http://www.codeproject.com/KB/aspnet/SingleSignon.aspx




In case of InProc, state is maintained within the managed
memory of the ASP.NET process whereas in case of OutProc
mode session is managed by an external resource (
StateServer or SQL Server)
In case of InProc, state is maintained within the managed
memory of the ASP.NET process whereas in case of OutProc
mode session is managed by an external resource (
StateServer or SQL Server)


This EggheadCafe article -
http://www.eggheadcafe.com/articles/20021016.asp has a good
comparison

Storage location

* InProc - session kept as live objects in web server
(aspnet_wp.exe). Use "cookieless" configuration in
web.config to "munge" the sessionId onto the URL (solves
cookie/domain/path RFC problems too!)
* StateServer - session serialized and stored in memory
in a separate process (aspnet_state.exe). State Server can
run on another machine
* SQLServer - session serialized and stored in SQL server

Performance

* InProc - Fastest, but the more session data, the more
memory is consumed on the web server, and that can affect
performance.
* StateServer - When storing data of basic types (e.g.
string, integer, etc), in one test environment it's 15%
slower than InProc. However, the cost of
serialization/deserialization can affect performance if
you're storing lots.

of objects. You have to do performance testing for
your own scenario.
* SQLServer - When storing data of basic types (e.g.
string, integer, etc), in one test environment it's 25%
slower than InProc. Same warning about serialization as in
StateServer.
Robustness
* InProc - Session state will be lost if the worker
process (aspnet_wp.exe) recycles, or if the appdomain
restarts. It's because session state is stored in the memory
space of an appdomain. For details, see KB324772.
* StateServer - Solve the session state loss problem in
InProc mode. Allows a webfarm to store session on a central
server. Single point of failure at the State Server.
* SQLServer - Similar to StateServer. Moreover, session
state data can survive a SQL server restart, and you can
also take advantage of SQL serv


How to add read-only property?
If a property does not have a set assessors. Then it is read-only.

try
{
// some sql code here...
}
catch(SqlException se)
{
// Handle SQL Exception here...
MessageBox.Show("SQL Exception occurred");
}
catch(Exception e)
{
// Some non sql exception happened...
MessageBox.Show("Unknown Exception occurred");
}

Persistent cookies and non persistent cookies.

Persistent cookies are those which is storing in cookies folder in hard disk.

Non persistent cookies are created on memory, inside the browser process. When we close the browser, that memory region will collect by Operating system, and the cookie will also delete.
Protected:-Access is limited to the Containing class or
Types derived from the Containing class

Internal:-Access is limited to the Current Assembly

Protected Internal:-Access is limited to the current
Assembly or types derived from the Containing class

http://databases.aspfaq.com/database/should-i-use-a-temp-table-or-a-table-variable.html
A local temporary table exists only for the duration of a
connection or, if defined inside a compound statement, for
the duration of the compound statement.

A global temporary table remains in the database
Permanently, but the rows exist only within a given
Connection. When connection is closed, the data in the
Global temporary table disappears. However, the table
Definition remains with the database for access when
database is opened next time.


74. What is the diff BW abstract class and interface?

A. An abstract class may contain complete or incomplete methods.
B. Interfaces can contain only the signature of a method but no body.
C. Thus an abstract class can implement methods.
D. But an interface can not implement methods.
E. an abstract class can contain fields, constructors, or destructors and implement properties
F. An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation.
G. An abstract class cannot support multiple inheritances.
H. An interface can support multiple inheritances. Thus a class may inherit several interfaces
I. But only one abstract class.
J. A class implementing an interface has to implement all the methods of the interface,
K. But the same is not required in the case of an abstract Class.
L. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Class
M. No access modifiers in interfaces.
N. Abstract classes are faster than interfaces.

So Which One Should I Use?
Abstract classes can add more functionality without destroying the child classes that were using the old version. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. In an interface, creation of additional functions will have an effect on its child classes due to the necessary implementation of interface Methods in classes. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. Say there are two classes, bird and airplane, and both of them have methods called fly. It would be ridiculous for an airplane to inherit from the bird class just because it has the fly() method. Rather, the fly() method should be defined as an interface and both bird and airplane should implement that interface. If we want to provide common, implemented functionality among all implementations of component, we should use an abstract class. Abstract classes allow us to partially implement classes, whereas interfaces contain no implementation for any members. So the selection of interface or abstract classes depends on the needs and design of our project. We can make an abstract class, interface, or combination of both depending on our needs.
The most likely situation in which we make a class or method sealed will be if the class or method is internal to the operation of the library, class, or other classes that we are writing. Because any attempt to override some of its functionality will cause problems. We can mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending our classes. For example, in the .NET base class library string is a sealed class.
We should not use the sealed key word on a method unless that method is itself an override of another method in some base class. If we are defining a new method and we don’t want anyone else to override it, we should not declare it as virtual in the first place. If however, we have overridden a base class method, the sealed keyword provides a way of ensuring that the override supplied to a method is a “final” override that means no one else can override it again.


1) How to implement Data relation between two tables.
Ans. In order to set the relationship between two or more than two columns, ADO.NET provides the DataRelation class. When a DataRelation object is created, it assists to enforce some constraints on the relationships between columns. The constraint may be like a Unique constraint that ensures that a column will have no duplicate value in the table. A Foreign Key constraint may be used to enforce Referential Integrity. The Unique property may be set by setting the unique property of a DataColumn to True. This may also be done by adding an instance of the UniqueConstraint class to the DataRelation object. As a part of the foreign key constraint, we may specify referential integrity rules that are applied at 3 places

1) When a parent record is updated
2) when a parent record is deleted
3) When a change is rejected or accepted.

A DataRelation object permits to establish a parent-child relationship between two or more tables inside a DataSet object. The easiest way to create a DataRelation between two tables in a DataSet is to setup a primary key - foreign key relationship between the columns of a table.

See code example below, where a DataRelation has been setup between the Employee table and the Salary table...
'Code Below in VB.NET
Dim Conn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim RowParent As DataRow
Dim RowChild As DataRow

Conn = New _
SqlConnection(ConfigurationSettings.Appsettings("SomeConnectionStringWrittenInWeb.Config"))
da = New SqlDataAdapter("SELECT * FROM Employees", Conn)
ds = New DataSet()

Try
Conn.Open()
da.Fill( ds,"Employees")
da.SelectCommand = New SqlCommand("SELECT * FROM Salary", Conn)
da.Fill(ds, "Salary")
Catch ex As SqlException
Response.Write(ex.ToString())
Finally
Conn.Dispose()
End Try

'Next, Let us create a Data Relationship
ds.Relations.Add("Employee_Salary", ds.Tables("Employees").Columns("EmployeeID"), _
ds.Tables("Salary").Columns("EmployeeID"))
'Display the Employee and Child Salary in the Form
'Say we have a Label in the form
For each RowParent in ds.Tables("Employees").Rows

lblRelation.Text &= RowParent("Emp_Name")
For each RowChild in RowParent.GetChildRows("Employee_Salary")
lblRelation.Text &= "
" & RowChild("Sal_Amount")
Next
Next

2) How do u communavate with ui layer from bl layer?
A. By creating the objects of the classes which are in bl layer.
3) Where u would deploy ur webservices
4) What is dot net framework?
A. It is a platform using u can create, deploy and run applications and webservices and it basically consist of 3 diif things like
• CLR
• Hierarchical .net class library
• Active server pages
5) What is the diff between dynamic and forwardonly cursor

Ans. Forward only is not scrollable and dynamic is scrollable.
6) Check whether textbox has been entered by null value.
-----------
Global Logic

1.11) what is reflaction.

Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime, but in the upcoming example we will be reading and invoking only.

Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System.Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from thier names, you can use these classes to inspect different aspects of an object at runtime.

2) What is the diff between full outer join and inner join?
A. Inner join:


We use this when we compare two columns from two different table .Based on equality or non equality, we retrieve the rows matched.
eg.

Select emp.empid, order.orderid
from emp Innerjoin order
on Emp.empid=order.empid

This example gives all the rows from emp,order tables where the empid's in both the tables are same.


Outer Join:

There are three types of outer joins namely:
Left Outer Join---For retreiving all the columns from the first table irrespective of the column match.
Right Outer Join---For retreiving all the columns from the second table irrespective of the column match
Full Outer Join---For retreiving all the columns from both the tables irrespective of column match.

Eg.

Employee Table :- Department Table:-

EmployeeID EmployeeName DepartmentID DepartmentID DepartmentName
1 Smith 1 1 HR
2 Jack 2 2 Finance
3 Jones 2 3 Security
4 Andrews 3 4 Sports
5 Dave 5 5 HouseKeeping
6 Jospeh 6 Electrical
************************************************************************************************
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

The ResultSet will be :-

EmployeeID EmployeeName DepartmentName
1 Smith HR
2 Jack Finance
3 Jones Finance
4 Andrews Security
5 Dave HouseKeeping

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

The ResultSet will be :-

DepartmentID DepartmentName
1 HR
2 Finance
3 Security
5 HouseKeeping
************************************************************************************************

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

The ResultSet will be: -

EmployeeID EmployeeName DepartmentName
1 Smith HR
2 Jack Finance
3 Jones Finance
4 Andrews Security
5 Dave HouseKeeping
6 Jospeh

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.


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

The ResultSet will be :-

DepartmentID DepartmentName EmployeeName
1 HR Smith
2 Finance Jack
2 Finance Jones
3 Security Andrews
4 Sports NULL
5 HouseKeeping Dave
6 Electrical NULL

This query will result in Null value for Employee Name where no Employee is assigned to that department.

4) How to find out which column should be indexed.
If the column meets the fallowing criteria’s
• As indexes are used increase the performance of the query which contains search condition or join so it should be done on the column which often on above type of queries.
• As joins can be implemented on foreign keys so typically all the foreign keys should be indexed.
• The column which contain maximum number of distinct values
• And if the column’s data is not often modified.
5) What is reindexing?
6) Why is a UNION ALL faster than a UNION?

UNION ALL faster than a UNION because for union operation server needs to remove the duplicate values but for union all its not. That’s why the UNOIN ALL is faster than UNION Operation. It is recommended that if you know that the union set operation never returns duplicate values than you must use UNION ALL instead of UNION.

7. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row processing of the result sets.

Types of cursors: Static, Dynamic, Forward-only, Key set-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip; where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000

END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing,

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row

Where we should cursor with a example below-

Row-by-row operations

Cursors are best used when performing row-by-row operations that can't be accomplished with set-based operations (i.e., when you need to fire a stored procedure once per row in a table).

Here is an example of a cursor used in the Microsoft shipped routine sp_helppublication

DECLARE hC CURSOR LOCAL FAST_FORWARD FOR
SELECT pubid, name FROM syspublications WHERE name like @publication
OPEN hC
FETCH hC INTO @pubid, @pubname
WHILE (@@fetch_status <> -1)
BEGIN
IF is_member(N'db_owner') <> 1
BEGIN
exec @retcode = sp_MSreplcheck_pull
@publication = @pubname,
@raise_fatal_error = 0,
@given_login = @username
END
IF (is_member(N'db_owner') = 1) OR (@retcode = 0 AND @@error = 0)
INSERT INTO #accessiblepubs values(@pubid)
FETCH hC INTO @pubid, @pubname
END
CLOSE hC
DEALLOCATE hC

This same procedure can be accomplished in a singly nested while loop, but cursors are a better option for performance. For more than one nested loop, you should use a while loop.

Here is an example with the above batch rewritten as a while loop.

DECLARE @count int
DECLARE @pubid int
DECLARE @publication varchar(10)
DECLARE @pubname varchar(10)
DECLARE @retcode int
SET @publication='pubs'
DECLARE @username sysname
SET @username=suser_name()
SELECT @count=count(pubid) FROM pubs.dbo.syspublications WHERE name like @publication
WHILE (@count > 0 )
BEGIN
IF is_member(N'db_owner') <> 1
BEGIN
SELECT @pubid=pubid, @pubname=name FROM syspublications WHERE name like @publication
exec @retcode = sp_MSreplcheck_pull @publication = @pubname, @raise_fatal_error = 0, given_login = @username
END
IF (is_member(N'db_owner') = 1) OR (@retcode = 0 AND @@error = 0)
INSERT INTO #accessiblepubs values(@pubid)
SELECT @count=@count-1
END

Quick and dirty

SQL developers are often under the gun to write code fast. Writing a cursor requires less mental effort than writing its set-based equivalent. Unfortunately these shortcuts often remain in production and cause problems further down the line. (Thanks for the above two observations from SQL MVPs Itzik Ben Gan and Erland Sommarskog.)

Cursors are faster than using while loops. Here is an example illustrating the timings.

USE PUBS
GO
CREATE TABLE NUMBERS (pk INT NOT NULL IDENTITY PRIMARY KEY , CHARCOL char(20))
DECLARE @intcol INT
SET @intcol=1
WHILE @intcol<8001
BEGIN
INSERT INTO NUMBERS (charcol) VALUES (@intcol)
SELECT @intcol=@intcol+1
END
DECLARE @PK VARCHAR (20)
DECLARE @datetime DATETIME
SET @datetime=GETDATE ()
DECLARE test CURSOR FOR SELECT charcol FROM NUMBERS
OPEN test
FETCH NEXT FROM test INTO @PK
WHILE (@@FETCH_STATUS =0)
BEGIN
SELECT @PK
FETCH NEXT FROM test
INTO @PK
END
CLOSE TEST
DEALLOCATE TEST
SELECT DATEDIFF(ms, @datetime, GETDATE())
--3786 ms
DECLARE @counter INT
DECLARE @datetime DATETIME
SET @datetime=GETDATE ()
SET @counter=1
WHILE (@counter< 8001)
BEGIN
SELECT charcol from numbers where pk=@counter
SELECT @counter=@counter+1
END
SELECT DATEDIFF(ms, @datetime, GETDATE())
--4676 ms – almost a full second longer

This is a trivial example, but it does illustrate the performance advantage of cursors over while loops. In our case of 8,000 rows there is nearly a one-second speed advantage in using a cursor over a while loop.



8. What are the basic difference between clustered and a non-clustered index?

The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.

9.What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

9. How to deploying a web services?
A. Deploying the Web Services from development to staging or production is very simple. Similar to ASP.NET applications, just copy the .ASMX file and the .DISCO files to the appropriate directories, and you are in business.
10. What is the default version number of assembly?
A. 1.0.0.0
11.What soap version ur using?
A. 1.2
12. What version of Ajax Ur using now?
A.1.0
13. What are similarities between Class and structure ?
A. Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers
14. By default what is the maximum number of connections kept in the connection pool?
A.100
15. How many events are there for Gridview in Asp.Net?
A.22
16. Details about @@IDENTITY and @@ SCOPE_IDENTITY

Transact-SQL Reference (SQL Server 2000)
SCOPE_IDENTITY
Returns the last IDENTITY value inserted into an IDENTITY column in the same scope. A scope is a module -- a stored procedure, trigger, function, or batch. Thus, two statements are in the same scope if they are in the same stored procedure, function, or batch.
Syntax
SCOPE_IDENTITY ( )
Return Types
sql_variant
Remarks
SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in that they return values inserted into IDENTITY columns.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
SCOPE_IDENTITY and @@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
For example, you have two tables, T1 and T2, and an INSERT trigger defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 as a result of the trigger.
Assuming that both T1 and T2 have IDENTITY columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1.
@@IDENTITY will return the last IDENTITY column value inserted across any scope in the current session, which is the value inserted in T2.
SCOPE_IDENTITY() will return the IDENTITY value inserted in T1, which was the last INSERT that occurred in the same scope. The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.
See Examples for an illustration.
Examples
This example creates two tables, TZ and TY, and an INSERT trigger on TZ. When a row is inserted to table TZ, the trigger (Ztrig) fires and inserts a row in TY.
USE tempdb
GO
CREATE TABLE TZ (
Z_id int IDENTITY(1,1)PRIMARY KEY,
Z_name varchar(20) NOT NULL)

INSERT TZ
VALUES ('Lisa')
INSERT TZ
VALUES ('Mike')
INSERT TZ
VALUES ('Carla')

SELECT * FROM TZ

--Result set: This is how table TZ looks
Z_id Z_name
-------------
1 Lisa
2 Mike
3 Carla

CREATE TABLE TY (
Y_id int IDENTITY(100,5)PRIMARY KEY,
Y_name varchar(20) NULL)

INSERT TY (Y_name)
VALUES ('boathouse')
INSERT TY (Y_name)
VALUES ('rocks')
INSERT TY (Y_name)
VALUES ('elevator')

SELECT * FROM TY
--Result set: This is how TY looks:
Y_id Y_name
---------------
100 boathouse
105 rocks
110 elevator

/*Create the trigger that inserts a row in table TY
when a row is inserted in table TZ*/
CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
BEGIN
INSERT TY VALUES ('')
END

/*FIRE the trigger and find out what identity values you get
with the @@IDENTITY and SCOPE_IDENTITY functions*/
INSERT TZ VALUES ('Rosalie')

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
GO
SELECT @@IDENTITY AS [@@IDENTITY]
GO

--Here is the result set.
SCOPE_IDENTITY
4
/*SCOPE_IDENTITY returned the last identity value in the same scope, which was the insert on table TZ*/

@@IDENTITY
115
/*@@IDENTITY returned the last identity value inserted to TY by the trigger, which fired due to an earlier insert on TZ*/


17. What’s connection pooling and how to use It.?
A. A connection with a database server is a hefty and high resource consuming process. If any application needs to fire any query against any database server, we need to first establish a connection with the server and then execute the query against that database server.
Not sure whether you felt like this or not; when you are writing any stored proc or a query, the query returns the results with better response time than the response time, when you execute that same query from any of your client applications. I believe, one of the reasons for such behavior is the overheads involved in getting the desired results from the database server to the client application; and one of such overheads is establishing the connection between the ADO.
Web applications frequently establish the database connection and close them as soon as they are done. Also notice how most of us write the database driven client applications. Usually, we have a configuration file specific to our application and keep the static information like Connection String in it. That in turn means that most of the time we want to connect to the same database server, same database, and with the same user name and password, for every small and big data.
ADO.NET with IIS uses a technique called connection pooling, which is very helpful in applications with such designs. What it does is, on first request to database, it serves the database call. Once it is done and when the client application requests for closing the connection, ADO.NET does not destroy the complete connection, rather it creates a connection pool and puts the released connection object in the pool and holds the reference to it. And next time when the request to execute any query/stored proc comes up, it bypasses the hefty process of establishing the connection and just picks up the connection from the connection pool and uses that for this database call. This way, it can return the results comparatively faster.

Syntax-
conn.ConnectionString = "integrated security=SSPI; SERVER=YOUR_SERVER; DATABASE=YOUR_DB_NAME; Min Pool Size=5; Max Pool Size=60; Connect Timeout=2; pool=true”
--Maximum number of connections we can use in pool is hundred and standard number of connection we shld use is 40


18. What are the magic tables in SQL Server 2000?
A. A when we are performing DML operations into table these Inserted & Deleted tables
(Called as magic tables) will be created automatically.

When we insert any record then that record will be added
Into this Inserted table initially, similarly while
Updating a record a new entry will be inserted into
Inserted table & old value will be inserted into Deleted
Table.

In the case of deletion of a record then it will insert
That record in the Deleted table

Note that the Magic Table does not contain the information
About the columns of the data-type text, ntext, or image.
Attempting to access these columns will cause an error.

Note: And these magic tables can be accessed using triggers only.

18. What are defaults? Is there a column to which a default can't be bound?

A.A default is a value that will be used by a column, if no
Value is supplied to that column while inserting data.
IDENTITY columns and timestamp columns can't have defaults
Bound to them

19. How do you find the error, how can you know the number of rows effected by last SQL statement?

A.select @er=@@error,@rc=@@rowcount
19. Can we create clustered index on non primary key column

A.NO.If the table has the primary key column, then by default
it will have a clustered index on that primary key
Cloumn.So if you want to create a clustered index on none
Primary key column then you has to create it before
Setting a column as the primary key column or u have to
Delete the clustered Primary key columns index to create a
new one. but it is recommended to have a clustered index on
primary key column.

But on that table primary key should be created with
Non-clustered index and the column u want to create a
Cluster index is should be unique.

2. Can a table have two primary keys?
Ans:-A table can have Only One Primary key. But a table can have
composite Primary key. That means we can create composite
primary key.
upto 16 columns only.
20. What is the difference between two queries: 1. SELECT * FROM table WHERE 1=1; 2. SELECT * FROM table

in first query 1=1 always true, then it retrieves all columns
in a table.
so, there is no difference in between these two

21. How do I compare two values when one value (data type) is char and the other is an integer?

I will convert column with integer datatype to char because i can not convert char to integer if column contains any alphabet and then i will compare two values.

22. Where do you think the user’s names and passwords will be stored in sql server?

1 They get stored in master db in the sysxlogins table.

23. WHAT IS DIFFRENCE BETWEEN TRUNCATE AND DELETE STATEMENT

Truncate is used for deleting all data from table. it is similar to delete command without condition. Main differences b/w delete & truncate are

1. Truncate is faster in execution than delete which will restructure the complete table without bothering of data. Where as delete checks the data row by row writes
Information into log and deletes.
2. With truncate we cannot use any conditions

24.
How to Generate a Series of Random Integers With T-SQL?

1 using rand ()

25. How do we get month name in SQL Server 2000, Oracle, and MS Access?
A.select datename(mm,getdate())

26. WHY CAN WE CREATE ONLY ONE CLUSTERED INDEX ON A TABLE IN SQL SERVER?

Clustered Index creation does not depend upon primary key,
it can be created on any column, but the write answer is
whenever we create clustered index on a table it physically
sorts the column values, so another clustered index is not
Possible.

27. in emptable i want to retrive the name of employee whose name in 'J'char.exp: arjun,jagadesh,niranjan,anju,aaaj etc.

A.select * from emp where name like '%J%'
27A. in emptable i want to retrive the name of employee whose name in start ith j
A.select * from emp where name like '% J '



28. Advantages and Disadvantages of Cursor?
Answer
Advantage:

You can do row vise validation from a table

Disadvantage:

Of example you are retrieving 100 rows. Every single row you retrieve will hit the server as a single select query so performance will be low.


29. What is the difference between distinct clause and group by clause?

Distinct Clause:
---------------
Distinct Clause Will Eliminate the Duplicate data or Rows
When u r selecting from table .So it Produce the Data or
Rows with out Duplication.Generally Distinct Clause will
Be Placed on the Column of the Table.

Group Clause:
-------------
Group Clause will group or pack the rows or data based on
The Column(S).

30. How to implement locking in sql server

no need to implement locks sql server automatically holds
locks

31. What is the use of CASCADE CONSTRAINTS?
Answer
2 If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table.

The principal advantage to the cascykjyjading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

32. how to know description of a table in sqlserver 2000

sp_help is correct answer for Sql server

32. What is the difference between a local and a global variable?

Local Variable :
The scope or lifetime of the local variable is with in a block or procedure..

Eg: DECLARE @Variable1

Global Variable :
The scope or lifetime of the global
variable throughout the execution of the program..
Eg: DECLARE @@Variable1

33. Can Somebody tell me the difference between Clustered & Non- Clustered Index??

while creating primary key it will create cluster index.
while creating unique key it will create noncluster index
---cluster index it will create only one per table
---Non Cluster index it will create up to 249 per table
--cluster index physical sort the data
--Non cluster index logical sort the data.


34. Can we create physical table using stored procedure.

A. Yes we can create but we can’t create using functions.

35. How to Maintain Transaction In C#?

You need to create object of connection and then create
Object of command and then assign a conn.begintransation to
A command object then tran.commit or tran.rollback this way
You can maintain transaction in c#

36. Why we can't create the object of abstract class?

The reason behind this is, the abstract class contains
Abstract methods which cant do any job. Calling such
function is meaningless. So it is not allowed to
Instantiate abstract class.

37. While excuting the page, it will go under the fallowing
Steps (or fires the events) which collectively known as Page
Life cycle.
Page_Init -- Page Initialization
LoadViewState -- View State Loading
LoadPostData -- Postback data processing
Page_Load -- Page Loading
RaisePostDataChangedEvent -- PostBack Change Notification
RaisePostBackEvent -- PostBack Event Handling
Page_PreRender -- Page Pre Rendering Phase
SaveViewState -- View State Saving
Page_Render -- Page Rendering
Page_UnLoad -- Page Unloading

37. WHT IS DIFFERENCES BETWEEN HTML CONTROLS AND SERVER CONTROLS.

1) Sever Control internally maintain the sate(EnableViewState
Property) whereas HTML control are not having such
Property to maintain the state.
2) The html controls the server is hit only on page submit.But
For server controls on every user response the server is
Hit.The server controls are used in places like railway
Reservation. The html control is used in places like hotel
Menu card.

38. Have u used webcontrols?Tell me something about these?

Yes, webcontrols are represented in the form of dll.they
Are compiled content and the controls will appear in the
Toolbox. caching is not supported

38. Describe a diffgram ? Write any one use of that?

One of the XML formats which we can use to render DataSet
object contents to XML is a diffgram.
Diffgram is used in reading database data to an XML file to
be sent to a Web Service.

39. What is a bubbled event?

In case of some server controlls like datagrid,repeter,datalist in that we can add another control also like suppose in datagrid we can add check box and in that the check event is not raised by itself or check box.

check box is in datagrid so that datagrid is parent and checkbox is child so that check box send check event to parent that is datagrid .

this pass event from child to parent is called event bubbled.then parent pass it to page using itemtemplate





in that chked is subroutine and oncheck is event so that chked is always public or protected

public sub chked(by val e as event,by val---)

//code
end sub

event bubbling
pass event-from-child-to-parent

40. What is the diff bw array and array list?

A.1. Array is collection of similar datatype objects and where as arraylist can dissimilar data types.

2. Array list has an upper bound but has a dynamic upper bound.



41. What is enum?
A. An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type.

By default, these numerical values are integers, but they can also be longs, bytes, etc. (any numerical value except char) as will be illustrated below

Ex.
1. public enum DAYS
2. {
3. Monday,
4. Tuesday,
5. Wednesday,
6. Thursday,
7. Friday,
8. Saturday,
9. Sunday
10. }

1. for the first literal: if it is unassigned, set its value to 0.
2. for any other literal: if it is unassigned, then set its value to one greater than the value of the preceding literal.
If we want to change the initial value from 0 to 1 then we need declare
Monday=1,
42. What is timestamp?

A. A. time stamp data type is used to automatically generate the
Unique number.A database-wide unique number.

You can add a timestamp column to a table to help maintain the integrity of the database when multiple users are updating rows at the same time. You may also want to know how many rows and which rows were updated without re-querying the table.

43. What is composite control?

Composite Control is an abstract class in .NET that is inherited by those web controls that contain child controls within them.

A choice towards a composite control is made when there is a need for a group of controls to perform a particular action in sync.
Also it is going to be used in many projects. For example if we want a calculator UI to be made, then it needs a text box, a number of button controls to be grouped together along with the functional code. If this calculator UI and functionality are going to be reused in many projects, then it is wiser to create it as a re-usable control, instead of copy/pasting the code every time. This way, when different web controls are put together as a single control, it makes a composite control


44. What are partial classes?
a. It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. There are several situations when splitting a class definition is desirable:
• When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
• When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
• To split a class definition, use the partial keyword modifier, as shown below:

45. What are the diff bw remoting and web services?
A. Web services involve allowing applications to exchange messages in a way that is platform, object model, and programming language independent. Web services are stateless and know nothing about the client that is making the request. The clients communicate by transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or SOAP. (Want to get some funny looks in the hallway Stand around in the hallway near the marketing department with your colleagues and discuss the benefits of using SOAP).The following list outlines some of the major differences between .NET Remoting and Web services that will help you to decide when to use one or the other

---------
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 isn’t 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.


46. Inheriting the two members with Same Name but from two different Interface in a single Class
If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. For example:
C#
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
}
}
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period. For example:
C#
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
C#
SampleClass obj = new SampleClass();
//obj.Paint(); // Compiler error.

IControl c = (IControl)obj;
c.Paint(); // Calls IControl.Paint on SampleClass.

ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass.
Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method:
C#
interface ILeft
{
int P { get;}
}
interface IRight
{
int P();
}
To implement both interfaces, a class has to use explicit implementation either for the property P, or the method P, or both, to avoid a compiler error. For example:


47.Which One is more secure Websevices or remoting.?

Ans.Webservices
A. Because ASP.NET Web Services rely on HTTP, they integrate well with the standard internet security architecture. ASP.NET uses the security features of IIS to provided strong support for standard HTTP authentication, authorization such as Basic, digest, digital certificates, and even MS Passport. However, even though these standard transport-level techniques to secure Web Services are quite effective, they only go so far. In complex scenarios involving multiple Web Services in different trust domain, you will need to use ad-hoc solutions. Work is currently in-progress on a set of security specification that builds on the extensibility of SOAP messages to offer message-level security capabilities.
In the general case, .NET Remoting does not secure cross-process calls. However, a .NET Remoting endpoint deployed in IIS can use the security features of IIS quite easily, including the use of SSL for secure communication across the wire. However, note that if you are using a TCP or HTTP channel in a process outside IIS, then you will need to implement your own authorization and authentication mechanisms. The following table summarizes these points:
Technology Security
ASP.NET Web Services Uses the security features of IIS by default
.NET Remoting Cross-process calls are not secured. Will use the security features of IIS only if deployed in IIS.

48.How to handle State management in Remoting and webservices.?
A. The ASP.NET Web Services model assumes stateless service architecture by default. It does not inherently relate multiple calls from the same user. Each time a client makes a call to a Web Service page, a new object is created to service the request. The object is destroyed after the method call is complete. To maintain state across calls, you can either use the Application and Session objects, or you can implement your own custom solution.
.NET Remoting supports a wide range of state management options and may or may not correlate multiple calls from the same user depending on what type of object you choose. For example, Server-Activated Objects (SAO) does not correlate calls from the same user: Singleton objects share state for all users, and Single Call Objects are stateless. Client-Activated Objects (CAO) however, does correlate calls from the same user and they maintain state per client. The following table summarizes these points:
Technology State Management
ASP.NET Web Services Stateless by default. State can be managed using standard ASP.NET objects or a custom solution
.NET Remoting Different management options depending on the type of the remote object.

48.What is the functionality for itemdatabound.?

A.Itemdatabound has been replaced by rowdatabound in gridview.

Occurs when a data row is bound to data in a GridView control.

49. .What is the functionality for RowCommand.?
A. Occurs when a button is clicked in a GridView control.
50. What is the function of SET NOCOUNT (Transact-SQL).?
Stops the message that shows the count of the number of rows affected by a Transact-SQL statement or stored procedure from being returned as part of the result set.
51. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
52. What is a self join? Explain it with an example.
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: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.
CREATE TABLE EMP
(
Empid int,
Mgrid int,
Empname char (10)
)

INSERT emp SELECT 1, 2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid
52. How u do hit with api for payment gateway and sending sms.
A. For the we need to use com component called msxml2.dll which contains all the
Method for hitting the API and getting response from the server.
1) First of all we need to decode the using Server.HtmlDecode(st.string) in another string called stdecode and then we need to make the decoded string as Server.UrlEncode(st).
2) Then String url=”api url”
_targetAddress =url
3. Then we need to create a object of msxml2 dll so that we can hit with that by using open methos.
msxml.open("POST", _targetAddress, False, "", "")
msxml.setRequestHeader("Accept", "*/*")
msxml.setRequestHeader("Accept-Language", "en-us")
msxml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
msxml.setRequestHeader("Connection", "Keep-Alive")
msxml.setTimeouts(1800000, 1800000, 1800000, 1800000)
msxml.send(url)(we are hitting deir server with the our enocoded data).
Hidden1.Value = msxml.responseText

53. Question - What is Globalization and Localization in ASP.NET?
Answer - Localization is the process of adapting a software application for a specific locale. Globalization is the process of identifying the localizable resources of the application. You can provide support for Localization and Globalization to the application using System.Globalization, System.Resources and System.Threading namespaces.
The developer can define culture specific information using the System.Globalization namespace. The System.Resources namespace contains ResourceManager class that allows access to resources either from the main assembly or from the Satellite Assemblies. The System.Threading namespace supports for multithreaded programming.
A web form has two culture values, Culture and UICulture. Culture value is used for date and number formatting and UICulture values are used to determine culture specific resources.
You can set culture and UICulture values in the application as follows.

Using element of Web.Config.

Using @Page directive in the Page.

In Code-Behind Page e.g.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ("en-GB");
Thread.CurrentThread.CurrentUICulture=new CultureInfo("en-GB");
54. Question - What is the Globalization approaches possible in ASP.NET?
Answer - You can follow many approaches to have globalized application.
You can create separate web application for each culture.
You can create an application that can detect the user’s culture and adjusts output at run time using format specifiers and other tools.
You can store culture-dependent strings in resource files that are compiled into satellite assemblies.
55.Question - Implementing ASP.NET Globalization.
Answer - Create resource files and compile them into a binary resource file.
Create satellite assembly for each of the resource file for each culture.
Store them in separate folders for easy access and replacement.
Read the resources from the satellite assembly that is stored in different folders based on the locale and culture.
56.Question - Define Resource Files and Satellite Assemblies.
Answer - Resource Files: A resource file contains non-executable data that are used by the application and deployed along with it. Bitmaps, Icons etc are the examples of resource files. In ASP.NET, resource files are used to make application to support multiple cultures. You can create resource files each of them correspond to specific locale or culture of the application. You can use resgen utility to compile resource file into an assembly. You can create a satellite assembly from a compiled resource file using the AL utility provided with Microsoft .NET SDK.
Advantages of resource files are as follows.
It supports Globalization features in ASP.NET.
You can have culture based information separate from the content and logic of the application.
You can change resource content without effecting application's code.
Satellite Assemblies
Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture-specific resources in a binary format. They store compiled localized application resources. They can be created using the AL utility and can be deployed even after deployment of the application.
Satellite Assemblies encapsulate resources into binary format and thus make resources lighter and consume lesser space on the disk.

Note: Resource-only assemblies can contain any resource, such as images and text. Satellite assemblies contain only culture-specific resources.

57. How can u sort an array list in descending order?
A. if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
mycountries.Sort()
mycountries.reverse() // Omit this one to make it in asc order.
dd.DataSource=mycountries
dd.DataBind()
end if
end sub
58. What is delay signing?
Answer: Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.
59. What jit compiler.
A. The high level programming languages that need to be compiled require a runtime, so that the architecture on which the language runs is provided with details on how to execute its code. All the programming languages use its corresponding runtime to run the application. For example, to run an application developed using Visual Basic, the computer on which the application will be run must be installed with the Visual Basic runtime. The Visual Basic runtime can run only the applications developed with Visual Basic and not the ones developed with any other programming language like Java. ?
In the .NET Framework, all the Microsoft .NET languages use a common language runtime, which solves the problem of installing separate runtime for each of the programming languages. Microsoft .NET Common Language Runtime installed on a computer can run any language that is Microsoft .NET compatible.

The main advantage of the .NET Framework is the interoperability between different languages. As all the Microsoft .NET languages share the same common runtime language, they all work well together. For example, you can use an object written in C# from Visual Basic.NET. The same applies for all the other Microsoft .NET languages.

When you compile a Microsoft.NET language, the complier generates code written in the Microsoft Intermediate Language (MSIL). MSIL is a set of instructions that can quickly be translated into native code.

A Microsoft.NET application can be run only after the MSIL code is translated into native machine code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native code when the application or component is run instead of compiling the application at development time. The Microsoft.NET runtime consists of two JIT compilers. They are standard JIT compiler and the EconoJIT compiler. The EconoJIT compiler compiles faster than the standard JIT compiler, but the code it produces is not as optimized as the code obtained from the standard JIT compiler.
61.How many non cluster index u can create pre table. ?
A. 249 nonclustered and 1 clustered
62.How many Parameters can per stored procedure and user defined functions.
A.2100 and 2100
63.Maximmum REFERENCES per table
A.253
64. Columns per base table
A.1024
65.What is the diff between ddl and dml triggers.?
A. DDL triggers and DML triggers are used for different purposes.
DML triggers operate on INSERT, UPDATE, and DELETE statements, and help to enforce business rules and extend data integrity when data is modified in tables or views.
DDL triggers operate on CREATE, ALTER, DROP, and other DDL statements. They are used to perform administrative tasks and enforce business rules that affect databases. They apply to all commands of a single type across a database, or across a server.
DDL triggers run only after a Transact-SQL statement is completed. DDL triggers cannot be used as INSTEAD OF triggers.
66. Polymorphism Overview

When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.

Replacing a member of a base class with a new derived member requires the new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced. For example:

class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}

public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}

When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. For example:

DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.

In order for an instance of a derived class to completely take over a class member from a base class, the base class has to declare that member as virtual. This is accomplished by adding the virtual keyword before the return type of the member. A derived class then has the option of using the override keyword, instead of new, to replace the base class implementation with its own. For example:

Class BaseClass
{
Public virtual void DoWork () { }
Public virtual int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public override void DoWork() { }
public override int WorkProperty
{
get { return 0; }
}
}

Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived class overrides a virtual member, that member is called even when an instance of that class is being accessed as an instance of the base class. For example:

DerivedClass B = new DerivedClass ();
B.DoWork (); // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork (); // Also calls the new method.

Virtual methods and properties allow you to plan ahead for future expansion. Because a virtual member is called regardless of which type the caller is using, it gives derived classes the option to completely change the apparent behavior of the base class.


Virtual members remain virtual indefinitely, no matter how many classes have been declared between the classes that originally declared the virtual member. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. For example:

C# Copy Codepublic class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
C# Copy Codepublic class C : B
{
public override void DoWork() { }
}

A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealed keyword before the override keyword in the class member declaration. For example:

C# Copy Codepublic class C : B
{
public sealed override void DoWork() { }
}

In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes using the new keyword, as the following example shows:

C# Copy Codepublic class D : C
{
public new void DoWork() { }
}

In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.

A derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword. For example:

C# Copy Codepublic class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
C# Copy Codepublic class C : B
{
public override void DoWork()
{
// Call DoWork on B to get B's behavior:
base.DoWork();

// DoWork behavior specific to C goes here:
// ...
}
}


abstract
The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessory.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessory.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:

An abstract method is implicitly a virtual method.
Abstract method declarations are only permitted in abstract classes.
Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:

public abstract void MyMethod();The implementation is provided by an overriding method, which is a member of a non-abstract class.
It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

It is an error to use the abstract modifier on a static property.
An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.

An abstract class that implements an interface might map the interface methods onto abstract methods. For example:


Interface I
{
Void M();
}
Abstract class C: I
{
Public abstract void M ();
}For more information, see 10.1.1.1 Abstract classes and 10.5.6 Abstract methods.

Example
In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().

// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property
{
get;
}

public abstract int GetY // Abstract property
{
get;
}
}

class MyDerivedC: MyBaseC
{
public override void MyMethod()
{
x++;
y++;
}

public override int GetX // overriding property
{
get
{
return x+10;
}
}

public override int GetY // overriding property
{
get
{
return y+10;
}
}

public static void Main()
{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}Output
Copy Code
x = 111, y = 161In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:

Copy Code
MyBaseC mC1 = new MyBaseC (); // Error you will get the following error message:

Copy Code
Cannot create an instance of the abstract class 'MyBaseC'.
a
67. What is 3-Tier Architecture

1.0 Definition and motivation

A 3-tier application is a program which is organized into three major disjunctive tiers. These tiers are
• Presentation Tier (Top Tier)
• Logical Tier (Middleware Tier)
• Data Tier (Bottom Tier).
Each layer can be deployed in geographically separated computers in a network. Some architects divide Logic Tier in to two sub tiers Business and Data Access Tiers, in order to increase scalability and transparency. The tiers can be deployed on physically separated machines. The characteristic of the tier communication is that the tiers will communicate only to their adjacent neighbors. For an example, The Presentation Tier will interact directly with the Business Tier and not directly with Data Access or Data Tiers.

1. Presentation Layer


Presentation Layer is nothing but a piece of software that deals with User interface of the Application. Displaying Data to the user and allowing him to interface with it is the main functionality. "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

We can create Presentation layer by Windows Forms or Asp.net Web Forms
Windows Forms are basically used to create traditional Desktop application.
They can offer rich UI design. The main drew back of windows application is they need to install on each and every machine.

On the other hand ASP.net web forms also offer rich UI. They are mainly used for web applications.
2. Business Logic Layer

Business Logic Layer is responsible for processing the data retrieved and sent to the presentation layer. The main task of Business layer is business validation and business workflow

In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

.Net Components forms these layers. Asp.net web service can also serve as Business Logic Layer. But they should be use only if the business validation happens at some external place other than our network.

By using .Net Remoting we can distribute the logic to other machines also.

3. Data Access Layers

Data Access Layer deals with data manipulation actions such as Insert, edit, and delete, select in .NET Database can be from SQL Server or Access database; however it's not limited to just those. It could also be Oracle, mySQL or even XML.You should design data access layer in such a way that other layers need not have any knowledge about underlying data store.

ADO.NET is the data access technology under .NET. Though ADO.NET allows connected data access via DataReader classes more focus is on disconnected data access. Dataset plays a key in this mode. In some rare cases you can also use ADO for data access but its use should have valid reasons. Do not use ADO just because you like Recordset!

Again .NET components form this layer. As stated earlier you may also use classic COM components.

Web services can also form data access layer. This is especially true if your database do not have a data provider. In such cases you can write some custom code to connect with the data and populate DataSet with it and then return DataSet to the caller.

In addition to ADO.NET you can also make use of built-in RDBMS capabilities such as stored procedures and functions

Passing data from one layer to another


Passing data from one layer to another is required in almost all the cases. Traditionally developers used comma separated strings, arrays and disconnected recordsets to achieve this. In .NET, DataSet provides an excellent way to pass your data across layers. You can even create the DataSet programmatically and populate it with your data. If you like objects a lot then you can make use of "Typed DataSets". Typed DataSet is nothing but a class derived from DataSet that exposes the tables and rows as objects.

Advantages


1. Reduces tight coupling between User interface, business process and database.
2. Change in database or any data access methods do not have effect on the presentation layer.
3. It becomes easier to modify or extend your application, without breaking or recompiling the client-side code

68. How to make autopostback false for certain items in dropdown control?
A. Suppose we have n elements and we want to make autopostback false when clicks
Items say Shiva.

We can do it by using javascript
Function MakeFalse ()
{
If (document.form1.ddlgrode.value=’Shiva’)
{
Return false;
}
Form1.submit();
}







69. How can u assign a strong name to an assembly?
A. In order to assign one or more assemblies a strong name; you must first create the 1,024-bit public and private key pair. You do this by running the Strong Name Utility (SN.EXE), like so:

sn.exe -k PublicPrivateKeyFile.snk

I. How can u extract Public key from the strong name key file
This randomly creates a pair of 1,024-bit cryptographic keys. You can use these keys for encryption and decryption by using the RSA public/private key algorithm. The resulting key file contains both the public and the private key. You can extract the public key from the file and place it in a separate file like this:
sn.exe -p PublicPrivateKeyFile.snk PublicKeyFile.snk
Ii.How can we assign a strong name to a assembly?
sn.exe -R YourAssembly.dll PublicPrivateKeyFile.snk

70. How to maintain state in web service?
A. By default web services are stateless but u can implement by making it enable
In web method.
1. C#

[ WebMethod(EnableSession=true) ]
public int PerSessionServiceUsage()
[Visual Basic]
< WebMethod(EnableSession:=True) > _
Public Function PerSessionServiceUsage() As Integer


U can use session and application objects.

71. When and how we can implement function overloading?

A. In complex applications written in C#, we may need many methods which do essentially similar functions but are just different enough to be considered unique. For example, we may have to calculate a person's tax liability and would need to implement a method for doing this calculation in our application program. However, there are many different rules when it comes to tax calculations and they vary throughout the world. While there may be many rules, one basic equation stays the same: Your net income equals your gross income minus a computed tax amount. It is the method of computing your tax that varies.

We would probably have to implement different methods for each type of tax calculation. And, we could give each method a unique name such as TaxCalc1, TaxCalc2, TaxCalc3, etc. But wouldn't it be nice to just name the method TaxCalc and pass different arguments to it based on the computation desired?

For instance, let's say you live in a region within your country where you are taxed on your personal income, the value of your home, and any income you generate by doing business. On sales you generate through business activity, you must pay a gross receipts tax on all sales. If you own your home, you must pay a property tax on the imputed value of it. Then lastly, you must pay a tax on all income you generate through a job with another employer.

An Example: Tax Calculation
For this article, we will use a hypothetical example of computing various taxes on a person's property, sales, and income. Let's summarize the logical flow through pseudocode:

HV = Home_Value
HR = Home_Tax_Rate
GS = Gross_Sales
GR = Gross_Sales_Tax_Rate
PI = Personal Income

If YOU_OWN_YOUR_OWN_HOME and DO_NOT_OWN_A_BUSINESS THEN
Tax = TaxCalc(HV,HR) ' Calculate tax on the home's value
ELSE
If YOU_DO_NOT_OWN_YOUR_OWN_HOME and OWN_A_BUSINESS THEN
Tax = TaxCalc(GS,GR) ' Calculate tax on your gross receipts from sales
ELSE
If YOU_OWN_YOUR_OWN_HOME and OWN_A_BUSINESS THEN
Tax = TaxCalc(HV,HR,GS,GR) ' Calculate tax on both your home and gross receipts
ENDIF
ENDIF
ENDIF

Tax = Tax + TaxCalc(PI) ' And everyone gets a tax calculation on personal income

The pseudo code says that if you own your own home but do not have a business, then you will calculate your tax based on the home's value and the tax rate on a home. If you don't own a home but you own a business then you will calculate your tax based on your gross sales and gross sales tax rate. Finally, if you own a home and a business then you will call TaxCalc and pass all four values. Everyone is run through the TaxCalc method for personal income tax. We don't have to pass a rate for personal income tax calculation because everyone is at a fixed rate which is embedded within the method.

Keep in mind that this example of tax calculation is all hypothetical. Tax codes and calculations, as you know, are much more complex than what is described here throughout the world. But for the sake of this example, we see that we have a method named TaxCalc that is able to take one, two, or four arguments based upon the type of tax we are calculating. Without method overloading, we would have to create a unique method name for each type of calculation we would have to do. We would probably name each TaxCalc1, TaxCalc2, and TaxCalc3 respectively.

How does C# know which method to call? It's easy. It knows which method to invoke based on the number and type of arguments passed to it. This is also referred to as the signature of the method. If C# sees you are calling TaxCalc with four arguments, then it will call that method with four receiving arguments. The same is true for the other two methods as well.

The Overloaded Methods
Each method is defined as follows in our overloading example:

// This method takes for arguments: two amounts and two rates
public static double TaxCalc(double pamt1, double prate1, double pamt2,
double prate2)
{
double taxamt;
Console.WriteLine("Using method with 4 arguments");
taxamt = (pamt1 * prate1) + (pamt2 * prate2);
return taxamt;

} // *** TaxCalc ***
// This method only takes two arguments: an amount and a rate
public static double TaxCalc(double pamt1, double prate1)
{
double taxamt;
Console.WriteLine("Using method with 2 arguments");
taxamt = pamt1 * prate1;
return taxamt;

} // *** TaxCalc ***

// This method only takes one argument: an amount
public static double TaxCalc(double pamt)
{
double taxrate = 0.15;
double taxamt = 0;
Console.WriteLine("Using method with 1 argument");
taxamt = pamt * taxrate;
return taxamt;

} // *** TaxCalc ***


The methods are all very similar however they are differ by the number of arguments used in the tax calculation. If we have two tax rates and two amounts, C# would pick the first method based on four arguments and invoke that. The same holds true for the other two methods.

72.What is a check constrain.?

A. CHECK constraints enforce domain integrity by limiting the values that are accepted by a column. They are similar to FOREIGN KEY constraints in that they control the values that are put in a column. The difference is in how they determine which values are valid: FOREIGN KEY constraints obtain the list of valid values from another table, and CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.
You can create a CHECK constraint with any logical (Boolean) expression that returns TRUE or FALSE based on the logical operators. For the previous example, the logical expression is: salary >= 15000 AND salary <= 100000.
You can apply multiple CHECK constraints to a single column. You can also apply a single CHECK constraint to multiple columns by creating it at the table level. For example, a multiple-column CHECK constraint can be used to confirm that any row with a country/region column value of USA also has a two-character value in the state column. This allows for multiple conditions to be checked in one location.

73. Give me one example of abstract classes and interface?

A. Define an Abstract Class And Interface
In the following code listing an abstract class named Product has been defined.
Listing 1
public abstract class Product
{
//fields
protected string id;
Protected double price;
//properties



public abstract string ID
{
get;
set;
}

public abstract double Price
{
get;
set;

}
public abstract double CalculatePrice();
}
Define an Interface
In the following code listing an interface named Iproduct has been defined.
Listing 2
public interface Iproduct
{
string ID
{
get;
set;

}

double Price
{
get;
set;

}
double CalculatePrice();
}
Implementation
In the following code listing the Iproduct interface has been implemented by the class implementInterface.
Listing 3
public class implementInterface: Iproduct
{
protected string id;
protected double price;
public string ID
{
get
{
return id;
}
set
{
id = value;
}
}
public double price
{
get
{
return price;
}
set
{
price = value;
}

}
public double CalculatePrice()
{
return Price * 1.25;
}
In the following code listing the abstract Class named Product has been implemented by the class implementAbstract.
Listing 4
public class implementAbstract: Product
{
public override string ID
{
Get
{
return id;
}
Set
{
Id = value;
}

}
public override double Price
{
get
{
return price;
}
set
{
price = value;
}

}
public override double CalculatePrice
{
return Price * 1.25;
}

}
How to Test
In the following code listing abstract class implementation is being tested.
Listing 5
ImplementAbstract testAbstract=new implementAbstract();
testAbstract.ID=”A1”;
testAbstract.Price=1000.00;
double amt=testAbstract.CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+testAbstract.ID +” “+ “is”+” “+amt);
Response.Write(“
”);
In the following code listing the implementation of our interface is being tested.
Listing 6
ImplementInterface testInterface=new implementInterface();
testInterface.ID=”B1”;
testInterface.Price=900.00;
double Iamt= testInterface.CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+testInterface.ID +” “+ “is”+” “+Iamt);
Response.Write(“
”);
It should be noted that static members are not inherited under any circumstances. Hence we can not declare a static method in an interface because interfaces have no implementation. We can, however, declare a method as static in an abstract class, because abstract classes can have implementations of static methods. This has been described in the following code listing:
Listing 7
In an abstract class:
public static void test()
{
}
But we can not write the following in an interface.
Listing 8
static void test();

75. Can we use return statement in stored procedure?

A.Yes

76. How to cache a dataset.?
A. DataSet ds = (DataSet)Cache["mydata"];
if (ds == null) {
ds.ReadXml(Server.MapPath(_filename));
Cache.Insert("mydata", ds,
new CacheDependency(Server.MapPath(_filename)),
DateTime.Now.AddHours(12), NoSlidingExpiration);
}

myDataGrid.DataSource = ds;
myDataGrid.DataBind ();




77. What is the difference between ref & out parameters?
An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.

77. What is jagged array?

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays."
78.What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?
A: When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes)
Make a constructor private if:
- You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.
- You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

79. How to get one of cells value from gridview on rowcommand?
A. Integer selectedIndex = Integer.Parse(e.CommandArgument.ToString)
String Gid = gdvCamp.DataKeys(_selectedIndex).Value
String c_type = gdvCamp.Rows.Item(_selectedIndex).Cells(10).Text.ToString

8.Diff between nvarchar and varchar?
A. VARCHAR is an abbreviation for variable-length character string with a maximum limit of 8000 bytes.

NVARCHAR are the Unicode equivalents of VARCHAR. Unicode uses two bytes per character, which allows the storage of multilingual characters with a maximum length of 4000 bytes.

The most common use of NVARCHAR is to store character data that is a mixture of English and non-English symbols, such as English and Chinese. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension.

If your database will not be storing multilingual data you should use the VARCHAR datatype instead. This is because to store the extended character codes for other languages, NVARCHAR requires twice as much space as VARCHAR.

80. Can we use function overloading in web services?

A.Yes, but need to use diff value in messagename attribute in web method class.


Public Function GetWelcomeMessage(ByVal name As String) As String
C#
[WebMethod(MessageName="GetWelcomeMessageWithName")]
Public Function GetWelcomeMessage(ByVal name As String) As String

Now, compile the service again and run in the browser. You will notice that you get GetWelcomeMessageWithName listed rather than GetWelcomeMessage for the second web method. In all your client code you will use this method name instead of original method name. Your typical client code will look like this :

'I assume that you have created web service proxy
'either by WSDL utility or adding a web reference
'in VS.NET
Dim x as new MyWebServices.Service1()
'call first web method
dim str1 as string=x.GetWelcomeMessage()
'now call overloaded version
dim str2 as string=x.GetWelcomeMessageWithName()



81.Can we use all types of access specifiers in classes in web services.?

A. We can use private and protected internal only on classed if we any other then it would give compile time error but we can use all type of access specifiers in properties and methods with in the class.So the same applies in webservices too.
82. Basic Design Patterns and Groups

Design patterns have two major benefits. First, they provide you with a way to solve issues related to software development
using a proven solution. The solution facilitates the development of highly cohesive modules with minimal coupling. They
isolate the variability that may exist in the system requirements, making the overall system easier to understand and
maintain. Second, design patterns make communication between designers more efficient. Software professionals can immediately
picture the high-level design in their heads when they refer the name of the pattern used to solve a particular issue when discussing system design.

Design patterns fall into several groups based on the type and aims of the pattern. For example, some patterns provide
presentation logic for displaying specific views that make up the user interface. Others control the way that the application
behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define
best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses.
The following list shows some of the most common design patterns within these groups:

Model-View-Controller (MVC)
Model-View-Presenter (MVP)
Use Case Controller
Host or Behavioral Command
Publish-Subscribe / Observer
Plug-in / Module / Intercepting Filter
Structural
Service Agent / Proxy / Broker
Provider / Adapter
Creational
Factory / Builder / Injection
Singleton
Persistence
Repository

The Singleton Pattern

The Singleton pattern defines the creation of a class for which only a single instance can exist. It is useful for exposing
read-only data, and static methods that do not rely on instance data. Rather than creating an instance of the class each
time, the application obtains a reference to an existing instance using a static method of the class that implements the
Singleton pattern.

If this is the first call to the method that returns the instance, the Singleton creates an instance, populates it with any
required data, and returns that instance. Subsequent calls to the method simply return this instance. The instance lifetime is that of the application domain—in ASP.NET this is usually the lifetime of the domain Application object.

sample code in C#
This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

Hide code

// Singleton pattern -- Structural example

using System;

namespace DoFactory.GangOfFour.Singleton.Structural
{

// MainApp test application

class MainApp
{

static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}

// Wait for user
Console.Read();
}
}

// "Singleton"

class Singleton
{
private static Singleton instance;

// Note: Constructor is 'protected'
protected Singleton()
{
}

public static Singleton Instance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}
}


Output
Objects are the same instance



ASP.NET and the Model-View-Presenter Pattern

The ASP.NET code-behind technology, which uses partial classes, provides a natural implementation of the MVP pattern. The code-behind file (the Presenter) contains all the logic and processing code, and populates the page (the View). Event handlers within the code-behind file handle events raised by controls or by the page itself to perform actions when a postback to the server occurs. To complete this pattern, the code-behind file can use a separate data access layer or component (the Model) to read from, write to, and expose the source data—usually accessed through built-in providers that are part of the .NET Framework.

For example, a page might use a separate class that exposes methods to read and update a database table. This class might use the SqlClient, OleDb, or another data provider to connect to the database and execute dynamic SQL queries or stored procedures. The code in the code-behind file uses this class to retrieve the data, and populates the controls defined in the ASPX file that generates the user interface. When the user interacts with controls in the page, perhaps changing values in the data, code in the code-behind file executes during the postback and uses the data access class to push the changes back into the database.

Clicking one of the buttons causes a postback to the server and raises the event that corresponds to that button. For
example, the interface component for the second button shown in Figure 6 is an ASP.NET Button control, declared within the
View (the ASPX page), which initiates an event handler named btn_CustModel_Click in the Presenter (the code-behind file) to
handle the Click event:


Text="   "
OnClick="btn_CustModel_Click" />
Get name for customer
Text="ALFKI" Columns="3" />
from CustomerModel



The Presenter (the code-behind file) contains the declaration of the btn_CustModel_Click method, which creates an instance of the Model (a class file named CustomerModel.cs in the App_Code folder) and calls one of its methods to get the name of the customer identified by the customer ID users enter into the text box next to that button:


protected void btn_CustModel_Click(object sender, EventArgs e)
// display the name of the specified customer
{
try
{
// use method of the CustomerModel class
CustomerModel customers = new CustomerModel();
Label1.Text += "Customer Name from CustomerModel class: ";
Label1.Text += customers.GetCustomerName(
txtID_CustModel.Text);
}
catch (Exception ex)
{
Label1.Text += "PAGE ERROR: " + ex.Message;
}
Label1.Text += "

";
}

You can view the contents of the files Default.aspx (the View), Default.aspx.cs (the Presenter), and CustomerModel.cs (the
Model) that implement the MVP pattern in this example to see all the UI control declarations and code they contain. As you
saw in Figure 6, there are buttons to execute a range of CustomerModel methods, as well as methods of the Repository, Web
Reference and Service Agent implementations discussed in the following sections.

Visual Studio and the Service Agent and Proxy Patterns
The Proxy and Broker patterns provide a natural technique for connecting to and using remote services without forcing the use
of O/S or application-specific protocols such as DCOM. In particular, they are ideal for use with Web services. In Visual
Studio, when developers add a Web Reference to a project, Visual Studio automatically collects the Web service description
(including a WSDL contract file). This lets the code generate a suitable proxy class that exposes the methods of the remote
service to code in the application. Code in the application can then use the remote service by creating an instance of the
proxy class and calling the exposed methods defined in the contract. For example, here's the code used in the sample
application to call the CustomerName method of the DemoService service:

83. What is the diff between collection and list?
Collection.
A. These classes provide support for stacks, queues, lists, and hash tables, arraylist. Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.

Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.

Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.

The ArrayList and StringCollection classes and the List generic class offer access to their elements by the zero-based index of the element.

The Hashtable, SortedList, ListDictionary, and StringDictionary classes, and the Dictionary and SortedDictionary generic classes offer access to their elements by the key of the element.

List Class-

Contains any number of elements that are accessed sequentially. Lists are structures that can contain values of any X++ type. All the values in the list must be of the same type.

What are the differences between Method Overloading and Method Overriding?

i) Overloading deals with multiple methods in the same class with the same name but different signatures. Where as, overriding deals with two methods, one in the base class and another in the child class, that have the same signature.
ii) Overloading lets you define a similar operation in different ways for different data. Overriding lets you define a similar operation in different ways of different object types.
iii) In Overloading methods should have different signatures. But, in Overriding methods should have same signatures.
iv) In Overloading, two or more methods may belong to the same class. But in Overriding, two methods must belong to two different classes.
84. N-Tier and Example
Usually N-Tier Architecture begins as a 3-Tier model and is expanded. It provides finer granularity. Granularity is the ability of a system, in this case, an application, to be broken down into smaller components or granules. The finer the granularity, the greater the flexibility of a system. It can also be referred to as a system’s modularity. Therefore, it refers to the pulling apart of an application into separate layers or finer grains.
One of the best examples of N-Tier Architecture in web applications is the popular shopping-cart web application. The client tier interacts with the user through GUIs (Graphic User Interfaces) and with the application and the application server. In web applications, this client tier is a web browser. In addition to initiating the request, the web browser also receives and displays code in dynamic HTML (Hypertext Markup Language), the primary language of the World Wide Web. In a shopping cart web application, the presentation tier displays information related to such services as browsing merchandise, purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network. This layer calls custom tags throughout the network and to other networks. It also calls database stored procedures and web services, all in the goal of providing a more sophisticated response. This layer glues the whole application together and allows different nodes to communicate with each other and be displayed to the user through the browser. It is located in the application server.
In N-Tier Architecture, the business logic tier is pulled out from the presentation tier and, as its own layer; it controls an application’s functionality by performing detailed processing. For example, in our shopping cart example, this tier completes credit card authorization and calculates things like shipping costs and sales tax. The tools used to encapsulate an application’s business logic into its own layer include web services, custom tags, and stored procedures.
The business tier can also be considered the integration layer. Encapsulation allows the application to communicate with the data tier or the business logic tier in a way that is intelligible to all nodes. Encapsulation is one of the principles of object-oriented programming (OOP) and refers to an object’s ability to conceal its data and methods. Encapsulated objects only publish the external interface so any user interacting with them only needs to understand the interface and can remain ignorant as to the internal specifications. This way a user can call all sorts of services into action by calling the custom tag without having to know the code details of what made communication or implementation possible. The services just have to be accessible in the custom tag library. Encapsulation in the integration tier also liberates the network from just one vendor. The integration tier allows N-Tier Architecture to be vendor independent. In the shopping cart example, the application may have a simple custom tag for searching inventory and providing the most up-to-date, detailed information.
85. Write a program to reverse a string.

A. public string Reverse(string str)
{
int len = str.Length;
char[] arr = new char[len];

for (int i = 0; i < len; i++)
{
arr[i] = str[len - 1 - i];
}

return new string(arr);
}

Vb.net

Public Function Reverse(ByVal str As String) As String
Dim len As Integer = str.Length
Dim arr As Char() = New Char(len - 1) {}
For i As Integer = 0 To len - 1

arr(i) = str(len - 1 - i)
Next

Return New String(arr)

End Function
86.print all the prime numbers.?
A. ArrayList primeNumbers = new ArrayList();

for(int i = 2; i < 100; i++)
{
bool divisible = false;

foreach(int number in primeNumbers)
if(i % number == 0)
divisible = true;

if(divisible == false)
primeNumbers.Add(i);
}

Vb.net

Dim primeNumbers As New ArrayList()
For i As Integer = 2 To 10

Dim divisible As Boolean = False

For Each number As Integer In primeNumbers
If i Mod number = 0 Then
divisible = True
End If
Next

If divisible = False Then
primeNumbers.Add(i)
End If
Next

85.Similarties and diff bw gridview,datalist and repeater controls.

Examining the Similarities Between the Data Web Controls
The main similarity between the DataGrid, DataList, and Repeater Web controls is that all three have a DataSource property and a DataBind() method. In order to bind data to one of these data Web controls, the same technique is used:



In addition to these similarities, the data Web controls each also have the following three events:


ItemCreated,
ItemDataBound, and
ItemCommand

In Gridview
roqcreated
rowdatabound
rowcommand

Now, for each DataRow, first, a new DataGridItem is created. Then, the DataGrid's ItemCreated event fires. Next, the DataRow is assigned to the DataGridItem's DataItem property. Following this, the DataGrid's ItemDataBound event fires. This process is repeated for all of the DataRows.


Differences

The DataGrid Web control was designed to display data in an HTML

. Each row in the DataGrid's DataSource is displayed as a row in the HTML
. The DataGrid has an AutoGenerateColumns property, which can be set to either True or False. If AutoGenerateColumns is set to True (the default), each field in the DataSource is displayed as a column in the resulting HTML
. If, however, AutoGenerateColumns is set to False, then the developer must explicitly specify what columns should appear.

One downside of a DataGrid is its rather "blocky" display. That is, the DataGrid displays each DataSource record as a row in an HTML
, and each field as a column in said table. While the DataGrid allows for the developer to customize the output for a particular column through the , it still is restrictive in that each DataSource record occupies precisely one HTML
row. (For an example of customizing a DataGrid's column using templates, see Combining Two DataSource Fields Into One DataGrid Column.)


Datalist:

The DataList Web control is useful for displaying data that can be highly customized in its layout. By default, the DataList displays its data in an HTML
. However, unlike the DataGrid, with the DataList you can specify via the RepeatColumns how many DataSource records should appear per HTML
row. For example, the following code and live demo illustrates having five DataSource records displayed per HTML
row.

...
RepeatColumns="5" >

Question:

<%# DataBinder.Eval(Container.DataItem, "Description") %>


Views:

<%# DataBinder.Eval(Container.DataItem, "ViewCount", "{0:#,###}") %>


The DataList is capable of performing sorting, paging, and editing of its data, but to do so requires quite a bit more programming than to accomplish these tasks with the DataGrid. Therefore, if you know you will be needing these functionalities, it is likely best to proceed with the DataGrid. If, however, you will not need these functionalities, but do necessarily need the extra control over the formatting, consider a DataList.



Repeater Conrol

The Repeater control, unlike the DataGrid and DataList, is not derived from the WebControl class, and therefore does not have the stylistic properties that are common to all Web controls. (These stylistic properties that are common to all Web controls include Font, ForeColor, BackColor, BorderStyle, and so on.)

The Repeater, like the DataList, only supports templates; however, the Repeater has only a subset of the DataList's template options. Specifically, the following templates can be used with the Repeater:


AlternatingItemTemplate,
ItemTemplate,
HeaderTemplate,
FooterTemplate, and
SeparatorTemplate

One More template ll be added in cash of datagrid or datalist:
Edititem template

The Repeater control provides the maximum amount of flexibility over the HTML produced. Whereas the DataGrid wraps the DataSource contents in an HTML

, and the DataList wraps the contents in either an HTML
or tags (depending on the DataList's RepeatLayout property), the Repeater adds absolutely no HTML content other than what you explicitly specify in the templates.


86.Diff bw html control and server control.?

All this is true that both controls are nearly similar, but they have a vast difference that exists between them. The ASP .NET Server Controls are more rich in functionality as compared to their HTML Server Control counterparts. Let's take a look at some other differences that exist between these controls.
1. Control Abstraction:
A HTML Server Control has similar abstraction with its corresponding HTML tag and offers no abstraction.

ASP .NET Server Controls have higher level of abstraction. An output of an ASP .NET server control can be the result of many HTML tags that combine together to produce that control and its events.

2. Object Model:
The HTML Server Controls follow the HTML-centric object model.

ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls.

3. Browser Compatibility:
The HTML Server Controls have no mechanism of identifying the capabilities of the client browser accessing the current page.

ASP .NET Server Controls can however detect the target browser's capabilities and render themselves accordingly.
87. Diff between where and having.?

Introduction
We always get confused between WHERE and Having clause and make mistakes. Here in this article, I will try to highlight all the major differences between WHERE and HAVING, and things you should be aware of, when using either WHERE or HAVING.

------------------------------------------------------------------------------

Most of the time you will get the same result with Where or Having . The below given two SQL command produces the same result set That is, both count the number of records found for the states of California and Los Angles.

SELECT state, COUNT(*)
FROM Test
WHERE state IN ('CA', 'LA')
GROUP BY state
ORDER BY state

SELECT state, COUNT(*)
FROM Test
GROUP BY state
HAVING state IN ('CA', 'LA')
ORDER BY state

Background
(Optional) So, where is the difference ,Which is better? I'll let you answer those questions in a minute.

The main reason for using WHERE clause is to select rows that are to be included in the query. For example, assume table Test.Suppose I want the names, account numbers, and balance due of all customers from California and Los Angles. Since STATE is one of the fields in the record format, I can use WHERE to select those customers.

Using the code
SELECT cusnum, lstnam, init
FROM Test
WHERE state IN ('CA', 'LA')

CUSNUM LSTNAM INIT BALDUE
====== ============ ==== ========
938472 John G K 37.00
938485 Mark J A 3987.50
593029 Lily E D 25.00


Suppose I want the total amount due from customers by state. In that case, I would need to use the GROUP BY clause to build an aggregate query.

SELECT state,SUM(baldue)
FROM Test
GROUP by state
ORDER BY state

State Sum(Baldue)
===== ===========
CA 250.00
CO 58.75
GA 3987.50
MN 510.00
NY 589.50
TX 62.00
VT 439.00
WY .00



Points of Interest
Suppose I want the same information, but I don't care about states where nobody owes me any money. Since the total owed by state is an aggregate figure, i.e., the figure is generated from a group of records, you must use HAVING to select the proper data.

SELECT state,SUM(baldue)
FROM Test
GROUP by state
HAVING SUM(baldue) > 0
ORDER BY state

State Sum(Baldue)
===== ===========
CA 250.00
CO 58.75
GA 3987.50
MN 510.00
NY 589.50
TX 62.00
VT 439.00



Here's the rule. If a condition refers to an aggregate function, put that condition in the HAVING clause. Otherwise, use the WHERE clause.

Here's another rule: You can't use HAVING unless you also use GROUP BY.

Now, go back to the first example, where WHERE and HAVING produce the same result set. What's the difference? The first query uses the WHERE clause to restrict the number of rows that the computer has to sum up. But the second query sums up all the rows in the table, then uses HAVING to discard the sums it calculated for all states except Texas and Georgia. The first query is obviously the better one, because there is no need to make the computer calculate sums and then throw them away.

88.can foreign contain null values.?

A The value of a composite foreign key matches the value of a parent key if the value of each column of the foreign key is equal to the value of the corresponding column of the parent key. A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.
89. Interface usage and implelementation.
A. This C# Tutorial deals with interfaces in C# .Net. An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
Defining an Interface:
Let us look at a simple example for c# interfaces. In this example interface declares base functionality of node object.

Interface INode
{
string Text
{
get;
set;
}
object Tag
{
get;
set;
}

int Height
{
get;
set;
}

int Width
{
get;
set;
}

float CalculateArea();

}


The above INode interface has declared a few abstract properties and function which should be implemented by the derived classes.

//Sample for Deriving a class using a C# .Net interface - c# tutorial

public class Node : INode
{

public Node()
{}
public string Text
{

get
{
return m_text;
}

set
{
m_text = value;
}

}

private string m_text;
public object Tag
{

get
{
return m_tag;
}

set
{
m_tag = value;
}

}

private object m_tag = null;
public int Height
{

get
{
return m_height;
}

set
{
m_height = value;
}

}

private int m_height = 0;
public int Width
{

get
{
return m_width;
}

set
{
m_width = value;
}

}

private int m_width = 0;

public float CalculateArea()
{

if((m_width<0)||(m_height<0))
return 0;

return m_height*m_width;

}

}


Now the above code has created a c# class Node that inherits from INode c# interface and implement all its members. A very important point to be remembered about c# interfaces is, if some interface is inherited, the program must implement all its declared members. Otherwise the c# compiler throws an error.
The above code was a simple example of c# interface usage. Now this has to be followed with some advanced details of interface building in C# .Net. The previous example used only names of methods or properties that have the same names as in interface. But there is another alternative method for writing the implementation for the members in class. It uses full method or property name e.g. INode.CalculateArea () {// implemetation}.
Multiple Inheritance using C# interfaces:
Next feature that obviously needs to be explained is multiple inheritance using c# interfaces. This can be done using child class that inherits from any number of c# interfaces. The inheritance can also happen with a combination of a C# .Net class and c# interfaces. Now let us see a small piece of code that demonstrate us multiple inheritance using only interfaces as parent data types.

class ClonableNode : INode,ICloneable
{
Public object Clone()
{
return null;
}

// INode members
}


The above example created a class ClonableNode. It implements all the functionality of INode interface in the same way as it was done in Node class. Also it realizes Clone method only one item of IClonable interface of .NET library.
90. The following new features have been added to C# language with version 2.0 of .NET.
Generics
Iterators
Anonymous methods
- Anonymous Methods
C# supports delegates for invoking one or multiple methods. Delegates provide operators and methods for adding and removing target methods, and are used extensively throughout the .NET Framework for events, callbacks, asynchronous calls, and multithreading. However, you are sometimes forced to create a class or a method just for the sake of using a delegate. In such cases, there is no need for multiple targets, and the code involved is often relatively short and simple. Anonymous methods is a new feature in C# 2.0 that lets you define an anonymous (that is, nameless) method called by a delegate.
For example, the following is a conventional SomeMethod method definition and delegate invocation:
Copy Code
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = new SomeDelegate(SomeMethod);
del();
}
void SomeMethod()
{
MessageBox.Show("Hello");
}
}


You can define and implement this with an anonymous method:
Copy Code
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
MessageBox.Show("Hello");
};
del();
}
}


Partial classes

91. New Features In Asp.net 3.0

-ASP.NET 3.0 is not a new version of ASP.NET. It's just the name for a new ASP.NET 2.0 framework library with support for Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation; and Windows CardSpace

Wpf-
Windows Presentation Foundation (hereafter referred to as WPF) is a new API for creating graphical user interfaces for the Windows platform. It is an alternative to WinForms that further empowers developers by providing an API capable of taking full advantage of the multimedia facilities of the modern PC. Unlike WinForms, it does not wrap Win32 but is completely new, built from the ground up using .NET. The fundamental power of WPF comes from the fact that it is vector based, hardware accelerated and resolution independent.
Reminiscent of WinForms, you’ll find many of the controls you are used to when building applications: Button, ComboBox, ListBox, etc. However, in WPF, your UI design is represented in a completely different fashion. Instead of using a designer generated code file or a resource file as the source of a UI definition, WPF uses XML. Specifically, it uses XAML

92.What is static constructor.?

A. C# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-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 non-static data member of a class.
Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.
You may say, why not initialize static data members where we declare them in the code. Like this :
private static int id = 10;
private static string name = "jack";
Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.
Let me explain you with examples:
//File Name : Test.cs
using System;
namespace Constructor
{
class Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
public static void print()
{
Console.WriteLine("Test.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test.print();
}
}
}

In the above example, static data member is declared and initialized in same line. So if you compile and run this program your output would look similar to this :
Test.id = 5
Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member of class Test.id.
//File Name : Test1.cs
using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < 10 )
{
id = 20;
}
else
{
id = 100;
}
Console.WriteLine("Static Constructor for Class Test1 Called..");
}
public static void print()
{
Console.WriteLine("Test1.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test1.print();
}
}
}

As you can see in the above static constructor, static data member is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :
Static Constructor for Class Test1 Called..
id = 20
Since in class Test was initialized with a value of 5, therefore in class Test1 got initialized to a value of 20.
Some important point regarding static constructor from C# Language Specification and C# Programmer's Reference:
1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
---------------Yet to take print out----------------
83. Tell me something about passport authentication?
Passport authentication is a centralized, single sign-on authentication service provided by Microsoft. At present a large number of Internet users use Microsoft services such as MSN or Hotmail. They submit their profiles during the registration process in those Microsoft services. The real benefit is that you can utilize the user profile data in your Web sites if you implement passport authentication in your site. That is, information about the user is accessible to your application through a profile that is stored with Microsoft. Many companies, such as McAfee.com and eBay, employ Passport authentication in their Web sites. The benefit of Passport authentication is that the user doesn't have to remember separate usernames and passwords for various Web sites, and the user can keep his or her profile information in a single location. .NET Passport[11] provides users with single sign-in (SSI) and stores the authentication information using encryption technologies such as Secure Sockets Layer (SSL) and the 3DES algorithm for data protection. Figure 9-4 shows the Microsoft .NET Passport home page.

The general procedure to implement Passport authentication in an ASP.NET application is as follows:
• Register your site with the passport service.
• Download, install, and configure the Passport SDK from Microsoft Download or in http://www.passport.com. To deploy Passport on a real-time Web site, you have to register and get a production key, for which Microsoft charges a licensing fee.[12] For authentication, the user is directed to the page http://login.passport.com.
[12] There are two fees for licensing .NET Passport: a periodic compliance testing fee of $1,500 US and a yearly provisioning fee of $10,000 US. The provisioning fee is charged on a per-company basis.
• While testing your site, you cannot employ regular Passport accounts to sign in. Instead, to test the SDK, you have to launch a PREP Passport account or Preproduction key.[13] The Preproduction (PREP) environment allows sites to confirm their development efforts against .NET Passport servers without access to real-world .NET Passport user identifications and profiles. This preproduction registration can be done at http://current-register.passporttest.com. For authentication, the user is redirected to the site http://current-login.passporttest.com (the address of the PREP Login server).
[13] Do not use your Production password for PREP passwords. The PREP system is a separate test environment containing only test data, so it is best for security purposes to keep your Production password unique to the Production system.
• Configure the Web.config file as

84. Tell me something abt forms authentication.
A. Securing a Web Application with Forms Authentication
For varying kinds of risk you need varying kinds of security. For an intranet application it may be suitable to use Windows authentication (see Chapter 13 for more information), but for Internet applications you may want to use a more aggressive approach. For example, you may elect to have users log in using forms authentication and further restrict access based on assigned roles for those users. The first step is to authenticate the user. I will demonstrate forms authentication here. (For a good example of forms authentication and roles-based security, refer to the IBuySpy portal code available for download from Microsoft at http://www.asp.net.com.)
Forms authentication is just what it sounds like. You are going to provide a login form for the user to enter a user name and password; authenticate that user, and allow access if the person provides valid credentials. There are a few pieces to this puzzle. The first two occur in the Web.config file. We need to modify the Web.config file for the application that requires authentication; specifically we need to modify the and tags. Additionally, we will need to provide some sort of login form. Finally, we need to set an authorization cookie if the user is authenticated. Listing 15.31 shows the Web.config modifications.
Listing 15.31 Modifying the Web.config File for Forms Authentication
loginUrl="Login.aspx" protection="All"> timeout="20" The authentication mode is set to Forms. (The default is Windows integrated.) When we change authentication to Forms we need to include a nested tag, which specifies the cookie name, a login URL , a protection attribute that describes how the cookie is stored, and an expiration attribute, timeout. In Listing 15.31 we have indicated that the user should be redirected to a page named Login.aspx for authentication. The protection value All means that the authentication cookie is validated and encrypted, and the authentication cookie will expire after 20 minutes.
The authorization section is very simply set to deny all unauthenticated users. (The wildcard ? means unauthenticated users.) With these settings all users will be redirected to the Login.aspx page for authentication. (The Login.aspx page is included in CachingDemo.sln.)
As mentioned above, if the user is authenticated, we need to set an authorization cookie. Listing 15.32 shows some very basic code for that.

Listing 15.32 Setting an Authentication Cookie for Authorized Users
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Authenticate here! FormsAuthentication.SetAuthCookie(TextBox1.Text, True) Response.Redirect(Request.ApplicationPath + "/WebForm1.aspx") End SubThe
Button1_Click code is from the Login.aspx page. The code simply authenticates everyone. In a production application you would read the user name and password from some repository. If the supplied user name and password were valid, you would call FormsAuthentication.SetAuthCookie and redirect the user to the requested path.
In the listing the second argument to SetAuthCookie indicates that the authorization cookie is persisted, which means the user will still be authenticated after the browser closes and until the cookie expires. Pass False if you want the cookie to reside in-memory and expire when the user closes the browser. Finally, in the Redirect statement I had to add the name of the page because I didn't use one of the default pages for my instance of IIS. Had the page been named default.aspx, I could return the user to the originally requested page with Response.Redirect(Request.ApplicationPath).

This section covers basic forms authentication. To go beyond that, you will need to create an instance of a class that implements IPrincipal, add a string list of roles, and assign this principal object to the Context.User property. The string roles can be used to verify the roles of an authenticated user.

85. What is .ashx handler file?
A. Basically when we execute an aspx file it generally submits the html contents to the browser and user returned with html contents. But sometime we want return some xml content to browser so that user can download from the browser
Ex
There are lots of suggestions creating a regular ASPX page (say rss.aspx) and in Page_Load use Response. Write to return the XML
Response.ContentType = "text/xml";
Response.ContentEncoding = Encoding.UTF8;

string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string

Response.Write( sXml );
Response.End();

Then that same can be done using aspx file but takes lots of overheads. So to overcome that a new page type with .ashx extension has been intertroduced.
Now the above same code can be implemented in ashx file.
86. What is operator overloading?
All unary and binary operators have pre-defined implementations that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#. The following table shows the operators and their overloadability in C#.
Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can't be overloaded

() (Conversion operator) They can't be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ->, new, is, as, sizeof These operators can't be overloaded
In C#, a special function called operator function is used for overloading purpose. These special function or method must be public and static. They can take only value arguments. The ref and out parameters are not allowed as arguments to operator functions. The general form of an operator function is as follows
88. Q: Why isn't Session_End fired when I call Session_Abandon?
A: First of all, Session_End event is supported only in InProc mode. In order for Session_End to be fired, your session state has to exist first. That means you have to store some data in the session state and has completed at least one request.




89. Geniric Class-

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.
The List<(Of <(T>)>) class is the generic equivalent of the ArrayList class. It implements the IList<(Of <(T>)>) generic interface using an array whose size is dynamically increased as required.
In deciding whether to use the List<(Of <(T>)>) or ArrayList class, both of which have similar functionality, remember that
the List<(Of <(T>)>) class performs better in most cases and is type safe. If a reference type is used for type T of the
List<(Of <(T>)>) class, the behavior of the two classes is identical. However, if a value type is used for type T, you need
to consider implementation and boxing issues.

Example-

List dinosaurs = new List();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

86. Anonymous Methods:

In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.
Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:
C# Copy Code
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!");

By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.
Disadvantage:
The scope of the parameters of an anonymous method is the anonymous-method-block.
It is an error to have a jump statement, such as goto, breaks, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous Method blocks whose target is inside the block.
87. Partial Classes-
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.
To split a class definition, use the partial keyword modifier, as shown below:
Ex-
public partial class Employee
{
public void DoWork()
{
}
}

public partial class Employee
{
public void GoToLunch()
{
}
}

Need To Check-

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace.
All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All
the parts must have the same accessibility, such as public, private, and so on.

If any of the parts are declared abstract, then the entire type is considered abstract. If any of the parts are declared
sealed, then the entire type is considered sealed. If any of the parts declare a base type, then the entire type inherits
that class.

All of the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts
can specify different base interfaces, and the final type implements all of the interfaces listed by all of the partial
declarations. Any class, struct, or interface members declared in a partial definition are available to all of the other
parts. The final type is the combination of all the parts at compile time.


88. What is web farm?
A Web site that has more than one server or (2) an Internet service provider that provides Web hosting services using
multiple servers.

What is the use of web farm?



To Increasing Scalability through IIS Load Balancing:-

Web farms not only increase performance by reducing the load on each server in the Web farm, they also increase availability.
If one server in the Web farm is disabled (such as being taken offline for maintenance), other servers in the Web farm take
over, so users are never aware of the offline server.

Steps to Remember while hosting site

In a Web farm, each client request can go to a different machine on every postback. Because of this behavior, you cannot leave the validation Key attribute set to AutoGenerate in the Machine.config file. Instead, you must set the value of the validation Key attribute to a fixed string that is shared by all the machines on the Web farm.
Generate Machine Key Elements for Web Farm

The Element configures keys to use for encryption and decryption of forms authentication cookie data and
view state data, and for verification of out-of-process session state identification.

Here is an example of Configuration Structure for the element:

Listing 1



decryptionKey="AutoGenerate|value[,IsolateApps]"
validation="SHA1|MD5|3DES"/>

Session Maintenance
[ Back To Top ]


The default ASP.NET in-process session state handling, results in server affinity and cannot be used in a Web farm scenario.
For Web farm deployments, the session state must be stored out of process in either the ASP.NET State service or a SQL Server database.
Out of Process Mode

In the Out of Process mode, the session information is stored in a separate “state server” process. The worker process ("aspnet_wp.exe") will communicate with the state server ("aspnet_state.exe") to retrieve session information. However, the use of state server mode can affect the performance of the application by 10-15%. The main reason for this performance hamper is due to the fact that session information resides in a separate process (i.e. in a memory area outside the direct control of the asp_net worker process). So with every request, the worker process has to get the session values from a separate process.
To keep session information outside the worker process, the objects inside the session must be serializable. So with end of every request, the objects inside the session are serialized and with the beginning of each request, the objects are de-serialized.
To continue to use the state server model, the sessionstate parameter in the web.config file needs to be updated.
Listing 5:


mode="stateserver"
cookieless="false"
timeout="20"
stateconnectionstring="data source=127.0.0.1;user id=userid;password=password"
server="127.0.0.1"
port="42424"/>
The default data source is set to the local machine so if the state server is on a different machine as that
of the application then the correct machine name should be given on the web.config file.
SQL Server Mode
In the SQL Server mode the information is stored in the SQL Server rather than memory. But to use the SQL Server session state, we need to create the necessary tables and the stored procedures that ASP.NET will look for on the identified SQL Server. The SQL Server mode affects the performance to a greater degree, but makes the session information more secure as we can have two or more identical computers running SQL server for a single database. So if one computer fails another computer can take over and serve requests without session data loss.
For applications in ASP.NET 1.1 and SQL 2000
To configure to use the SQL Server mode, the sessionstate parameter in the web.config needs to be updated.
Listing 6

Mode="sqlserver"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=MySqlServer;user id=ASPState;password=1Gr8State"
server="127.0.0.1"
port="42424" />
Configure the SQL Server to store Session objects by running a script to create the ASPState database.
Version 1.0 of the .NET Framework provides a state database configuration script in
%SYSTEMROOT%\Microsoft.NET\Framework\v1.0.3705\InstallSqlState.sql. If you open the file, you will see a statement to create a database called ASPState.

For applications in ASP.NET 2.0 and SQL 2005
To install the session state database on SQL Server, run Aspnet_regsql.exe tool and supply the following information with the command.

• The name of the SQL Server instance, using the -S option
• The logon credentials for an account that has permission to create a database on a computer running SQL Server: Use the -E option to use the currently logged-on user, or use the -U option to specify a user ID along with the -P option to specify a password.
• The -ssadd command-line option to add the session state database
Listing 7
aspnet_regsql.exe -S -U -P -ssadd -sstype pYou can run Aspnet_regsql.exe without any
command-line arguments to run a wizard that will walk you through specifying connection information for your SQL Server
database and installing or removing the database elements for supported features. You can also run Aspnet_regsql.exe as a
command-line tool to specify database elements for individual features to add or remove.

To run the wizard, run Aspnet_regsql.exe without any command-line arguments, as shown in the following example.
89. WebGarding-
Web garden is a scenario in which a single machine has multiple aspnet worker processes running simultaneously. To achieve this, machine should have multiple CPU and scheduling of the job is done by Windows. To set up web garden, open machine.config on your machine, and go down to processmodel section. The attribute webgarden will be set to true and cpumask is used to indicate which CPU can run ASP.NET worker processes.

91. What is varcharmax?
A. When we use varchar it ‘s capacity is 8000 so to use more then that capacity we can opt for varchar max which is newly introduced.
92. What is global.asax?
A. The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks. Let's take a closer look at how you may use it in your application development efforts.
Overview
The Global.asax file is in the root application directory. While Visual Studio .NET automatically inserts it in all new ASP.NET projects, it's actually an optional file. It's okay to delete it—if you aren't using it. The .asax file extension signals that it's an application file rather than an ASP.NET file that uses aspx.
The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.
Programming
The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The Global.asax file contains the following events:
• Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.
• Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
• Application_Error: Fired when an unhandled exception is encountered within the application.
• Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
• Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.
• Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.
• Application_EndRequest: The last event fired for an application request.
• Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
• Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
• Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
• Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
• Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
• Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
• Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
• Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
• Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
• Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
• Session_Start: Fired when a new user visits the application Web site.
• Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

92. In check the given data is integer or not?
A.We need to use isinteger function?
function validateInt()
{
var o = document.frmInput.txtInput;
switch (isInteger(o.value))
{
case true:
alert(o.value + " is an integer")
break;
case false:
alert(o.value + " is not an integer")
}
}
93.How to check whether browser supports javascript or not.?
If (page.request.browser.javascript)
{}
94.Find the value of xml file using stored procedure.?
A.
CREATE PROCEDURE SelectByIdList(@productIds xml) AS

DECLARE @Products TABLE (ID int)

INSERT INTO @Products (ID) SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @productIds.nodes('/Products/id') as ParamValues(ID)

SELECT * FROM
Products
INNER JOIN
@Products p
ON Products.ProductID = p.ID
Now we can call it as follows:

EXEC SelectByIdList @productIds='3615'

95.Basic diff between gridview and datagrid.?
A. The main difference between a DataGrid and a GridView control is that the DataGrid control has centralized event handling which means any event raised by a control inside the DataGrid’s template column will be handled by the ItemCommand event of the DataGrid. But this functionality is some what different in the GridView control. It directly calls the handler of the control.
I mean to say that in the GridView control, if you add a template column having a GridView inside it and then if you select the Column Sorting command, it will not call any event of the master grid, but will directly call the sorting handler of the child grid. It is up to the user to take advantage of this feature.
96.Refrash parent window while closing a child window.?
protected void Page_Load(object sender, EventArgs e)
{
string scriptString = "";

// ASP.NET 2.0
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}

//// ASP.NET 1.X
//if (!Page.IsClientScriptBlockRegistered(scriptString))
//{
// Page.RegisterClientScriptBlock("script", scriptString);
//}

if (!Page.IsPostBack) { }
}

96.What is crosspage posting.?
one technique to achieve crosspage posting is use action attribute as target url in the form tag and set methods as post, this ll transfer all the required data to to target page and in that target page we can collect the values like request. form(“control name”).
Problem with this approach is we can’t use run at server in the form tag,so we can’t use any server control.
To overcome that problem in .net 2.0 a new feature has been interduced called as postbakurl property which need to be set with target page url in the button
Control of the form and to collect the data in target page we need to fallow the fallowing approach.
if (PreviousPage != null)
{
TextBox nameTextBox =
(TextBox)PreviousPage.Form.FindControl("_nameTextBox");
TextBox ageTextBox =
(TextBox)PreviousPage.Form.FindControl("_ageTextBox");
CheckBox marriedCheckBox =
(CheckBox)PreviousPage.Form.FindControl("_marriedCheckBox");

_messageLabel.Text = string.Format(
"

Hello there {0}, you are {1} years old and {2} married!

",
nameTextBox.Text, ageTextBox.Text,
marriedCheckBox.Checked ? "" : "not");
Link-http://www.informit.com/articles/article.aspx?p=680819



97. Tell me something about try catch and finally block.
Multiple catch blocks with different exception filters can be chained together. Multiple catch blocks are evaluated from top to bottom, but only one catch block is executed for each exception thrown. The first catch block that species the exact type or a base class of the thrown exception will be executed. If no catch block specifies a matching exception filter, then a catch block with no filter (if any) will be executed. It is important to place catch blocks with the most specific — most derived — exception classes first.
Throw-
Throwing an Exception

In C#, it is possible to throw an exception programmatically. The ‘throw’ keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throws an ArgumentException explicitly.

throw new ArgumentException(“Exception”);

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
Try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}

98. What is default port number of iis?
A.80
99. Default port no for assembly.
A.1.0.0.0
100.How can u get the index for the selected row.?
A. Gridview.selectedindex

101. What is wcf and wpf?
Wcf-
Introduction:
When your business relies on a service-oriented architecture, you must make sure that your services are robust. The most important driver behind the robustness of your application is where/how you host your service. You must ask yourself several questions when thinking about hosting services: What are the availability requirements of my services? How am I going to manage and deploy my services? Do I need to support older versions of my services?
Learning how to cover these business requirements is essential to developing successful services. As you learned in Chapter 3, you have to host services on your own host. Windows Communication Foundation (WCF) doesn't come with its own host, but instead comes with a class called ServiceHost that allows you to host WCF services in your own application easily. You don't have to think about any of the network transport specifics to be able to make sure that your services are reachable. It's a matter of configuring your services' endpoints either programmatically or declaratively, and calling the Open method of ServiceHost. All of the generic functionality regarding bindings, channels, dispatchers, and listeners that you learned about in Chapter 3 is integrated into ServiceHostBase and ServiceHost. This means that the responsibility of the application that you use to host your service, the application where ServiceHost is running, is significantly less than you would expect up front.
This chapter is about which types of applications you can use to host ServiceHost. In addition, you will learn about the differences when you want to consume these services hosted in different applications.
Self-Hosting Your Service
The most flexible and easiest way to host WCF services is by self-hosting. To be able to self-host your services, you have to meet two requirements. First, you need the WCF runtime; second, you need a managed .NET application in which you can host ServiceHost. It is your own responsibility to write the code that starts and stops the host.
The following are the advantages of self-hosting:
Is easy to use: With only a few lines of code you have your service running.
Is flexible: You can easily control the lifetime of your services through the Open() and Close() methods of ServiceHost.
Is easy to debug: Debugging WCF services that are hosted in a self-hosted environment provides a familiar way of debugging, without having to attach to separate applications that activate your service.
Is easy to deploy: In general, deploying simple Windows applications is as easy as xcopy. You don't need any complex deployment scenarios on server farms, and the like, to deploy a simple Windows application that serves as a WCF ServiceHost.
Supports all bindings and transports: Self-hosting doesn't limit you to out-of-the-box bindings and transports whatsoever. On Windows XP and Windows Server 2003, IIS limits you to HTTP only.
The following are the disadvantages of self-hosting:
Limited availability: The service is reachable only when the application is running.
Limited features: Self-hosted applications have limited support for high availability, easy manageability, robustness, recoverability, versioning, and deployment scenarios. At least, out-of-the-box WCF doesn't provide these, so in a self-hosted scenario you have to implement these features yourself; IIS, for example, comes with several of these features by default.
In other words, you shouldn't consider self-hosting for enterprise scenarios. Self-hosting is suitable during the development or demonstration phases of your enterprise project. Another suitable example where you would self-host your services is when you want applications on a user desktop to communicate with each other or in a peer-to-peer scenario

Link-http://msdn.microsoft.com/en-us/library/bb332338.aspx

How to consume the wcf servive once it is hosted in the application using servicehost class.?

We can create the proxy of the service using the fallowing options.

1)Add servive reference like for webservice
2)or else we can use a SvcUtil.exe command line tool called.

WPF-
Windows Presentation Foundation (hereafter referred to as WPF) is a new API for creating graphical user interfaces for the Windows platform. It is an alternative to WinForms that further empowers developers by providing an API capable of taking full advantage of the multimedia facilities of the modern PC. Unlike WinForms, it does not wrap Win32 but is completely new, built from the ground up using .NET. The fundamental power of WPF comes from the fact that it is vector based, hardware accelerated and resolution independent.
Reminiscent of WinForms, you’ll find many of the controls you are used to when building applications: Button, ComboBox, ListBox, etc. However, in WPF, your UI design is represented in a completely different fashion. Instead of using a designer generated code file or a resource file as the source of a UI definition, WPF uses XML. Specifically, it uses XAML. Please, don’t let this frighten or dissuade you. It’s surprisingly intuitive and much easier than you would think (not to mention fun). There are many other new features in WPF, too many to discuss in this tutorial. Below, you can see a chart depicting what I consider to be some of the most important features/innovations in WPF.
102) what is an application domain - an explanation for .Net beginners
An application domain is the CLR equivalent of an operation system's process. An application domain is used to isolate applications from one another. This is the same way an operating system process works. The separation is required so that applications do not affect one another. This separation is achieved by making sure than any given unique virtual address space runs exactly one application and scopes the resources for the process or application domain using that address space.
However, a CLR application domain is separate from a process. It is contained within an operating system process. A single CLR operating system process can contain multiple application domains. There are some major pluses to having application domains within a single process.
Lower system cost - many application domains can be contained within a single system process.
The application in an application domain can be stopped without affecting the state of another application domain running in the same process.
A fault or exception in on application domain will not affect other application domains or crash the entire process that hosts the application domains.
Configuration information is part of an application domains scope, not the scope of the process.
Each application domain can have different security access levels assigned to them, all within a single process.
Code in one application domain cannot directly access code in another application domain. (* see below)

So you see, the CLR is like a mini
103) how can u make communicate with two application domains?

NET remoting enables you to build widely distributed applications easily, whether application components are all on one computer or spread out across the entire world. You can build client applications that use objects in other processes on the same computer or on any other computer that is reachable over its network. You can also use .NET remoting to communicate with other application domains in the same process. (For details about programming application domains, see Programming with Application Domains.)
.NET remoting provides an abstract approach to interprocess communication that separates the remotable object from a specific client or server application domain and from a specific mechanism of communication. As a result, it is flexible and easily customizable. You can replace one communication protocol with another, or one serialization format with another without recompiling the client or the server. In addition, the remoting system assumes no particular application model. You can communicate from a Web application, a console application, a Windows Service – from almost anything you want to use. Remoting servers can also be any type of application domain. Any application can host remoting objects and provide its services to any client on its computer or network.
To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following:
• A remotable object.
• A host application domain to listen for requests for that object.
• A client application domain that makes requests for that object.
Even in a complex, multiclient/multiserver application, .NET remoting can be thought of in this way. The host and the client application must also be configured with the remoting infrastructure and you must understand the lifetime and activation issues that the remoting infrastructure introduces
103)How can you create transaction using ado.net.?

My copy of Pro ADO.NET 2.0 by Apress showed up the other day. I am not ready to give my final review of it, but it seems to be a solid book. Most of ADO.NET has not changed with the release of ADO.NET 2.0, so when you buy a new book about ADO.NET 2.0 don't expect a wealth of new information.

Anywhoo, I thought I would share some basic information about SQL Server Transactions for those who are new to ADO.NET. The book does a good job of providing an overview of transactions and a basic template for how to execute local transactions in code. Here is the basic template for an ADO.NET 2.0 Transaction:

using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = null;

try
{
// BeginTransaction () Requires Open Connection
connection.Open();
transaction = connection.BeginTransaction();

// Assign Transaction to Command
command.Transaction = transaction;

// Execute 1st Command
command.CommandText = "Insert ...";
command.ExecuteNonQuery();

// Execute 2nd Command
command.CommandText = "Update...";
command.ExecuteNonQuery();

transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
A c# using statement wraps up the connection, because SqlConnection implements IDisposable. The using statement makes sure that Dispose() gets called on the connection object so it can free up any unmanaged resources.

Before you can begin a transaction, you must first open the connection. You begin your transaction and then assign any newly created command objects to that transaction and perform queries as necessary. Commit the transaction. If an error occurs, Rollback the transaction in a catch statement to void out any changes and then rethrow the error so that the application can deal with it accordingly. The connection is properly closed in the finally statement, which gets called no matter what, and any unmanaged resources are disposed when the using statement calls Dispose() on the connection. Pretty simple solution to a fairly advanced topic.

The above template could actually implement a second c# using statement around command, because SqlCommand also implements IDisposable. I don't know that it is really necessary, however. More theoretical than probably anything. I just like to see using statements around anything that implements IDisposable:

using (SqlConnection connection =
new SqlConnection(connectionString))
{
using (SqlCommand command =
connection.CreateCommand())
{
SqlTransaction transaction = null;

try
{
// BeginTransaction() Requires Open Connection
connection.Open();

transaction = connection.BeginTransaction();

// Assign Transaction to Command
command.Transaction = transaction;

// Execute 1st Command
command.CommandText = "Insert ...";
command.ExecuteNonQuery();

// Execute 2nd Command
command.CommandText = "Update...";
command.ExecuteNonQuery();

transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
}

104. Can we alter view state data?
A. View State when used as it is, Has its security concerns. Though the data stored in hidden fields Are encoded using base64 encoding, it is still available to users to tamper with. So it is advisable to encrypt the data. To encrypt the data, set the page's ViewStateEncryptionMode property to true.
If you store information in view state, you can use normal read and write techniques; the page handles all encryption and decryption for you. Encrypting view state data can affect thePerformance of your application, so do not use encryption unless you need it.
In the @ Page directive, set the ViewStateEncryptionMode attribute to "Always".
So that’s an overview of View State in ASP.Net
105. What are custom controls?
Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.
How to choose the base class for your custom control
To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:
You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, and are examples of nonvisual rendering.
You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.
If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.

In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.
How to create and use a simple custom control that extends from System.Web.UI.Control using Visual Studio
Start Visual Studio.
Create a class library project, and give it a name, for example, CustomServerControlsLib.
Add a source file to the project, for example, SimpleServerControl.cs.
Include the reference of the System.Web namespace in the references section.
Check whether the following namespaces are included in the SimpleServerControl.cs file.
System
System.Collections
System.ComponentModel
System.Data
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls


Inherit the SimpleServerControls class with the Control base class.
public class SimpleServerControl : Control

Override the Render method to write the output to the output stream.
protected override void Render(HtmlTextWriter writer)
{
writer.Write("Hello World from custom control");
}
Note The HtmlTextWriter class has the functionality of writing HTML to a text stream. The Write method of the HtmlTextWriter class outputs the specified text to the HTTP response stream and is the same as the Response.Write method.
Compile the class library project. It will generate the DLL output.
Open an existing or create a new ASP.NET Web application project.
Add a Web Forms page where the custom control can be used.
Add a reference to the class library in the references section of the ASP.NET project.
Register the custom control on the Web Forms page.
<%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>

To instantiate or use the custom control on the Web Forms page, add the following line of code in the
tags.




Note In this code, SimpleServerControl is the control class name inside the class library.Run the Web Forms page, and you will see the output from the custom control.
105. Refresh parent window while closing a child window
What if you were to pass to the child window the url of the parent window.
When you close the child window, redirect to the url of the parent window,
using javascript, use something like...
window.open(url);
window.close();
106. How can u implement custom paging in .net?
A. We can do dis by using row number().
ROW_NUMBER Function in SQL2005
SQL Server 2005 comes with ROW_NUMBER that provide row number capability without sacrifice the server resources with unneeded table scan. This function can be used for various tasks, not only for displaying row number field. With this function on hand, you can solve the above problem with the following statement: USE NorthWind
Go
SELECT ROW_NUMBER() OVER (ORDER BY ProductID) as RowNumber,ProductID, ProductName, UnitPrice FROM Products
This approach need only one table scan instead of twice as the sub query approach of SQL Server 2000. It will return the following result:
RowNumber ProductID ProductName UnitPrice
--------- ----------- ------------------------------- ---------------------
1 1 Chai 100.00
2 2 Chang 100.00
3 3 Aniseed Syrup 100.00
4 4 Chef Anton's Cajun Seasoning 100.00
Please give attention to the OVER keyword that used as a base for numbering process. That query does numbering based on the order of ProductID field. You will get different result if replace (ORDER BY ProductID) with (ORDER BY ProductID DESC). The different result sets is also returned if you replace ProductID with another field.
Modify the above query become the following script and hit F5 key:
SELECT ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) as RowNumber,ProductID, ProductName, UnitPrice
FROM Products
It returns the different result with the above query. This time you get result sets that already numbered based on UnitPrice field, with descending order.
Practical Use of ROW_NUMBER
Imagine you want to update the UnitPrice field of the Products table. The sales department wants to update ten most expensive products become 10% less. This puzzle can be solved with ROW_NUMBER function.
Consider the following UPDATE statement:
UPDATE Products
SET UnitPrice = 0.9 * UnitPrice
WHERE ProductID IN
(
SELECT ProductID FROM(
SELECT ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS Number, ProductID FROM Products) AS B
WHERE Number < = 10
)
The script updates ten most expensive products with 0.9 * UnitPrice. You also can do parameterized query, make it more flexible to determine the update criteria.
Custom Paging in Web Application
Another use of ROW_NUMBER is doing custom paging in ASP.NET application. ASP.NET data control such as old DataGrid (.NET 1.1) and GridView (.NET 2.0) support both default and custom paging. When paging with default method is simple and easy, it needs big overhead. When you navigate between pages with default paging enabled, it returned ALL data on every postback instead of the data that really needed for particular page. This is a big performance issue when dealing with large result sets.
Custom paging solves the problem by returning only the result sets needed for every page. ASP.NET 2.0 provides ObjectDataSource control that already supports custom paging.
The first task to do is creating stored procedure with two parameters: pageSize and startRowNumber. The pageSize parameter contains row amount of every page, and startRowNumber is used for storing starting row number for particular page.

CREATE PROC sp_GetProductsByPage
@pageSize int,
@startRowNumber int
AS
SELECT * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY ProductName) as RowNumber, ProductID, ProductName, UnitPrice
FROM Products) AS Products
WHERE RowNumber BETWEEN @startRowNumber AND (@startRowNumber + @pageSize )
The sp_GetProductsByPage procedure will return the only data needed for particular page. ObjectDataSource needs a business object that returns a DataTable, DataSet, or Collection object. So you create a Product class with 2 methods: GetProductsByPage and CountProduct.

The following code assuming that you already have a valid SqlConnection object.

public DataTable GetProductsByPage(int pageSize, int startRowNumber)
{

SqlCommand cmd = new SqlCommand();

SqlParameter prPageSize = new SqlParameter("@pageSize", SqlDbType.Int, 4);
cmd.Parameters.Add(prPageSize);
prPageSize.Value = pageSize;

SqlParameter prStartRow = new SqlParameter("@startRowNumber", SqlDbType.Int, 4);
cmd.Parameters.Add(prStartRow);
prStartRow.Value = startRowNumber;

cn.Open();
cmd.CommandText = "sp_GetProductsByPage";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;

DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));

return dt;
}

public int CountProduct()
{
SqlCommand cmd = new SqlCommand();

cn.Open();
cmd.CommandText = "SELECT COUNT(ProductID) FROM Products";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;

return (int)cmd.ExecuteScalar();
}
The GetProductsByPage function executes sp_GetProductsByPage stored procedure and returns result sets for every page. The CountProduct function is needed by ObjectDataSource for calculating input integer for startRowNumber parameter. The last action is build a webpage with Visual Web Developer 2005 Express (I love it, it's free!), drag and drop GridView and ObjectDataSource. Configure the ObjectDataSource to use Product class as data object, and choose GetProductsByPage as SELECT command. Skip Update, Insert, and Delete tab, and finish it. The ObjectDataSource property should be configured as follows: Don't forget to set up the AllowPaging property of the GridView to TRUE, and PageSize property to 10. Now you have a GridView with custom paging ability, something that more reliable and resource friendly that default paging.

107. 108.Invoking a webservice using html page.
A. In order to call remote methods from Web Services, you need to use the WebService behavior. The WebService behavior is implemented as an HTML Component (HTC), so it can be used in Microsoft Internet Explorer 5 and later versions. The WebService behavior communicates with Web Services over HTTP using Simple Object Access Protocol (SOAP).
The first step in using the WebService behavior is to attach it to an element using the STYLE attribute. It is also necessary to set the ID attribute so that this element can be easily referenced in script. You can attach the WebService behavior to various types of elements. Here is an example that shows how to attach it to a DIV element:
STYLE="behavior:url(webservice.htc)">

And here is an example that shows how to attach it to a BODY element:
STYLE="behavior: url(webservice.htc)">


html>

Ip2country



Consuming a webservice by HTML Page


onresult="getResult()">

IPnumber:

Country:



Demerits of this approach:

This procedure is only valid for simple data types such as strings, integer etc.
108. What is nullable type?

Introduction:

Have you ever needed to add a null value to your integer, date & time, decimal or Boolean etc... data types?! I'm sure you may face this desire before and you had to work around it to submit null value to those value data types. For example using DateTime.MinValue as a mark to a null value. But you cannot submit DateTime.MinValue to SQL Server Database, as this will throw an exception.
So .Net Framework 2.0 comes out with a great new feature and solution to your problem. It is The Nullable Value Types. I'm saying .Net Framework to generalize the feature as it is a new feature in both C# and VB.NET.
The New Story:
In .Net Framework 2.0, value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.
Nullable type is constructed from the generic Nullable structure. By having this feature, you can submit null values to you database table field normally, like submitting a null DateTime value to a datetime field in your database table.
Now how can we declare a nullable value type?
Simply like this:

C#

DataTime? dtmVarName = null;

int? intVarName = null;

bool? bVarName = null;

VB.NET
Dim dtmVarName As Nullable(Of DateTime)
Dim intVarName As Nullable(Of Integer)
Dim bVarName As Nullable(Of Boolean)
How can you check if your nullable value type contains data?
Simply by checking HasValue property attached to your nullable value type

C#:

if (dtmVarName.HasValue)

{

//...do something

}

VB.NET:
If dtmVarName.HasValue Then
'...do something
End If
To extract your normal value from your nullable type, use Value property, only if HasValue returns true.
Conclusion:
The following is written in MSDN, but I found it very useful to be used to close this article. Nullable types have the following characteristics:
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
108. Generic classes
By using this we can handle runtime errors at compile time.
A. Type Safety
Many of the languages in .NET, like C#, C++, and VB.NET (with option strict on), are strongly typed languages. As a programmer using these languages, you expect the compiler to perform type-safety checks. For instance, if you try to treat or cast a reference of the type Book as a reference of the type Vehicle, the compiler will tell you that such a cast is invalid.
However, when it comes to collections in .NET 1.0 and 1.1, there is no help with type safety. Consider an ArrayList, for example. It holds a collection of objects. This allows you to place an object of just about any type into an ArrayList. Let's take a look at the code in Example 1.
Example 1. Lack of type safety in ArrayList
using System;
using System.Collections;
namespace TestApp
{
class Test
{
[STAThread]
static void Main(string[] args)
{
ArrayList list = new ArrayList();

list.Add(3);
list.Add(4);
//list.Add(5.0);

int total = 0;
foreach(int val in list)
{
total = total + val;
}

Console.WriteLine(
"Total is {0}", total);
}
}
}
I am creating an instance of ArrayList and adding 3 and 4 to it. Then I loop through the ArrayList, fetching the int values from it and adding them. This program will produce the result "Total is 7." Now, if I uncomment the statement:
list.Add (5.0);
The program will produce a runtime exception:
Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
at TestApp.Test.Main(String[] args) in c:\workarea\testapp\class1.cs:line 18
What went wrong? Remember that ArrayList holds a collection of objects. When you add a 3 to the ArrayList, you are boxing the value 3. When you loop though the list, you are unboxing the elements as int. However, when you add the value 5.0, you are boxing a double. On line 18, that double value is being unboxed as an int, and that is the cause of failure.
(The above example, if it was written using VB.NET would not fail, however. The reason is VB.NET, instead of unboxing, invokes a method that converts the values into Integers. The VB.NET code will also fail if the value in ArrayList is not convertible to Integer. See Gotcha #9, "Typeless ArrayList Isn't Type-Safe," in my book .NET Gotchas for further details.)
As a programmer who is used to the type safety provided by the language, you would rather have the problems pop up during compile time instead of runtime. This is where generics come in.

What Are Generics?
Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation.
Using Generics Collections
The System.Collections.Generics namespace contains the generics collections in .NET 2.0. Various collections/container classes have been "parameterized." To use them, simply specify the type for the parameterized type and off you go. See Example 2:
Example 2. Type-safe generic List


List aList = new List();
aList.Add(3);
aList.Add(4);
// aList.Add(5.0);
int total = 0;
foreach(int val in aList)
{
total = total + val;
}
Console.WriteLine("Total is {0}", total);

In Example 2, I am creating an instance of the generic List with the type int, given within the angle brackets (<>), as the parameterized type. This code, when executed, will produce the result "Total is 7." Now, if I uncomment the statement doubleList.Add(5.0), I will get a compilation error. The compiler determines that it can't send the value 5.0 to the method Add(), as it only accepts an int. Unlike the example in Example 1, this code has type safety built into it.

110. Understanding VARCHAR(MAX) in SQL Server 2005
In SQL Server 2000 and SQL Server 7, a row cannot exceed 8000 bytes in size. This means that a VARBINARY column can only store 8000 bytes (assuming it is the only column in a table), a VARCHAR column can store up to 8000 characters and an NVARCHAR column can store up to 4000 characters (2 bytes per unicode character). This limitation stems from the 8 KB internal page size SQL Server uses to save data to disk.
To store more data in a single column, you needed to use the TEXT, NTEXT, or IMAGE data types (BLOBs) which are stored in a collection of 8 KB data pages that are separate from the data pages that store the other data in the same table. These data pages are arranged in a B-tree structure. BLOBs are hard to work with and manipulate. They cannot be used as variables in a procedure or a function and they cannot be used inside string functions such as REPLACE, CHARINDEX or SUBSTRING. In most cases, you have to use READTEXT, WRITETEXT, and UPDATETEXT commands to manipulate BLOBs.
To solve this problem, Microsoft introduced the VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) data types in SQL Server 2005. These data types can hold the same amount of data BLOBs can hold (2 GB) and they are stored in the same type of data pages used for other data types. When data in a MAX data type exceeds 8 KB, an over-flow page is used. SQL Server 2005 automatically assigns an over-flow indicator to the page and knows how to manipulate data rows the same way it manipulates other data types. You can declare variables of MAX data types inside a stored procedure or function and even pass them as variables. You can also use them inside string functions.

Microsoft recommends using MAX data types instead of BLOBs in SQL Server 2005. In fact, BLOBs are being deprecated in future releases of SQL Server.
111.Why it is not possible to implement multiple inheritance.?
In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?
For example, in the context of GUI software development, a class Button may inherit from both classes Rectangle (for appearance) and Mouse (for mouse events), and classes Rectangle and Mouse both inherit from the Object class. Now if the equal’s method is called for a Button object and there is no such method in the Button class but there is an over-ridden equals method in both Rectangle and Mouse, which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. Class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to Form a diamond shape.

112. Copy data from one table to another?
INSERT INTO TABLE2 (COL1, COL2, COL3) SELECT COL1, COL4, COL7 FROM TABLE1
113. Context Object?
A. One of the lesser known techniques for passing data between pages is the Context object. An instance of the context object is associated with every page instance. Because a page generally only lives on the server for milliseconds (while being executed and rendered), items stored in the Context object are short lived. In many situations this is the most efficient way to store items because they are quickly and automatically purged from memory. In addition to living for the life of a page, the Context object also stays in memory while transferring to another page. The following code stores an item in Page1 and then retrieves the item in Page2, after which the Context object (and all items it contains) are cleared from server memory:

'VB.NET
Context.Items("UserName") = TextBox1.Text 'Page1
Server.Transfer("Page2.aspx") 'Page1
Dim s As String = Context.Items("UserName").ToString 'Page2

//C#
Context.Items["UserName"] = TextBox1.Text; //Page1
Server.Transfer("Page2.aspx"); //Page1
string s = Context.Items["UserName"].ToString(); //Page2


Note: that Server.Transfer must be used here for this technique to work. Response.Redirect would fail because that makes a round trip to the client, which kills the instance of the Context object. Figure 1 details some of the side effects you may encounter.


112) How to handle thread abortion error in response.redirect.
A.Response.redirect ("destinationpage.aspx", false)
113) how view state works?
Answer:
Textbox does not use ViewState as its only mechanism to retain state over postback. When rendered in HTML browser, TextBox is normal INPUT element from browser standpoint. When form is posted, the value of that INPUT element is posted along with the form. This happens whether you have ViewState enabled or disabled. Note that TextBox implements IPostBackDataHandler interface, so it loads the related, posted value from form post collection in its implementation of IPostBackDataHandler.LoadPostData.
Does Textbox use View State at all? Yes, it does. TextBox's Text property is implemented pretty much like this:
Public string Text
{
get
{
string text=(string)ViewState["Text"];
return (text==null)? String.Empty : text;
}
set
{a
ViewState["Text"]=value;
}
}
As you can see, value of Text property is actually stored to ViewState. So, how does TextBox use ViewState in this case?
Well, in IPostBackDataHandler.LoadPostData TextBox uses ViewState as it compares the value of Text property to the value that is posted. As you probably guess, this is the case when TextBox's TextChanged event is raised if these values differ. If ViewState is disabled, Text property returns always String.Empty (it has not been assigned a value yet) and as a result posted value and Text property always differ and TextChanged event is raised every time.
After this, posted value is assigned to the Text property and rendered as the value of TextBox and things start over again. Note that Text property (ViewState collection actually) does keep its value during the same request even if ViewState is disabled. Disabling has impact on ViewState persistence not the functionality of ViewState collection. When ViewState is disabled, ViewState collection (System.Web.UI.StateBag) works similarly to the Context.Items collection. It is as it would be cleared for every request, but its values are valid during the same request.
114) what is the use of cookieless session.
Some clients won't be configured to support cookies. This is relevant because by default the session ID is stored as a cookie. However, if you're programming for a wireless device such as a cell phone, or browsers that may have cookies disabled, you can still use the Session cache. The Session cache works without cookies by embedding the session ID in the URL. To disable and test the Session cache without cookies, set the sessionState cookieless attribute to "true" in the
Web.config file.
Configuration Settings
For each of the above features (Forms Authentication, Anonymous Identification, and Session State), you can control if and when the cookiesless feature will be used, and when the cookieless feature will be used instead. The configuration setting controlling this is:
cookieless="UseCookies | UseUri | UseDeviceProfile | AutoDetect""UseCookies": As this name implies, the cookieless feature Will never be used.
"UseUri": The cookieless feature will always be used.
"UseDeviceProfile": Depending on the browser making the request, the cookieless feature may or may not be used. If ASP.NET recognizes that the browser does not support cookies, then the cookieless feature will be used. Technically speaking, the two Boolean variables Request.Browser.Cookies andRequest.Browser.SupportsRedirectWithCookie must both be true for ASP.NET to assume that cookies are supported by the browser.
"AutoDetect": In this setting, ASP.NET attempts to detect whether the browser supports cookies or not.
115. What is the main difference between Client side JavaScript and and Server side Java Script. How actually they run on both side with Example?
Client side JavaScript encompasses the core language plus extras such as the predefined objects, only relevant to running Javasript in a browser.The clientside javascript is embedded directly in the HTML pages and is interpreted by the browser completly at the run time. Serverside javascript also encompasses the core language plus extas as the predefined objects and functions only relevant to running Javasript in a server.The serverside javascripts are compiled before they are deployed.
116. How do you create a new object in JavaScript?
Var obj = new Object(); or var obj = {};
117) Diff between master pages and user control?
A user control is different to a Master page.
Which one is better to use? When should the web user control be used and vice versa?
You would use a master page when you want a general layout for all web pages, e.g. you want all web pages to have a common banner and to have a side nav bar
A user control is just a component which you want to resuse. E.g. you have created a set of drop down lists that is like a cascading drop down from country - state - city. You can then make this into a user control and put it on any web page you want to reuse it rather than duplicate code you have made it into a reusable component.
IMBack:
Since both of them used to modify the layout of the site?
As mentioned above, they do not both modify the layout. A master page provides a uniform layout to all child pages whilst user controls provides a means to create a reusable component from web controls.
118) how can I call a function which are in master page from the content page?
Ans.
Suppose there is a function declared in master page as
Public Function add () (We have to make it public)
Return 3
End Function
Now we have to call this in content page .Say that content page name is default2.
Then we have first declare directive at content page
<%@ MasterType VirtualPath="~/MasterPage.master" %>
Then At page or what ever we can call that function by fallowing syntax
Me.Master.add ()(vb.net) Or this.master.add(c#)
118) what is the extension of master page?
Ans.Master
Need to take printout rom here
119. A user control is different to a Master page.
Which one is better to use? When should the web user control be used and vice versa?
You would use a master page when you want a general layout for all web pages, e.g. you want all web pages to have a common banner and to have a side nav bar
A user control is just a component which you want to resuse. E.g. you have created a set of drop down lists that is like a cascading drop down from country - state - city. You can then make this into a user control and put it on any web page you want to reuse it rather than duplicate code you have made it into a reuseable component.


IMBack:
Since both of them used to modify the layout of the site?
As mentioned above, they do not both modify the layout. A master page provides a uniform layout to all child pages whilst user controls provides a means to create a reuseable component from web controls.
2) How can I call a function which is in master page from the content page.
Ans.
Suppose there is a function declared in master page as
Public Function adds () (We have to make it public)
Return 3
End Function
Now we have to call this in content page .Say that content page name is default2.
Then we have first declare directive at content page
<%@ MasterType VirtualPath="~/MasterPage.master" %>
Then At page or what ever we can call that function by fallowing syntex
Me.Master.add() (vb.net)
Or
this.master.add(c#)
3) What is the extension of master page?
Ans.Master

Q.Will the application runs if we remove web.config file from the application?

A. Yes it will but, debugging will not work.

1. Diff between http handlers and modules

Notice that during the processing of an http request, only one HTTP handler will be called, whereas more than one HTTP modules can be called.



Http Handlers


HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. One difference between HTTP handlers and ISAPI extensions is that HTTP handlers can be called directly by using their file name in the URL, similar to ISAPI extensions.

Steps involved in implementing our HTTP handler are as follows:
1. Write a class which implements IHttpHandler interface
2. Register this handler in web.config or machine.config file.


HTTP Modules


HTTP modules are .NET components that implement the System.Web.IHttpModule interface. These components plug themselves into the ASP.NET request processing pipeline by registering themselves for certain events. Whenever those events occur, ASP.NET invokes the interested HTTP modules so that the modules can play with the request.


To use both of them in application we have to register them in the web.config










BY USING HTTP MODULES WE CAN IMPLEMENT CUSTOM AUTHENTICATION
AND AUTHORIZATION MECHANISM IN OUR APPLICATION.


Q.What is an application domain -

An explanation for .Net beginners
An application domain is the CLR equivalent of an operation system's process. An application domain is used to isolate applications from one another. This is the same way an operating system process works. The separation is required so that applications do not affect one another. This separation is achieved by making sure than any given unique virtual address space runs exactly one application and scopes the resources for the process or application domain using that addess space.

However, a CLR application domain is separate from a process. It is contained within an operating system process. A single CLR operating system process can contain multiple application domains. There are some major pluses to having application domains within a single process.

Lower system cost - many application domains can be contained within a single system process.
The application in an application domain can be stopped without affecting the state of another application domain running in the same process.
A fault or exception in on application domain will not affect other application domains or crash the entire process that hosts the application domains.
Configuration information is part of an application domains scope, not the scope of the process.
Each application domain can have different security access levels assigned to them, all within a single process.
Code in one application domain cannot directly access code in another application domain. (* see below)

So you see, the CLR is like a mini

115) Search text based on given criteria

1) Exact-

Select * from tblImageDetails where colourname like '%Asp.net%'

2) Endswith

Select * from tblImageDetails where colourname like '_ean'

WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).

3) Select * from tbluser where user_name LIKE '[C-P]arsen
WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on.

4) Contains

The following example finds all telephone numbers that have area code 415 in the Contact table.

SELECT FirstName, LastName, Phone
FROM Person.Contact
WHERE phone LIKE '415%'
ORDER by LastName;

120. What are @@fetch_status values and meaning?

0
The FETCH statement was successful.

-1
The FETCH statement failed or the row was beyond the result set.

-2
The row fetched is missing.

121. Can we pass session variable from.net to asp page?

A. Yes we can as asp has its session management mechanism.

121. What is Linq which is newly introduced?

A.Language-Integrated Query (LINQ) is a groundbreaking innovation in Visual Studio 2008 and the .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data.
Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. LINQ makes a query a first-class language construct in C# and Visual Basic. You write queries against strongly typed collections of objects by using language keywords and familiar operators. The following illustration shows a partially-completed LINQ query against a SQL Server database in C# with full type checking and IntelliSense support.

121. Can u us delete and update in joins?

To answer your question about "Can I use Joins to delete?” yes you can perform deletes with joins and here's an example:

DELETE Orders
FROM Orders INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
WHERE Customers.FirstName = 'Test'

121 Can We Use Truncate Command on a table which is referenced by Foreign Key?
NO, we can’t use Truncate Command on a table with foreign key
122. Can we use abstract class in web services?

A. Yes we can use.(doubt)
Q.What is static constructor?
Static Constructors
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced. It is declared using the following form:
[attributes] static identifier( ) { constructor-body }
where:

attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see C# Attributes.
identifier
The identifier is the same as the class name.
constructor-body
The block that contains the statements that initialize the class.

Remarks

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Example

In this example, the class MyClass has a static constructor and one static member, MyMethod(). When MyMethod() is called, the static constructor is invoked to initialize the class.

// StaticCtor1.cs
using System;
class MyClass
{
// Static constructor:
static MyClass()
{
Console.WriteLine("The static constructor invoked.");
}

public static void MyMethod()
{
Console.WriteLine("MyMethod invoked.");
}
}

class MainClass
{
static void Main()
{
MyClass.MyMethod ();
}
}

Output

The static constructor invoked.
MyMethod invoked.


Q.What is satellite Assemblies?

A definition from MSDN says something like this: "A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language."

This means that you develop your application in a default language and add flexibility to react with change in the locale. Say, for example, you developed your application in an en-US locale. Now, your application has multilingual support. When you deploy your code in, say, India, you want to show labels, messages shown in the national language which is other than English.

Satellite assemblies give this flexibility. You create any simple text file with translated strings, create resources, and put them into the bin\debug folder. That's it. The next time, your code will read the CurrentCulture property of the current thread and accordingly load the appropriate resource.

This is called the hub and spoke model. It requires that you place resources in specific locations so that they can be located and used easily. If you do not compile and name resources as expected, or if you do not place them in the correct locations, the common language runtime will not be able to locate them. As a result, the runtime uses the default resource set.

How do creating a Satellite Assembly?

1.Create a folder with a specific culture name (for example, en-US) in the application's bin\debug folder.

2.Create a .resx file in that folder. Place all translated strings into it.

3.Create a .resources file by using the following command from the .NET command prompt. (localizationsample is the name of the application namespace. If your application uses a nested namespace structure like MyApp.YourApp.MyName.YourName as the type of namespace, just use the uppermost namespace for creating resources files—MyApp.)

resgen Strings.en-US.resx LocalizationSample.
Strings.en-US.resources
al /embed:LocalizationSample.Strings.en-US.resources
/out:LocalizationSample.resources.dll /c:en-US
The above step will create two files, LocalizationSample.Strings.en-US.resources and LocalizationSample.resources.dll. Here, LocalizationSample is the name space of the application.

4.In the code, find the user's language; for example, en-US. This is culture specific.

5. Give the assembly name as the name of .resx file. In this case, it is Strings.

By definition, satellite assemblies can only contain resources. They cannot contain any executable code. Satellite assemblies are compiled from resource files which can be added to a project from the “add new item” menu.
Q.whatt’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data
type in this case and just write catch {}.
Q.Difference between string and string builder?
String and StringBuilder class stores strings. But when you cannot change a String object after creating one.
eg: String name = "Prasad";
By saying you cannot change the name object means you cannot change the value in name object internally. When you change the name object value to something else, a new String object is creating in memory and assigns the new value.
eg: name = "Prasad Reddy";
A new name object is creating in memory and the value "Prasad Reddy" is assinging to the newly created space.
That is why it is immutable.
But StringBuilder class occupies the same space even if you change the value.
If you are doing string concatenation StringBuilder class is far better in performance than String class.
That is it is mutable string
You can use StringBuilder's Append () method to use concatenation.
Hope you understood.
Q.What is static constructor?
# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-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 non-static data member of a class.
Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.
You may say, why not initialize static data members where we declare them in the code. Like this :
private static int id = 10;
Private static string name = "jack";
Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.
Let me explain you with examples:
In the above example, static data member is declared and initialized in same line. So if you compile and run this program your output would look similar to this:
Test.id = 5
Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member of class Test.id.
//File Name: Test1.cs
Using System;
namespace Constructor
{

class Test1

{

private static int id ;

//Static constructor, value of data member id is set conditionally here.

//This type of initialization is not possible at the time of declaration.

static Test1()

{

if( Test.Id < 10 )

{

id = 20;

}

else

{

id = 100;

}

Console.WriteLine("Static Constructor for Class Test1 Called..");

}

public static void print()

{

Console.WriteLine("Test1.id = " + id);

}

static void Main(string[] args)

{

//Print the value of id

Test1.print();

}

}

}

As you can see in the above static constructor, static data member is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :

Static Constructor for Class Test1 Called..
id = 20

Since in class Test was initialized with a value of 5, therefore in class Test1 got initialized to a value of 20.
Q.What is private constructor?
Private Constructor - When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. It is also used to create Singleton classes. Private Constructors
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. For example:
class NLog
{
// Private Constructor:
private NLog() {}

public static double e = 2.71828;
}
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don't use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Private constructors are useful to prevent creation of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
Example

The following is an example of a class using a private constructor.
// PrivateCtor1.cs
using System;
public class MyClass
{
private MyClass() {}
public static int counter;
public static int IncrementCounter()
{
return ++counter;
}
}

class MainClass
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// MyClass myObject = new MyClass(); // Error
MyClass.counter = 100;
MyClass.IncrementCounter();
Console.WriteLine("New count: {0}", MyClass.counter);
}
}

Output

New count: 101

Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible due to its protection level:

// MyClass myObject = new MyClass(); // error

Q.What is static constructor?
Static Constructors
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced. It is declared using the following form:
[attributes] static identifier( ) { constructor-body }
where:
attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see C# Attributes.
identifier
The identifier is the same as the class name.
Constructor-body
The block that contains the statements that initialize the class.
Remarks
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Example
In this example, the class MyClass has a static constructor and one static member, MyMethod(). When MyMethod() is called, the static constructor is invoked to initialize the class.

// StaticCtor1.cs
using System;
class MyClass
{
// Static constructor:
static MyClass()
{
Console.WriteLine("The static constructor invoked.");
}

public static void MyMethod()
{
Console.WriteLine("MyMethod invoked.");
}
}

class MainClass
{
static void Main()
{
MyClass.MyMethod();
}
}
Output
The static constructor invoked.
MyMethod invoked.
Q.How can you implement an abstract method?
We now have a class called SayHello which is derived from the abstract Talk class. The next step is to implement the abstr act speak() method. When implementing abstract members in a derived class the override modifier must be used. For example:
Using System;

Class Hello
{
Public abstract class Talk
{
public abstract void speak();

}

public class SayHello : Talk
{
public override void speak()
{
Console.WriteLine("Hello!");
}
}

static void Main()
{
SayHello hello = new SayHello();

hello.speak();
}
}
Q.What is the The Difference Between abstract methods and virtual Members?
So far we have only looked at abstract class members. As discussed above an abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile.
Another type of member is a virtual member. A member defined as virtual must be implemented in the base class, but may be optionally overridden in the derived class if different behavior is required. For example, the following example implements a virtual method in the Talk class:
using System;
class Hello`
{
public abstract class Talk
{
public abstract void speak();
public virtual void goodbye()
{
Console.WriteLine("Talk class says goodbye!");
}
}
public class SayHello : Talk
{
public override void speak()
{
Console.WriteLine("Hello!");
}
}
static void Main()
{
SayHello hello = new SayHello();

hello.speak();
hello.goodbye();
}
}
When executed, the goodbye() method in the Talk class will be executed resulting in the following output:
Hello!
Talk Class says goodbye!
If we decide that the default goodbye() method provided by the Talk class is not suitable for the requirements of the SayHello subclass we can simply implements our own version of the method using the override modifier:
using System;
class Hello
{
public abstract class Talk
{
public abstract void speak ();
public virtual void goodbye()
{
Console.WriteLine("Talk class says goodbye!");
}
}

Public class Say Hello: Talk
{
Public override void speak()
{
Console.WriteLine("Hello!");
}

public override void goodbye ()
{
Console.WriteLine ("SayHello Class says goodbye!");
}
}

static void Main()
{
SayHello hello = new SayHello();
hello.speak();
hello.goodbye();
}
}
Q.Difference between abstract members of inerface and abstract classes?
Abstract classes
Defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract.
Optionally, provide default (virtual) member implementation.
Interface
Defines abstract member signatures—all of which—implementing classes must implement. Otherwise, a compiler error results.
All members are virtual and cannot provide implementations.
Q.How can you cache different version of same page using ASP. NET cache object?
Output cache functionality is achieved by using “OutputCache” attribute on ASP. NET page header. Below is the syntax
<%@ Output Cache Duration="20" Location="Server" Vary By Param="state" Vary By Custom="minor version" Vary By Header="Accept-Language"%>
• Vary By Param: - Caches different version depending on input parameters send through HTTP POST/GET.
• Vary By Header: - Caches different version depending on the contents of the page header.
• Vary By Custom: -Lets you customize the way the cache handles page variations by declaring the attribute and overriding the Get Vary By Custom String handler.
• Vary By Control: -Caches different versions of a user control based on the value of properties of ASP objects in the control.
Singleton - Creational Design Pattern:
Intent (Introduction):
There are times, when one needs to have a class which can be only instantiated once. Singleton Design Pattern addresses to such situation by providing a design for such classes (known as Singleton class).
Description:

There are at least two solutions or scenario for implementing Singleton Class. The first solution says that there should be only one shared object and reference to that object should be available only through static method like GetInstance() while making the constructor private. A number of clients can be awarded the reference to such shared object. The second solution says that the constructor should be public (as it appears in most cases) but once an object has been instantiated, an exception should be thrown for each successive constructor call; thus limiting the class to only one objects.
An Example:
First case Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object.
Class Diagram:

Implementation:
Let us first discuss the code of first case Singleton which is like:
class Singleton
{
private static Singleton instance;
private static int numOfReference;
private string code;
private Singleton()
{
numOfReference = 0;
code = "Maasoom Faraz";
}
public static Singleton GetInstance()
{
if(instance == null)
{
instance = new Singleton();
}
numOfReference++;
return instance;
}
public static int Reference
{
get { return numOfReference; }
}
public string Code
{
get { return code; }
set { code = value;}
}
}
There are 3 fields in the Singleton class. Static field instance is a reference to shared object in this Singleton class. Static field numOfReference is an integer variable to hold the number of current references to the single shared object of Singleton class. Code is a string value, it is used to demonstrate that the object is shared b/w references and change made to this field through one reference can be realized through other reference.
The constructor is made private and used to initialize the numOfReference and default value of code. GetInstance() method checks the instance, if it is null then it assign it an instance of Singleton otherwise return the old reference. GetInstance() also increments the numOfReference each time it is called to keep track of current number of reference to our shared instance. Property Reference returns the number of reference referencing our shared object while Code property can be used to set/get the code string of shared object.
The second case Singleton class (Singleton2) looks like:
class Singleton2
{
private static int numOfInstance = 0;
public Singleton2()
{
if(numOfInstance == 0)
{
Console.WriteLine("\r\nCreating First Object of Singleton2 class...");
numOfInstance++;
}
else
{
throw new Exception("This class is Singleton,
+ so only one object of it can be instantiated.");
}
}
}
Here we make the constructor public and use a private field numOfInstance which is incremented for each constructor call. If numOfInstance is zero (no object is yet instantiated), a new object is allowed to made. But, if this value is not zero (there is already an object of Singleton2 class, an exception is thrown.
Now let us try these with Main() method, the code in main is like:
static void Main(string[] args)
{
Singleton obj1 = Singleton.GetInstance();
obj1.Code = "Faraz Rasheed";
Console.WriteLine("No. of references : " + Singleton.Reference);
Console.WriteLine("First Objects code: " + obj1.Code);
Singleton obj2 = Singleton.GetInstance();
Console.WriteLine("No. of references : " + Singleton.Reference);
Console.WriteLine("Second Objects code: " + obj2.Code);
Singleton2 obj3 = new Singleton2();
Singleton2 obj4 = new Singleton2();
}

First we called GetInstance() and took the reference to the new object in obj1. The code for this object is changed to Faraz Rasheed which was Maasoom Faraz by default. Then, we check for number of references to this object and code set for this. Next, we get another reference to this object through GetInstance() in obj2. We again check the number of references and code using this reference. If both the references are pointing to the same shared object, the number of references now should be 2 while the code should also be Faraz Rasheed (remember if obj2 points to a new object then code would have been Maasoom Faraz, the default one) which is shown in the output.
We also made an object of Singleton2. When constructor is called for the first reference (obj3), the new object is instantiated printing the message on Console. But when another instance of Singleton2 is attempted to be made through obj4, an exception is thrown saying Singleton class can only be instantiated once.
Sample output from the program is:
No. of references : 1
First Objects code: Faraz Rasheed
No. of references : 2
Second Objects code: Faraz Rasheed

Creating First Object of Singleton2 class...
Unhandled Exception: System.Exception: This class is Singleton,so only one object of it can be instantiated.
at Singleton.Singleton2..ctor() in c:\documents and settings\msff\my documents\visual studio projects\singleton\class1.cs:line 75
at Singleton.Client.Main(String[] args) in c:\documents and settings\msff\my
documents\visual studio projects\singleton\class1.cs:line 20

Q. How ASP.NET Web Pages are processed on the Web Server?
Step 0: The Browser Makes an HTTP Request for an ASP.NET Web Page
The entire process begins with a Web browser making a request for an ASP.NET Web page. For example, a user might type into their browser's Address window the URL for this article, http://aspnet.4guysfromrolla.com/articles/011404.aspx. The Web browser, then, would make an HTTP request to the 4Guys Web server, asking for the particular file /articles/011404-1.aspx.
Step 1: The Web Server Receives the HTTP Request
The sole task of a Web server is to accept incoming HTTP requests and to return the requested resource in an HTTP response. The 4Guys Web server runs Microsoft's Internet Information Services (IIS) Web server. The first thing IIS does when a request comes in is decide how to handle the request. Its decision is based upon the requested file's extension. For example, if the requested file has the .asp extension, IIS will route the request to be handled by asp.dll.
Step 2: Examining the ASP.NET Engine
An initial request for http://aspnet.4guysfromrolla.com/articles/011404.aspx will reach IIS and then be routed to the ASP.NET engine?(http pipeline), but what happens next? The ASP.NET engine is often referred to as the ASP.NET HTTP pipeline, because the incoming request passes through a variable number of HTTP modules on its way to an HTTP handler.
HTTP modules are classes that have access to the incoming request. These modules can inspect the incoming request and make decisions that affect the internal flow of the request. After passing through the specified HTTP modules, the request reaches an HTTP handler, whose job it is to generate the output that will be sent back to the requesting browser. The following diagram illustrates the pipeline an ASP.NET request flows through.

There are a number of pre-built HTTP modules that are included in the HTTP pipeline by default. These modules include:
• OutputCache, which handles returning and caching the page's HTML output, if needed
• Session, which loads in the session state based on the user's incoming request and the session method specified in the Web.config file
• FormsAuthentication
Step 3: Generating the Output
The final step is for the suitable HTTP handler to generate the appropriate output. This output, then, is passed back through the HTTP modules and then back to IIS, which then sends it back to the client that initiated the request. (If the client was a Web browser, the Web browser would receive this HTML and display it.)
Since the steps for generating the output differ by HTTP handler, let's focus in on one in particular - the HTTP handler that is used to render ASP.NET Web pages. To retrace the initial steps, when a request comes into IIS for an ASP.NET page (i.e., one with a .aspx extension), the request is handed off to the ASP.NET engine. The request then moves through the modules. The request is then routed to the PageHandlerFactory, since in the machine.config's section we have the mapping:

...

...

The PageHandlerFactory class is an HTTP handler factory. It's job is to provide an instance of an HTTP handler that can handle the request. What PageHandlerFactory does is find the compiled class that represents the ASP.NET Web page that is being requested.
Q.What is http handler?
HTTP handlers are the endpoints in the ASP.NET HTTP pipeline. The job of the HTTP handler is to generate the output for the requested resource. For ASP.NET Web pages, this means rendering the Web controls into HTML and returning this HTML. For a Web service, it would involve executing the specified method and wrapping its return values into an appropriately formatted SOAP response. (For more on Web services, be sure to read:
Implementing HTTP Handlers
Now we will see how to implement an HTTP handler. So what should our new handler do? Well, as I stated above, handlers are mostly used for adding new functionalities to Web servers; therefore, we will create a handler that handles new types of files, files that have a .15seconds extension. Once we implement this handler and register it in the web.config file of our Web application, all requests for .15seconds files will be handled by this new handler.
You might be thinking about the use of such a handler. Well, what if you want to introduce a new kind of server scripting language or dynamic server file such as asp, aspx? You can write your own handler for this. Similarly, what will you do if you want to run Java servlets, JSPs and other server side Java components on IIS? One way of doing this is to install some ISAPI extension like Allaire or Macromedia Jrun. Or you can write your own HTTP handler. Although it is a difficult task for third-party vendors like Allaire and Macromedia, it is a very attractive option because their HTTP handlers will have access to all the new functionalities exposed by the ASP.NET runtime.
Steps involved in implementing our HTTP handler are as follows:
1. Write a class which implements IHttpHandler interface
2. Register this handler in web.config or machine.config file.
3. Map the file extension (.15seconds) to ASP.NET ISAPI extension DLL (aspnet_isapi.dll) in Internet Services Manager.
Q.What is http module?
4. HTTP modules are classes that have access to the incoming request. These modules can inspect the incoming request and make decisions that affect the internal flow of the request. After passing through the specified HTTP modules, the request reaches an HTTP handler, whose job it is to generate the output that will be sent back to the requesting browser. The following diagram illustrates the pipeline an ASP.NET request flows through.
HTTP modules are .NET components that implement the System.Web.IHttpModule interface. These components plug themselves into the ASP.NET request processing pipeline by registering themselves for certain events. Whenever those events occur, ASP.NET invokes the interested HTTP modules so that the modules can play with the request.
Once an HTTP module is built and copied into the bin directory of our Web application or copied into the Global Assembly Cache, then we will register it in either the web.config or machine.config file.
We can use and nodes for adding HTTP modules to our Web applications. In fact the modules are listed by using nodes in between and nodes.
Since configuration settings are inheritable, the child directories inherit configuration settings of the parent directory. As a consequence, child directories might inherit some unwanted HTTP modules as part of the parent configuration; therefore, we need a way to remove those unwanted modules. We can use the node for this.
If we want to remove all of the inherited HTTP modules from our application, we can use the node.
The following is a generic example of adding an HTTP module:
Q.What is lambda expression?
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side hold the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
C#
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.
Q.How to upgrade assembly components?
While it is pointed out that the GAC does facilitate side-by-side storage of DLLs based on the assembly’s strong identity (something that did not exist with system32), the author reasons that side-by-side storage isn’t useful because if a new version is available that your app didn’t use, then the update was pointless. Publisher policy is mentioned as a way to force all apps to use the update, and the argument concludes by saying that this ends up in exactly the same place we started with—system32.
A large source of confusion in this topic stems from what publisher policy really is and what it is intended for. There are two very different scenarios for updating an existing assembly:
1) Critical service updates (e.g. security fixes). These are tactical fixes intended to address specific problems with some previously released version of the component. No new features are in the update, and it is expected that the code is highly compatible with the existing version.
2) New feature releases. It may be the case that the new code is mostly compatible with the old version of the assembly, but there are no guarantees.
In case (1), it is clearly desirable to affect all applications on the machine. Because of the critical nature of security fixes, users (and administrators) want to be assured that if they apply a given security fix, that all applications are patched. This is a far better story than trying to hunt down n different applications on the machine that may be using the buggy component, and patching them individually. In the post-slammer-virus world, it should be evident that central servicing for security updates is a critical piece of ensuring machines are protected against malicious code.
In case (2), we recommend that component authors do not ship publisher policy statements which affect all applications. Because the compatibility of the assembly cannot be guaranteed against older versions, consuming the update should be done on an opt-in basis, rather than by default. You can selectively choose to use a new update for a particular application by utilizing application configuration policy.
A publisher policy statement is an XML configuration file wrapped as a separate assembly. There are three reasons that publisher policies are shipped as assemblies. The first is to ensure that the policy statement comes from the author of the assembly that the policy is making the compatibility statement about. This is accomplished by requiring that the policy assembly has a strong name generated with the same key-pair as the original assembly. The second reason is ease of deployment. Publishers or administrators can ship policy statements using the assembly deployment mechanisms provided by the .NET Framework, including the Windows Installer and code download. Using the Windows Installer is particularly convenient because all policy assemblies must be installed in the global assembly cache. Finally, assemblies ship policy statements so that they can be versioned. This allows a publisher to ship a subsequent statement if a previous policy is found not to work in some scenarios. In effect, this allows a publisher to change his mind about the compatibility of his assembly independent of when it was shipped. The flexibility enabled by decoupling the compatibility statements from the code makes it much easier to fix broken applications in the .NET Framework. If multiple versions of a given policy assembly are found in the assembly cache, the .NET Framework will use the policy assembly with the highest version number.
In general, there are two steps required to create a publisher policy assembly:
• 1. Create the XML file containing the compatibility statement. You will have to use an XML editor to create this file.
• 2. Use the Assembly Generation tool (Al.exe) to create an assembly containing the XML file.
The format of the xml file, along with rules about how the elements relate, is described in detail in the .NET Framework SDK Guide. Here is an example file:





publicKeyToken="e9b4c4996039ede8"
culture="en-us"/>

newVersion="2.0.0.0"/>

href="http://www.foo.com/bar.dll"/>




After the xml file is created, use the Assembly Generation tool to create a policy assembly. The following switches to the Assembly Generation tool are required:
1. /link: links the xml file into the assembly.
2. /out: gives the resulting policy assembly a name. Policy assemblies are found in the global assembly cache by naming convention. Therefore, their names must be:
policy...

For example, policy.2.0.myasm
3. /keyfile: The key pair used to give the assembly a strong name (or at least the public key if delay signing is used). As described earlier, this key pair must be the same key pair used to sign the assembly to which this policy statement applies.
4. /version: The version number of the policy assembly.
The following example shows a command line that uses the Assembly Generation tool:
Al /link:publisher.cfg /out:policy.2.0.myasm /keyfile:myasm.snk /version:2.0.0.0
Q.What is internal access modifier?
The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly, as in this example:
Public class BaseClass
{
// Only accessible within the same assembly
internal static int x = 0;
}

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

Example
This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.
// Assembly1.cs
// compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}

// Assembly1_a.cs
// compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // CS0122
}
}

this example, use the same files you used in example 1, and change the accessibility level of BaseClass to public. Also change the accessibility level of the member IntM to internal. In this case, you can instantiate the class, but you cannot access the internal member.
// Assembly2.cs
// compile with: /target:library
public class BaseClass
{
internal static int intM = 0;
}
//

// Assembly2_a.cs
// compile with: /reference:Assembly1.dll
public class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // Ok.
BaseClass.intM = 444; // CS0117
}
}

Q. What is tfs?
It’s a Microsoft product. The server-side component is team foundation server (commonly abbreviated tfs), which comprises two components: the application tier and the data tier. The application tier is a set of web services that provide access to tfs functionality, and a web portal and document repository facilitated by windows sharepoint services, whereas the data tier is essentially a microsoft sql server 2005 standard installation that warehouses all the information for tfs. Both tiers are required, but can be installed on the same or separate servers. Team foundation server contains one or more team projects, which consist of visual studio solutions, configuration files for team build and team load test agents, and a single sharepoint repository containing the pertinent documents for the project.
It can be used as bug tracking tool, we can write test cases using tfs, we can publish the results of test cases in it, and we can use it as a source control repository.
Q.How garbage collector works and how it finds out which object needs to be cleaned?
The process that cleans objects from memory and eliminates
Heap fragmentation is called garbage collection. It is implemented via a CLR service, appropriately called the Garbage Collector (GC).

When an object goes out of scope or all references to it are set to null, that object becomes available for garbage collection. As long as there is an active reference to an object from your program, the GC won’t try to clean that object.Determining which objects are collectable involves a process of creating a graph of live objects and, after all objects have been visited, cleaning up objects that are not in the graph. This graph begins with a set of roots, such as global and static objects.
Q.what is static class? Why you need stataic class?
We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.
Here are some more features of static class
Static classes only contain static members.
Static classes can not be instantiated. They cannot contain Instance Constructors
Static classes are sealed.
Sample:
Public static class MyStaticClass
{
Private static int _staticVariable;
Public static int staticVariable;
{
Get
{
Return _staticVariable;
}
Set
{
_staticVariable = value;
}
}
Public static void Function ()
{
}
}
Q.What is Metadata?
A: Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file. Every type and member defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on.
What does Metadata do?
Metadata describes every type and member defined in your code in a language-neutral manner. Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Q.What is menifest?
Manifest describes assembly itself.Assembly name, culture, version number, strong name, list of all files whereas Metadata describes the content within the assembly.
Assembly Manifest -
An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly's metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.
Assembly Metadata -
Information that describes every element managed by the common language runtime: Assemblies, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime.
Q.What is lambda expression?
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side hold the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:

delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}

Q.Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
Q.What is structure.?
Structures, or structs, are defined with the struct keyword followed by an identifier to name the structure. They are similar to classes, but have subtle differences. Structs are used as lightweight versions of classes that can help reduce memory management efforts when working with small data structures. In most situations, however, using a standard class is a better choice.
The Employee structure below declares a public and a private field. Access to the private field is granted through the public property "Name":
struct Employee
{
private string name;
public int age;

public string Name
{
set { name = value; }
get { return name; }
}
}
Q.Difference between strcture and class?
The principal difference between structs and classes is that instances of structs are values whereas instances of classes are references. Thus when you pass a struct to a function by value you get a copy of the object so changes to it are not reflected in the original because there are now two distinct objects but if you pass an instance of a class by value then there is only one instance.
A struct is a value type. To help understand the struct, it's helpful to make a comparison with classes, as described in Lesson 7: Introduction to Classes and subsequent chapters. While a struct is a value type, a class is a reference type. Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory. If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance. However, if you copy a class, C# creates a new copy of the reference to the object and assigns the copy of the reference to the separate class instance. Structs can't have destructors, but classes can have destructors. Another difference between a struct and class is that a struct can't have implementation inheritance, but a class can, as described in Lesson 8: Class Inheritance. Although a struct can't have implementation inheritance, it can have interface inheritance, as described in Lesson 13: Interfaces, which is the next lesson following this one. Lesson 22: Topics on C# Type, digs deeper into the differences between value and reference types, providing code that demonstrates the concepts that are introduced here.

Q.Difference between strcture and class constructor?
The third significant difference between class objects and struct objects refers to constructors. Constructors are supported by structs in the C# language, and you can define constructors for structs in exactly the same manner as you would for classes. If you are not familiar with constructors, they are methods with the same name as the struct or class ( see figure below). However,the only exception with struct constructors is that you are not permitted to define a constructor that takes no arguments.
Example of a valid constructor
using System;
struct Teacher
{
private string Name;
private string Address;
private string City;
private long Phone;

//Structs' Constructor
public Teacher(string name, string address, string city, string phone)
{
Name = name;
Address = address;
City = city;
Phone = phone;
}
}
An example of a non-valid Constructor
using System;
struct Teacher
{
private string Name;
private string Address;
private string City;
private long Phone;
//Structs\? Constructor is not valid because there are no
//arguments defined. A constructor with no arguments is not permitted!.
public Teacher()
{
Name = "Bob" ;
Address = "50 King St.";
City = "Saint John";
Phone = 643-2333;
}
}
So why is a struct constructor with no arguments not permitted in C#? This is because structs already containa default constructor which has no arguments. Keep in mind that this default constructor is part of the .Net framework, therefore it is not visible in our code. The sole purpose of the default constructor is toassign default values to its members. For example, observe thefollowing code,
using System;
struct Grade
{
int x;
int y;

public ShowValues()
{
Console.WriteLine("x is {0}", x);
Console.WriteLine("y is {0}",y);
}
}

class Test
{
public static void Main()
{
//When we instantiated the struct Grade using the new operator,
//the default constructor will run and assign the values 0 for x
//and 0 for y. This is why the answer will be:
//x is 0
//y is 0
Grade g = new Grade();
g.ShowValues()
}
}
Q.Find the max value in array?
public int getMax(int[] thearray)
{
// Throws NullReferenceException if thearray is null
// Throws IndexOutOfRangeException if thearray is zero length
int max = thearray[0];
for (int i = 1; i != thearray.Length; ++i)
{
if (thearray[i] > max) { max = thearray[i]; }
}
return max;
}
2nd approach
public int FindMax(ArrayList myList)
{
int max = Int32.MinValue;
for (i = 0; i{
int val = (int)myArrayList[i];
if (val > max)
max = val;
}
return max;
}
Q.Find the 2nd highest max value in array?
// populate an array with a few numbers
int[] myArray = new int[4];
myArray[ 0 ] = 20;
myArray[ 1 ] = 45;
myArray[ 2 ] = 23;
myArray[ 3 ] = 62;
Array.Sort( myArray );
Array.Reverse(myArray);
Console.WriteLine( "Second highest value = " + myArray.GetValue( 1 ));
Console.WriteLine( "Third highest value = " + myArray.GetValue( 2 ));
Q.Can we use a return statment in finally block?
No, because it will give complile time error.
Q.What is the output of the fallowing code?

string str1 = "shiva";
string str2 = str1;
str1 = "manoj";

A.str1manojstr2shiva

Q.Will this work in method overloading?
Static int Square(string var)
{
Console.WriteLine("int Square (int var) method called");
return 1;
}
static long Square(ref string var)
{
Console.WriteLine("long Square (long var) method called");
return 1;
}

Ans.Yes

and dis

static int Square(string var)
{
Console.WriteLine("int Square (int var) method called");
return 1;
}
static long Square(out string var)
{
Console.WriteLine("long Square (long var) method called");
return 1;
}
Ans-No...out parameter must be assign be assigned a value

Q.How can u merge 2 datasets data
Merges a specified DataSet, DataTable, or array of DataRow objects into the current DataSet or DataTable.
Sub BindGrid()
Dim myConnection as New SqlConnection (strConn)
Dim DS1 as DataSet
Dim DS1 As DataSet
Dim MyCommand As SqlDataAdapter
MyCommand = new SqlDataAdapter("exec s_get_table1", MyConnection)
DS1 = new DataSet()
MyCommand.Fill(DS1, "MyTable")
MyCommand = new SqlDataAdapter("exec s_get_table2", MyConnection)
DS2 = new DataSet()
MyCommand.Fill(DS2, "MyTable")
'Now this code works because the table name for both datasets is the same. 'Also the data type and column name for both tables are the same. ds1.merge(ds2)
MyDataGrid.DataSource=DS1.tables(0).DefaultView
MyDataGrid.DataBind()
End Sub
PreCondition:
1) All the columns specified in the datagrid must be present in both datasets.
2) The data type of all columns in the datasets must be the same.
3) The column names should match.
4) Table name should be same like the above example
Q.what is basic methods of dataadapter?
There are three most commonly used methods of DataAdapter:
Fill: Executes the SelectCommand to fill the DataSet object with data from the data source. It an also be used to update (refresh) an existing table in a DataSet with changes made to the data in the original datasource if there is a primary key in the table in the DataSet.
FillSchema: Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all the corresponding constraints.
Update: Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated, or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the UpdateBatch method provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table.
Q.What’s difference between System.SystemException and System.ApplicationException?
Answer: The difference between Application Exception and System Exception is that System Exceptions are thrown by the CLR, and Application Exceptions are thrown by Applications.
Q.Dataset Vs Data view?
A. DataView is a view onto an in-memory representation of data held in a DataTable. A DataSet is an in-memory representation of data, containing one or more DataTables.
Dataset is a disjointed (an instance of the actual data from a datasource like SQL Server or Access, by having a dataset you don't need to waste repeated calls back to the original source over the web.

A dataview. Every dataset can have multiple views, just like views with datatables. Dataviews are subsets of a dataset. A dataview could show the same information or less information than the dataset. Every dataset has a dataview and by default if you do not specify, it is dataview (0). When people say they are binding the dataset, they are actually binding dataset.dataview(0).
Q.What are ASHX files? What are HttpHandlers? Where can they be configured?
An .ashx file is an HttpHandler, and inherits from IHttpHandler. Like any file that might be requested, IIS is set up to direct the file to a worker process based on the extension. The HttpHandler has only one method, one property and no events, and eventually every request in the web application goes through it.
Q.What events fire when binding data to a data grid? What are they good for?
Gridview_RowCreated
The RowCreated event is fired when an item in a DataGrid control is created. This means that at the time the event is fired, the DataGrid does not yet know about the data that will be bound to it. So, if the logic of your method depends on this data being available to the control, you’re better off using the RowDataBound event. Other than that, the RowCreated event differentiates itself in one other way from the RowDataBound event: the ItemCreated event is raised when data is bound to the control and during round-trips (postbacks). These qualities make the event especially well-suited to add custom attributes to a DataRow (such as onmouseover or other javascript events) or to control the appearance in ways that do not depend on the data within the DataRow (such as making every 10th row a different color).
gridview_RowDataBound
The ItemDataBound event is fired after after an item in a DataGrid control is bound. This means that (unlike the RowCreated event) you can add special formatting to a DataRow that is dependent upon the data contained within that row. Since RowDataBound is fired after the RowCreated event, it is within this event that you are presented with the final opportunity to access the data before it is rendered to the client. These qualities make the event well-suited for changing the appearance of a row or cell based on the data within that row or cell (such as highlighting outliers or other important information).
gridview_PreRender
gridview_Unload
Q.Explain how PostBacks work, on both the client-side and server-side.?

Q. Which class can be used to perform data type conversion between .NET data types and XML types?
XmlConvert (Correct)
Q.What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Also Response.redirect redirects both the html page as well as the aspx page where as the server.transfer transfers the control only to the aspx pages
Q.What is server.execute and how is different from server.transfer?
Server.Execue is introduced in asp 3.0 and works in ASP.NET also for Th Server.Execute method URL is used as parameter
1) Control moves to the new pageand once the execution is done, control returns to the initial page
2) In the browser the URL is not changed (initial page URL is maintained )
Q.What does NULL mean?
The value NULL is a very tricky subject in the database world, so don't be surprised if several applicants trip up on this question. The value NULL means UNKNOWN; it does not mean '' (empty string). Assuming ANSI_NULLS are on in your SQL Server database, which they are by default, any comparison to the value NULL will yield the value NULL. You cannot compare any value with an UNKNOWN value and logically expect to get an answer. You must use the IS NULL operator instead.
Q.What is the difference between a return parameter and an OUTPUT parameter?
A return parameter is always returned by a stored procedure, and it is meant to indicate the success or failure of the stored procedure. The return parameter is always an INT data type.An OUTPUT parameter is designated specifically by the developer, and it can return other types of data, such as characters and numeric values. (There are some limitations on the data types that can be used as output parameters.)
You can use multiple OUTPUT parameters in a stored procedure, whereas you can only use one return parameter.
Q.How to Disabling Client-Side Validation in validation controls?
If you want to perform only server-side validation and to avoid validation on the client, you can specify for certain ASP.NET Server controls not to not run client-side script validation. To disable client-side validation, set the validation control's EnableClientScript property to false.

Q.How to Disable both Client-Side and Server-Side Validation
You can specify that individual controls on a Web Forms page cause a postback without triggering a check.
If you want to bypass validation for a specific ASP.NET Server control, you’ll have to set the control's CausesValidation property to false. Consider the ASP.NET code example below, showing how to disable validation for a Cancel button:

There is another way to disable a validation control, and you can accomplish it by setting the Enabled ASP.NET validation control property to false. Note that if you set Enabled to false, the ASP.NET validation control will not be rendered to the ASP.NET page at all:

Q.What is all Common properties in all validation controls?
ControlToValidate - This value is which control the validator is applied to.
ErrorMessage - This is the error message that will be displayed in the validation summary.
IsValid - Boolean value for whether or not the control is valid.
Validate - Method to validate the input control and update the IsValid property.
Display - This controls how the error message is shown. Here are the possible options:
None (The validation message is never displayed.)
Static (Space for the validation message is allocated in the page layout.)
Dynamic (Space for the validation message is dynamically added to the page if validation fails.)
Q.In validation controls is it always perform client side vaidation or server side validation?
Nice thing about these Validation controls is that it will preform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will preform server-side where necessary. This client-side/server-side detection and validation is done without extra work by the developer!
Q.What is a static class?
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.
Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. For more information, see Static Constructors .
Q.When to use static classes.?
Each member of an object can be classified in one of two ways: instance member or staticmember. When a copy of an object is created, it is considered instantiated. At that pointthe object exists as a sole entity, with its own set of attributes and behavior. If a second
instance of that object were created, it would normally have a separate set of data from
that of the first object instance. In C#, object members belong to the instance, unless
modified as static. An example of instance objects is a Customer class, where every
customer has different information.
If you use the static modifier with an object member, only a single copy of that member
can exist at any given time, regardless of how many object instances there are. Static
Fields 165members are useful for controlling access to static fields (object state). We can look at the.NET Framework Class Library (FCL) for good examples of when to use static methods,
such as the System.Math class, the System.IO.Path class, and the System.IO.Directory
class. Each of these classes has static members that operate on the input and return a
value. Because these methods don’t depend on any object state, making them static isconvenient and avoids the overhead of creating an instance.
Q.What is static members?
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.
Static class members are declared using the static keyword before the return type of the member, for example:
public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event Event Type RunOutOfGas;
//other non-static fields and properties...
}
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:
Automobile.Drive();
int i = Automobile. NumberOfWheels;

Q.Why in asp.net we keep our connection string in web.config file rather then in abblication or session objects?
In ASP.NET there are several options for storing connection strings. These include the Web.config file, Application variables, custom text files, and hardcoded into pages or components. In Classic ASP, it was common practice to use the Application object to store the connection string information for an application, so it was common to find code like this in the global.asax file:
Sub Application_OnStart
Application("Conn1_ConnectionString") = _
"Provider=SQLOLEDB.1;UID=sa;PWD=p;Initial Catalog=src;Data Source=localhost;"
End Sub

This was the "best practice" approach for many websites. Another option that some sites, such as ASPAlliance.com, used was to have these settings in a common text file that was then called with Server.Execute, such as this:
Sub Application_OnStart
Server.Execute "/db/config.asp"
End Sub
Although this worked wonderfully well in ASP, there is one thing new about ASP.NET that makes using the Application (or Session) object for storing database connection information unwise: Tracing. In a typical ASP application, it was fairly rare to find a page that would dump out the contents of the Application collection. If such a page existed, usually only the developer of the site knew about it. So having sensitive information in the Application object wasn't terribly insecure, as long as you were careful not to give the users any easy way to get a look at this collection of values. However, in ASP.NET, a trace dump will always show the contents of the Application collection. And anybody who knows anything about ASP.NET will know how to hit the Trace.axd file to see recent Trace dumps. Now, you say, "But you can configure tracing in the Web.config file, and I'll just turn it off there and be secure." Certainly, you should do that. However, don't forget that individual pages can have tracing enabled as well, and there is no global way to turn this off. And this is a GREAT debugging tool, so it's probably going to be used quite a bit by developers. That said, how long do you think it will be before a page slips by and is published with tracing still turned on? As soon as it does, your connection information will be publicized to the world if it is stored in your Application (or Session) object. I strongly believe that this will happen with relative frequency, and that for this reason alone it is a BAD IDEA to store sensitive data in the Application (or Session) object in ASP.NET.
Ok, so where DO I store this stuff?
Well, let's look at the most common situation -- the single web site. If you're building a single web site, and it has a single database supporting it, then your best bet is to follow the examples in place at IBuySpy.com and store your connection information in your Web.config file. It is then very easy to retrieve this information from any of your ASP.NET pages, using the following syntax:
'VB
Dim connstring as string
connstring = ConfigurationSettings.AppSettings("ConnectionString")

//C#
string connstring = ConfigurationSettings.AppSettings["ConnectionString"];

To add support for this to your Web.Config, you need to add an AppSettings section, like this one:



Q. when to use abstract class and when to use interface?
In Interfate you are restricting a user to implement each and every method of interface so if you have a requirement which is constantly changing so don't prefere interface.While in Abstract Class user don't need to implement each and every method which is not required or marked with mustoverrideAnd by using interface you can achive multiple inheritance in C# but with Abstact class it's can't be achive
Q.What is the magic tables in sqlserver?
One of the uses of trigger is to maintain log table
The tables "INSERTED" and "DELETED" are called magic tables of theSQL Server. We cannot see these tables in the data base. But we can access these tables from the "TRIGGER"
When we insert the record into the table, the magic table "INSERTED" will be created
In that table the current inserted row will be available. We can access this
record in the "TRIGGER".
Following code Explains the magic table "INSERTED"
CREATE TRIGGER LogMessage
ON EMP
FOR INSERT
AS
DECLARE @EMPNAME varchar(50) SELECT @EMPNAME= (SELECT EMPNAME FROM INSERTED) INSERT INTO LOGTABLE(UserId,Message) values (@EMPNAME,'Record Added')GO
When we delete the record from the table, the magic table "DELETED" will be created
In that table the current deleted row will be available. We can access this
record in the "TRIGGER".
Following code Explain the magic table "DELETED"
CREATE TRIGGER LogMessageON EMP FOR DELETE AS DECLARE @EMPNAME varchar(50) SELECT @EMPNAME= (SELECT EMPNAME FROM DELETED) INSERT INTO LOGTABLE(UserId,Message) values (@EMPNAME,'Record Removed')GO
The magic tables "INSERTED" and "DELETED" are main concept of the "TRIGGER".
By using these tables we can do lot of useful functionalities. The above code is
used to update the "LOGTABLE". Likewise we can maintain stock..
Q.Say you are using instead of trigger and now how can u insert the query which in action in action query in the instead of trigger.
A.Ya using magic tables.
Q.How does the garbage collector know if the application is using an object or not?
When an object goes out of scope or all references to it are set to null, that object becomes available for garbage collection. As long as there is an active reference to an object from your program, the GC won’t try to clean that object.
Determining which objects are collectable involves a process of creating a graph of live objects and, after all objects has been visited, cleaning up objects that are not in the graph. This graph begins with a set of roots, such as global and static objects. Following each object reference from each root and adding each referenced object creates the graph.
Q.Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Q.Can a child class calls the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}
Q.If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.
Q.Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the Load Library method.
Q.What is clr architecture and how it creates an assembly?
In the .NET Framework, a programmer writes in a high-level language that implements a class defining its structure (for example, the fields or properties of the class) and methods. Some of these methods can be static functions. The compilation of the program produces a file called an assembly that contains the compiled code in the Microsoft intermediate language (MSIL), and a manifest that contains all references to dependent assemblies.
Note: Assemblies are a vital element in the architecture of the CLR. They are the units of packaging, deployment, and versioning of application code in the .NET Framework. Using assemblies, you can deploy application code inside the database and provide a uniform way to administer, back up, and restore complete database applications.
The assembly manifest contains metadata about the assembly, describing all of the structures, fields, properties, classes, inheritance relationships, functions, and methods defined in the program. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies.
The .NET Framework supports custom attributes for annotating classes, properties, functions, and methods with additional information the application may capture in metadata. All .NET Framework compilers consume these annotations without interpretation and store them as assembly metadata. These annotations can be examined in the same way as any other metadata.
Managed code is MSIL executed in the CLR, rather than directly by the operating system. Managed code applications acquire CLR services, such as automatic garbage collection, run-time type checking, and security support. These services help provide uniform platform- and language-independent behavior of managed code applications.
MSIL
The source code of the .NET languages is not converted into the native code. Rather, it is compiled into a machine-independent intermediate code known as Microsoft Intermediate Language or the MSIL.
The JIT compiler
The MSIL code and metadata are loaded into the memory with the help of Common Language Runtime (CLR). The JIT compiler then compiles the MSIL code to native code and executes it at runtime. The JIT does not convert the entire MSIL code to its native equivalent. Rather, it does so in demands, i.e., the portion of the current execution code is converted and loaded into the memory. Hence, it works the same way that Demand Paging works in Virtual Memory supporting
Q.Is the following code legal?
Try
{
Response.Write ("Try block executed");
}
Finally
{
Response.Write ("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
Q.Can we inherit static classes?
No, because they are sealed internally.
Q. Can we Retrieving Multiple Result Sets using datareader?
Retrieving Multiple Result Sets using NextResult
If multiple result sets are returned, the Data Reader provides the NextResult method to iterate through the result sets in order. The following example shows the SqlDataReader processing the results of two SELECT statements using the ExecuteReader method.
Static void RetrieveMultipleResults (SqlConnection connection)
{
Using (connection)
{
SqlCommand command = new SqlCommand (
"SELECT CategoryID, CategoryName FROM dbo.Categories;" +
"SELECT EmployeeID, LastName FROM dbo.Employees",
Connection);
connection.Open ();
SqlDataReader reader = command.ExecuteReader ();
While (reader.HasRows)
{
Console.WriteLine ("\t{0}\t{1}", reader.GetName(0),
reader.GetName (1));

while (reader.Read ())
{
Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
reader.GetString (1));
}
reader.NextResult ();
}
}
}
Q. So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll?

A.Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.

Q.What is Hybrid Dictionary?
Implements IDictionary by using a ListDictionary while the collection is small i.e. for 10 or less, and then switching to a Hashtable when the collection gets large.
This class is recommended for cases where the number of elements in a dictionary is unknown. It takes advantage of the improved performance of a ListDictionary with small collections i.e. up to ten , and offers the flexibility of switching to a Hashtable which handles larger collections better than ListDictionary.
If the initial size of the collection is greater than the optimal size for a ListDictionary, the collection is stored in a Hashtable to avoid the overhead of copying elements from the ListDictionary to a Hashtable.
Need to use system. Collection namespace while implimenting this.
HybridDictionary myCol = new HybridDictionary ();
myCol.Add (“Braeburn Apples", "1.49" );

myCol.Add (“Fuji Apples", "1.29" );

Q.Find duplicates values in arraylist and array?
I have to sort the ArrayList first and then i have compare ontacts[ i ] with contacts[ i-1 ]

contacts.Sort();

for (int i=1; i <= contacts.Count-1; i++)
{
Console.WriteLine(contacts[ i ]);
Console.WriteLine(contacts[ i-1] );
if(contacts[ i ].ToString() == contacts[ i-1 ].ToString())
{
Console.WriteLine("Duplicate: "+contacts[ i ]);
}
}

Q.How to protect dll from dissembling it?
Q.What is the difference RegisterClientScriptBlock and RegisterStartupScript?
I will try to explain the difference between RegisterClientScriptBlock and RegisterStartupScript. I have experienced the difference while I was doing some stuffs yesterday. Here is what I was doing. I had a hidden field called txtHiddenField, an update button and some tabs in my page. I also have a javascript function called DisplayTab.

function DisplayTab(tabId)
{
var hdnView = document.getElementById("My hidden field's dotnet generated Id);
hdnView.value = tabId;
document.forms(0).submit();
}
When I click on those tabs I am calling the DisplayTab function with a tabid. It will work fine. ie there will not be any problem in finding the Hidden field using document.getElementById("My hidden field's dotnet generated Id);.

In my Update button click i have

ClientScript. RegisterClientScriptBlock (this.GetType(), "script", "");
This time when it reaches the DisplayTab , it wont be able to find the hidden field . The hdnView variable will be having null. Change the RegisterClientScriptBlock to RegisterStartupScript. This time it works fine. How is this possible? There is only a slight difference between the two methods.

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's
element. The code cannot access any of the form's elements because, at that time, the elements haven't been instantiated yet. This explains why hdnView variable had a null value in my case. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's element. The code can access any of the form's elements because, at that time, the elements have been instantiated. The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

Q. How to call server side method from JavaScript?
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.

[WebMethod]
Public static bool IsTicketAvailable(int NoOfTickets)
{
int AvailableTickets = 5;
return (NoOfTickets > AvailableTickets);
}

Include System.Web.Services namespace for the above code to work.

To call the above method from JavaScript,






No Of Tickets:





Q.How to call JavaScript function from code behind?
Calling a JavaScript function from codebehind is quiet simple, yet it confuses a lot of developers. Here's how to do it. Declare a JavaScript function in your code as shown below:

JavaScript



Call JavaScript From CodeBehind






In order to call it from code behind, use the following code in your Page_Load

C#

if (!ClientScript.IsStartupScriptRegistered("alert"))

{

Page.ClientScript.RegisterStartupScript

(this.GetType(), "alert", "alertMe();", true);

}
Q.What is coalition in sql server?
Q.Where to use static classes and single ton classes?
A. If your class doesn't store any state, and then use a Static class.
If it stores state and you require a single instance, then (maybe) use a Singleton.
Otherwise use a regular class.
Q.What is difference between select count (*), select (column name)?

COUNT(ColumnName)==> Returns the count of rows in a table by eliminating NULL values;

COUNT(*) ==>returns the cardinality (total number of rows) for an entire table.

The fact that COUNT(*) and COUNT(column) treat NULLs differently can be used to your advantage in many situations such as calculating the NULL Rows.

Q.What is the difference abstract classes and sealed classes?
I have understood from my readings that Abstract class can't be instantiated but can be derived by other classes. On the other hand, a sealed class can be instantiated but not be derived by another class (means a sealed class can't be a base class at all).

Q.What is the difference abstract classes and virtual classes?

A.
The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.
- The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

Abstract classes have the following features:
- An abstract class cannot be instantiated.
- An abstract class may contain abstract methods and accessors.
- It is not possible to modify an abstract class with the sealed (C# Reference) modifier, which means that the class cannot be inherited.
- A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

in general, virtual does not work on classes.
it is only for a class method, property, indexer or event declaration to have the possibility, to override them in a derived class.
an abstract class can't be initiated and can more interpretated as a template of a class, which has to be derived to create an instance of it


example
***** Abstract Class *****/
public abstract class Car
{
public int NumberOfWheels = 4;

// Abstract method - MUST be overridden!
public abstract string Honk();
}

public class Peterbilt : Car
{
public Peterbilt()
{
this.NumberOfWheels =18;
}
public override string Honk()
{
return "HOOOOONK";
}
}
public class Chevrolet : Car
{
public override string Honk()
{
return "BEEP!";
}
}


/***** Virtual Method Class *****/
public class Person
{
public Person(string name)
{
_Name = name;
}
private string _Name;

// Virtual method - does not have to be overridden
public virtual string GetInfo()
{
return "Name: " + _Name;
}
}
public class Employee : Person
{
private string _EmployeeID;
public Employee(string name, string employeeID)
:base(name)
{
_EmployeeID = employeeID;
}

public override string GetInfo()
{
return base.GetInfo() + "\nEmployee ID: " + _EmployeeID ;
}
}


/***** Test Class *****/
public class TestClass
{

public void Test()
{
//Car c = new Car(); // Cannot create an instance of an abstract class
Car c = new Chevrolet();
c.Honk();

Person p1 = new Person("Jane Doe"); // perfetctly legal
Employee p2 = new Employee("John Smith", "12345");
Person p3 = p2 as Person; // downcast to Person

string s1 = p1.GetInfo(); // returns Jane Doe
string s2 = p2.GetInfo(); // returns name and ID
string s3 = p3.GetInfo(); // returns name and ID!
}
}


Q. Events in ASP.NET Master and Content Pages
Events in ASP.NET Master and Content Pages
Both master pages and content pages can contain event handlers for controls. For controls, events are handled locally—a control in a content page raises an event in the content page, and a control in the master page raises an event in the master page. Controls events are not sent from the content page to the master page. Similarly, you cannot handle an event from a master page control in a content page.
In some cases, the same event is raised in both the content and the master page. For example, both pages raise Init and Load events. The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one. It is helpful to remember that the master page is merged into the content page and treated as a control in the content page.

The following is the sequence in which events occur when a master page is merged with a content page:


1. Content page PreInit event.
2. Master page controls Init event.
3. Content controls Init event.
4. Master page Init event.
5. Content page Init event.
6. Content page Load event.
7. Master page Load event.
8. Master page controls Load event.
9. Content page controls Load event.
10. Content page PreRender event.
11. Master page PreRender event.
12. Master page controls PreRender event.
13. Content page controls PreRender event.
14. Master page controls Unload event.
15. Content page controls Unload event.
16. Master page Unload event.
17. Content page Unload event.

Q.Can we inherit a class if it contains a private constructor?
A.will raise an error : 'Constructors.MyClass.MyClass()' is inaccessible due to its protection level
It is possible to have the class with only the private constructors. But yes as I said, such class can neither be instantiated nor be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also recall, once you provide constructor from your side the compiler will not add the no-parameter public constructor to your class.Well, one of the usage scenarios of such class could be � when you have only static members in the class and you don't need to instantiate it.
Q.What is indexed view?
With SQL Server 2000, the functionality of SQL Server views was expanded to provide system performance benefits. It is possible to create a unique clustered index on a view, as well as no clustered indexes, to improve data access performance on the most complex queries. In SQL Server 2000 and 2005, a view that has a unique clustered index is referred to as an indexed view.
Q.What is a partial class and where can we use that?
A. Partial types, introduced in C# 2.0, allow you to divide the definition of a single type into multiple parts. Although the parts can be in the same file, they are typically used to divide an object definition among multiple files. The primary purpose of partial types is tool. support in separating machine-generated code from the code you work with. For example,
VS2008 ASP.NET and Windows Forms project and item wizards create skeleton classes divided into two files. This reduces the amount of code you have to work with directly because your code is in one file and the machine-generated code is in another.

The syntax identifying a partial type includes a class (or struct) definition with the partial
modifier. At compile time, C# identifies all classes defined with the same name that have
partial modifiers and compiles them into a single type. The following code shows the
syntax of partial types:
using System;
partial class Program
{
static void Main()
{
m_someVar = 5;
}
}


Q.What is indexers and how to implement?
A.

Using indexers we can maintain array of objects.

Indexers let you build objects that can be used like arrays.
A useful comparison is to view their implementation as a cross between an array, property, and method.

Indexers behave like arrays in that they use the square-bracket syntax to access their
members. The .NET collection classes use indexers to accomplish the same goals. Their
elements are accessed by index.
Indexers are implemented like properties because they have get and set accessors, following
the same syntax. Given an index, they obtain and return an appropriate value with a
get accessor. Similarly, they set the value corresponding to the index with the value
passed into the indexer.
Indexers also have a parameter list, just like methods. The parameter list is delimited by
brackets. Normally, parameter types are commonly int, so a class can provide array-like
operations, but other useful parameter types are string or a custom enum. Here’s an
example:

const int MinLinksSize = 10;
const int MaxLinksSize = 10;
string[] m_links = new string[MaxLinksSize];

public string this[int i]
{
get
{
if (i >= MinLinksSize && i < MaxLinksSize)
{
return m_links[i];
}
return null;
}
set
{
if (i >= MinLinksSize && i < MaxLinksSize)
{
m_links[i] = value;
}
}
}
// code in another class
static void Main()
{
WebSite site = new WebSite();
site[0] = “http://www.mysite.com”;
string link = site[0];
}
Q.In .net can we create web application without IIS?
A.Yes,because it has its own iis which runs in the form of webserver.exe
Q.Can we create N-ton like singleton?
A.yes,we can.

/
---------------------------Mercer India Private Limited--------------------------
Q who exacted first?
Authentication is the process of determining the authenticity of a user based on the user's credentials. Whenever a user logs on to an application, the user is first authenticated and then authorized.
how to create temp table in sql server?
CREATE TABLE #Yaks (
YakID int,
YakName char(30) )
lifetime of the temp table in sql server ?
Local temporary tables are visible only in the current session... ... Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped using DROP TABLE
Important points about temporary tables:
1. It is almost similar to normal table with very few exceptions.
2. The scope of the temp table is the current connection session. It can be accessed from any where in same connection session.
3. This table is automatically dropped when the connection session is closed.
4. Different connection sessions creating temporary table with same name will create different copies of the temporary table with the same name. Actually internally the table name is appended with a unique number to support many connection sessions creating tables with same name. You can notice how the table name is uniquely maintained by sql server by running this query. select * from information_schema.tables where table name like '%customer%'
5. Foreign key relations cannot be applied to temp tables.
6. Optionally you may drop the table at the end of its use. It is a good practice to drop any temporary table after use. drop table #Customer
When you create a temporary table it will be created in tempdb. At the time of table creation the tempdb is locked and hence there is some overhead involved using this. If there are less than 100 records then using temporary tables is not recommended. In such cases you can use table variables which are stored in memory rather than in database(on disk)

Can I define connection sting in database level ?

Q.How to get return value thought store procedure ?
Q:can I run trigger in query manager ?
Q How do I know if a trigger is enabled?
select * from sysobjects where type = 'tr' and (status & 2048) > 0
Q: How to pass parameter in a programmer means like value type /refrence type etc ?
Q: Differnce between out/Ref parameter?

An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
Q:how many catch block in a try block ? And this is possible?
Single try block can handle multiple catch blocks
Try
{
}
Finally
{
}
Q;what is the namespace of try.catch block ?
using System; I thinks so not 100% sure
Q:Root namespace? using System;
Q:in a abstate class how many abstact method possible ? many
Q:Differnce between web sevices/remoting and abstact class and interface ?
What is autopostback ?
The AutoPostBack property is used to set or return whether or not an automatic post back occurs when the user presses "ENTER" or "TAB" in the TextBox control.
If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.

-------------Mercer India Private Limited----------------------------

------------------------OTS-----------------------------------------

Q: what is ajax and and different ajax comapnent u used?

Q: type of Authentication?

Q: what is caching and different time of caching ?

Caching is a technique of persisting the data in memory for immediate access to requesting program calls. Many in the developer community consider caching as one of the features available to improve performance of Web applications.

ASP.NET provides the flexibility in terms of caching at different levels.
• Output caching, which caches the dynamic response generated by a request.
• Fragment caching, which caches portions of a response generated by a request.
• Data caching, which allows developers to programmatically retain arbitrary data across requests?
Q: Diifernce in datalist/repepter/datagid /gridview? Adnd dataadpter.dataset?

Q: difference Ado/ado .net?

Q:why we use WCF ?

Q @@row count return ----------------------------?

Q What is differ sql server 2000/2005.?
Q: Select all table form database ? select * from sysobjects where xtype=’U’

Q:can multiple inhettace supoort in c# ?
no


Q Give a example of multiple inhettace ?



-END -----------------OTS------



Constructors:
In C#, (like other Objected Oriented languages) constructor is a method having the same name as the class The constructor is called when the object is being created It can have one or more parameters
Partial Class - This concept has been introduced in .NET framework 2.0. They give you the ability to split a single class into more than one source code (.cs or .vb) file. Here's what a partial class looks like when it's split over two files...
What is the difference between HashTable and Arraylist?

Arraylist is a collection of objects(may be of different types).
Arraylist is very much similar to array but it can take values of different datatypes.
If you want to find something in a arraylist you have to go through each value in arraylist, theres no faster way out.

Hashtable is also collection which takes a key corresponding to each values.
If you want to find something in a hashtable you dont have to go through each value in hashtable, instead search for key values and is faster.
What is the difference between ado and ado .net?

.
ADO works with connected Architechture and ADO.net works with Both Connected as well as disconnected.Ado.Net navigate data with XML. ADO Not nevigate.
table lockings is Possible in ADO and Table Lockings is not Possible in ADO.Net




Whats difference between Cache and Application object
In cache object you can specify dependency and in application object you can not.

RE: what is the difference between application state and caching

Application variables exist as long as the application is alive. Whereas the cache has the Property of timeout which allows us to control the duration of the Objects so cached.
Another usefulness in caching is that we can define the way we cache our output since caching can be done in 3 ways -
a) Full Page - defined in page directrive
b) Partial Page - Eg - .ascx control
c) Data / Programatic caching. using the Properties of Cache object such as Cache.Insert .
Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.

Whats new in C# 3.5

The key features that are introduced in C# 3.5 are

° Anonymous Types for LINQ

° Implicitly Typed Local Variables - The var Keyword

° Extension Methods

° Object and Collection Initializers( http://stackoverflow.com/questions/137688/c-3-new-feature-posts-and-not-about-net-3-5-features)

° Lambda Expressions

Source : csharpthegreat http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx


T is Global.asax file not Global.ascx

The Global.asx file is an optional file that contains code for responding to application level events raised by ASP.NET. This file is also called as ASP.NET application file. This file resides in the root directory of an application. If we are not defining this file in application, the ASP.NET page framework assumes that you have not defined any applicationa/Session events in the application.

Followign are the list of events handled in the global.asax file.

Event: Application_Start

When an application starts. This event occurs only one time in an application’s life cycle. It occurs again when you restart the application. It’s the best place to count number of visitors.

Event: Application_End

This event occurs when application ends.

Event: Session_Start

This event occurs whenever a new session starts. This is the best place to count user sessions for an application

Practical Usage: Setting user specific values, caching items based upon user context.

Event: Session_End

This event Opposite of the previous event.

Event: Application_Error

This event occurs when an unhandled error or exception occurs in an application.

Event: Application_BeginRequest

This event occurs every time when server makes a request. This event may occur multiple times in an applications life cycle.

Event: Application_End

This event occurs when an application closes


• An application is an IIS term, but it's one that ASP.NET utilizes. Essentially it creates a sandbox, or a set of boundaries to separate different sites, or parts of sites, from the others.
• An AppDomain is a .NET term. (In IIS7, AppDomains play a larger role within IIS, but for the most part it's an ASP.NET term)
• An AppDomain contains InProc session state (the default session state mode). So if an AppDomain is killed/recycled, all of your session state information will be lost. (if you are using the default InProc session state)
• Applications can have multiple AppDomains in them although often times there is a one-to-one relationship between them.
• In IIS6 and greater, there is the option of creating groups, or "pools" of applications that can be bundled together or separated; however the server administer decides. These are called Application Pools. Each app pool runs under its own w3wp.exe worker process.
• In IIS, it's easy to see an application. A new website is a separate application and any subfolder can be marked as an application. When they are, the icon beside the folder turnes into a picture of some gears. By right-clicking on the folder, you have the option of marking a folder as an application or removing it as an application, if it already is one. Also, in IIS6, in the Application Pools section, you can see all of the applications and which app pool they live under.
• ASP.NET, on the other hand, doesn't give much visibility into AppDomains, at least not from any visual tools. This is done behind the scenes. Programmatically you can create them, tear them down or see a list of all running AppDomains.
• You can recycle an application from IIS. In IIS5, you can't do it directly unless you recycle the entire web server, but in IIS6 and greater, you can recycle the application pool that the application lives under. It will gracefully die off and a new application will start up to replace it. Or, to word it another way, another w3wp.exe worker process will be started and then the old one will die off after it completes any currently running page requests.
• You can recycle an AppDomain in ASP.NET through the 'touch trick'. There are a few ways to do it, but the most straight forward is to edit your web.config file in notepad and add a space to an insignificant place. Then save the file. This will cause the AppDomain to recycle. This *does not* touch the IIS application though.
• Recycling an AppDomain will come pretty close to starting ASP.NET fresh again for that particular ASP.NET application, so although it doesn't recycle the apppool, it can give ASP.NET a fresh start in many situations.
Covering Indexes
The term covering index does not mean a separate kind of index having a different internal structure. Rather, this term is used to describe a certain technique that is used to improve performance. It is discussed here because, as will be shown later, for most practical purposes, a clustering index can be thought of as a covering index.
Let's consider a simple but typical example. Suppose that we need to join two tables—Master, defined as (MasterId int primary key, Data int), and Detail, defined as (DetailId int primary key, Data int, MasterId int)—and select columns (MasterID, Detail.Data) where Master.Data satisfies a certain condition. The condition can be anything that is built directly on the value of Master.Data—for example, Data = @data, Data between @start and @end, or Data in (1, 2, 3). Let's also assume that, besides primary key indexes, the Master table has an index idxMaster built on (Data, MasterID), and the Detail table has an index idxDetail built on (MasterID). The query plan will look as shown in Figure 3.

Difference between a.Equals(b) and a == b
Both .Equals and == are used for comparison.

If both a and b are value type then then you will get same result in a.Equals(b) and a == b.
but in case of reference type both behaves differently :
eg.

string a = new string(new char[] {'d', 'a', 'n', 'c', 'e'});
string b = new string(new char[] {'d', 'a', 'n', 'c', 'e'});
object c = a;
object d = b;

Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}

Output will be:

True
True
False
True

Covering Indexes and how they improve performance
A covering index is the term given to a non-clustered index that has been increased to include some extra fields in it that are not used for ordering, but are stored in the index anyway. The idea of setting up a covering index is so that all the fields required in a particular "select" query are "covered" by the index, i.e. all the fields requested in the select are found in the index. You create a covering index by adding certain columns as "included columns" or "non-key columns" in the index. These columns don't affect the order of the records, but do help performance.
To explain how this works and why it is a good thing, consider an index on my "invoice" table. This non-clustered index is composed of the invoice_date. If we wanted to perform this query:
select date, invoice_id, customer_id from invoice order by date
then this index would be a good one to choose. However, when SQL Server executes this query, it must do the following:
1. Use this index to go through the records in the table in date order.
2. For each record, retrieve the date from this index.
3. Due to the rule stated above, the invoice_id will also be found in this index, because invoice_id is the primary index on this table.
4. Use the invoice_id to lookup the actual invoice record and find the customer_id for the invoice.
You can see that this covering index will be faster for this particular query.

Union :- select all distinct record from tables with null
Union all : select all records
SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
________________________________________
CREATE INDEX Example
The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table:
CREATE INDEX PIndex
ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX PIndex
ON Persons (LastName, FirstName)

DROP INDEX Syntax for MS SQL Server:
DROP INDEX table_name.index_name

How to use Rank () in sql server?
select * from Student
Sree 23
Sajid 40
Georg 6
Mary 11
Sam 17
Jafar 6
Babu 38
Larry 5
Malu 29
Nisha 49
Biju 23

SELECT RANK() OVER (ORDER BY Mark DESC) AS [Rank],
FirstName,
Mark
FROM student

1 Nisha 49
2 Sajid 40
3 Babu 38
4 Malu 29
5 Biju 23
5 Sree 23
7 Sam 17
8 Mary 11
9 Gge 6
9 Jafar 6
11 Larry 5

How to use rowid in sql server ?
Select Row_Number() OVER(order by Mark) as rowID FROM student.

Stored Procedures Optimization Tips
1. Call stored procedure using its fully qualified name
2. Don't use the prefix "sp_" in the stored procedure name if you need to create a stored procedure to run in a database other than the master database.
3. Use the sp_executesql stored procedure instead of the EXECUTE statement
4. Try to avoid using temporary tables inside your stored procedure.
5. Try to avoid using DDL (Data Definition Language) statements inside your stored procedure.
6.Use SQL Server Profiler to determine which stored procedures has been recompiled too often.
Difference between Stored Procedure and Function ?

Functions can be called from procedure where as procedures cannot be called from function.
2> Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.
3> Function must return one and only one value where as Procedure can return any n).
4> Function can only have input number of values (0 to parameters only where as Procedure can have input as well as output parameters.
5> Function can have only select statement in it where as a Procedure can have select as well as DML statement in it.
6> Procedure can use try-catch block to handle exception where as try-catch block cannot be used in a function.
7> Function can be used in a assignment operation where as Procedure can not be part of assignment operation.

What is the diff between virtual class and abstract class?



http://mail.dotoo.com/Services/svcUserAdmin.asmx








difference between master page and user control
Master Page:

ASP.NET master pages allow you to create a consistent layout for
the pages in your application. A single master page defines the
look and feel and standard behavior that you want for all of the
pages (or a group of pages) in your application. You can then
create individual content pages that contain the content you want
to display. When users request the content pages, they merge with
the master page to produce output that combines the layout of the
master page with the content from the content page.

User Controls:
An ASP.NET user control is a group of one or more server controls
or static HTML elements that encapsulate a piece of functionality.
A user control could simply be an extension of the functionality
of an existing server control(s) (such as an image control that
can be rotated or a calendar control that stores the date in a
text box). Or, it could consist of several elements that work and
interact together to get a job done (such as several controls
grouped together that gather information about a user's previous
work experience).

What are the basic differences between user controls and custom controls?

Now that you have a basic idea of what user controls and custom controls are and how to create them, let's take a quick look at the differences between the two.


Deployment :
--------------------
User control:

Designed for single-application scenarios

Deployed in the source form (.ascx) along with the source code of the application

If the same control needs to be used in more than one application, it introduces redundancy and maintenance problems

Custom control:

Designed so that it can be used by more than one application

Deployed either in the application's Bin directory or in the global assembly cache

Distributed easily and without problems associated with redundancy and maintenance

Creation :
-------------
User control:

Creation is similar to the way Web Forms pages are created; well-suited for rapid application development (RAD)

Custom control:

Writing involves lots of code because there is no designer support

Content :
-------------------
A much better choice when you need static content within a fixed layout, for example, when you make headers and footers

More suited for when an application requires dynamic content to be displayed; can be reused across an application, for example, for a data bound table control with dynamic rows

Design :
-------------
User control:

Writing doesn't require much application designing because they are authored at design time and mostly contain static data

Custom control:

Writing from scratch requires a good understanding of the control's life cycle and the order in which events execute, which is normally taken care of in user controls

User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls:
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
How to declare two dimensional array in c#?

class TestArraysClass
{
static void Main()
{
// Declare a single-dimensional array
int[] array1 = new int[5];

// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };

// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };

// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];

// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

// Declare a jagged array
int[][] jaggedArray = new int[6][];

// Set the values of the first array in the jagged array structure
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
}
}
1)datagrid and gridview both have same functionality to display your data in the form of a table.
Datagrid is used in Windows Application whereas gridview is used in Web Applications.

2)The Repeater control is used to display a repeated list of items that are bound to the control.

3)The DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default.

4)FormView is a data-bound user interface control that renders a single record at a time from its associated data source, optionally providing paging buttons to navigate between records.

5)DetailsView is a data-bound user interface control that renders a single record at a time from its associated data source, optionally providing paging buttons to navigate between records. It is similar to the Form View of an Access database, and is typically used for updating and/or inserting new records. It is often used in a master-details scenario where the selected record of the master control (GridView, for example) determines the DetailsView display record.


PATINDEX (Transact-SQL)
Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.
SELECT ISNULL(au_id, 'XXX-XX-XXX' ) AS ssn
FROM authors

The ISNULL function compares au_id to null. If it is not null, it just returns the value of au_id. If it is null it will return XXX-XX-XXX.



Use case in sql
Select dailydays = case Datepart(dw, getdate())
when '1' then 'Today is Sunday'
when '2' then 'Today is Monday'

When '7' then 'Today is Saturday'
End



Comparing CHARINDEX and PATINDEX
The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify. PATINDEX can use wildcard characters, but CHARINDEX cannot.
These functions take two parameters:
• The pattern whose position you want. With PATINDEX, the pattern is a literal string that can contain wildcard characters. With CHARINDEX, the pattern is a literal string without wildcard characters.
• A string-valued expression, generally a column name, searched for the specified pattern.
For example, find the position at which the pattern arm starts in a certain row of the Title column in the Document table.
USE AdventureWorks;
GO
SELECT CHARINDEX('arm', Title)
FROM Production.Document
WHERE DocumentID = '1';
GO
Here is the result set.
----------------
7

(1 row(s) affected)
If you do not restrict the rows to be searched, the query returns all rows in the table and it reports nonzero values for those rows in which the pattern was found, and zero for all others.
The following example shows using wildcard characters to find the position at which the pattern reflector starts in any row of the Title column in the Document table.
USE AdventureWorks;
GO
SELECT DocumentID, PATINDEX('%reflector%', Title)AS POSITION
FROM Production.Document
WHERE PATINDEX('%reflector%', Title) <> 0;
GO
Here is the result set.
DocumentID POSITION
---------- --------
2 7
3 7

(2 row(s) affected)
If you do not restrict the rows to be searched, the query returns all rows in the table and reports nonzero values for those rows in which the pattern was found.
Web Farm
Web Garden is the web hosting system which comprises of multiple “processes”.
Web Farm is the web hosting system which comprises of multiple “computers”.
After developing our asp.net web application we host it on IIS Server. Now one standalone server is sufficient to process ASP.NET Request and response for small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are running behind the Load Balancer.
Web Garden
All IIS Request process by worker process ( w3wp.exe). By default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden. Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.
Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.
C#
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:
C#
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}

wat is a static class?n diff btw static and abstract class?


Static methods are shared by all instance of the class.It is commoan for all objects.
The static method can call only staic method.
The static method can call through class name.

Abstract class

1. Contatins abstract and concreate method.
2. When you inherit the abstract class you should be implemented all the abstract method, no need to worry about that concreate method.
3. Without create any instacne, you will access that class.

Static constructors have the following properties:
• A static constructor does not take access modifiers or have parameters.
• A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
• A static constructor cannot be called directly.
• The user has no control on when the static constructor is executed in the program.
• A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

• Destructors cannot be defined in structs. They are only used with classes.
• A class can only have one destructor.
• Destructors cannot be inherited or overloaded.
• Destructors cannot be called. They are invoked automatically.
• A destructor does not take modifiers or have parameters.

Property Indexer
Allows methods to be called as though they were public data members. Allows methods on an object to be called as though the object is an array.
Accessed through a simple name. Accessed through an index.
Can be a static or an instance member. Must be an instance member.
A get accessor of a property has no parameters. A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicitvalue parameter. A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

URI is only for identifying the resource.
URL is for locating/ finding resources.URL will contain request to URI i.e URI is a part of URL

Q How to know web services in not working?
Q2 : How to authencation web services ?
How to update view in run time n in sql server ?
why u called dataset as disconnected architecture
According to ADO.net, Dataset is said to be disconnected module and datareader is said to be connected module.
In disconnected module, the whole data is obtained at one strech and the modification is open to the local table. In connected module, Only one row is obtained each time from the database.

ADO and ADO.NET are different in several ways:

• ADO works with connected data. This means that when you access data, such as viewing and updating data, it is real-time, with a connection being used all the time. This is barring, of course, you programming special routines to pull all your data into temporary tables.


How can I make my SQL queries case sensitive?
If you installed SQL Server with the default collation options, you might find that the following queries return the same results:

CREATE TABLE mytable
(
mycolumn VARCHAR(10)
)
GO

SET NOCOUNT ON

INSERT mytable VALUES('Case')
GO

SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'

You can alter your query by forcing collation at the column level:

SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'caSE'

SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'case'

SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'Case'

-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'

The differences between a static member function and non-static member functions are as follows.
 A static member function can access only static member data, static member functions and data and functions outside the class. A non-static member function can access all of the above including the static data member.

 A static member function can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object.

 A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual

 A static member function cannot have access to the 'this' pointer of the class.
The static member functions are not used very frequently in programs. But nevertheless, they become useful whenever we need to have functions which are accessible even when the class is not instantiated.


To secure your webservice better you can go for authentication.
The sample code for Authentication
In Web.Config add your Particular access UserID and password





Create one IsAuth.cs and write the following code

public bool IsAuth(string UserId, string Password)
{
bool bResult = false;
string strPWD = string.Empty;
strPWD = ConfigurationManager.AppSettings[UserId].ToString();
try
{
if (strPWD == Password)
{
bResult = true;
}
return bResult;
}
catch (Exception ex)
{
return bResult;
}
}


In WebMethod

[WebMethod]
public string GetForm(string strFormInfo, string UserId, string Password)
{
try
{
if (!IsAuth(UserId, Password)) //IsAuth method called to verify the Userid and password
{
......
}
catch (Exception ex)
{
}
finally
{
}
}


using System;

interface Interdemo
{
void Show();
}

class Interimp:Interdemo
{
public void Show()
{
Console.WriteLine("Show() method Implemented");
}

public static void Main(string[] args)
{
Interimp inter = new Interimp();
inter.Show();
}
}
Combining Interfaces
Two or more interfaces can be combined into a single interface and implemented in a class, as shown in Listing 2:
using System;
interface Interdemo
{
void Show();
}

Interface Interdemo1
{
void Display();
}

interface Combineinter:Interdemo,Interdemo1
{
//Above interfaces combined
}

class Multipleinterimp:Combineinter
{
public void Show()
{
Console.WriteLine("Show() method Implemented");
}

public void Display()
{
Console.WriteLine("Display() method Implemented");
}

public static void Main(string[] args)
{
Multipleinterimp inter = new Multipleinterimp();
inter.Show();
inter.Display();
}
}
You easily can determine whether a particular interface is implemented in a class by using is and as operators. The is operator enables you to check whether one type or class is compatible with another type or class; it returns a Boolean value. Listing 3 illustrates the usage of the is operator by revisiting Listing 2.
Listing 3
using System;

interface Interdemo
{
bool Show();
}

interface Interdemo1
{
bool Display();
}

class Interimp:Interdemo
{
public bool Show()
{
Console.WriteLine("Show() method Implemented");
return true;
}

public static void Main(string[] args)
{
Interimp inter = new Interimp();
inter.Show();

if(inter is Interdemo1)
{
Interdemo1 id = (Interdemo1)inter;
bool ok = id.Display();
Console.WriteLine("Method Implemented");
}

else
{
Console.WriteLine("Method not implemented");
}
}
}
Whereas the is operator returns a boolean value as shown in the preceding listing, the as operator returns null if there is any incompatibility between types. Listing 4 examines the usage of this operator. Here we have revisited Listing 3. Notice the change in code inside the Main () method.
Listing 4
using System;

interface Interdemo
{
bool Show();
}

interface Interdemo1
{
bool Display();
}

class Interimpas:Interdemo
{
public bool Show()
{
Console.WriteLine("Show() method Implemented");
return true;
}

public static void Main(string[] args)
{
Interimpas inter = new Interimpas();
inter.Show();

Interdemo1 id = inter as Interdemo1;

if(null!=id)
{

bool ok = id.Display();
Console.WriteLine("Method Implemented");
}

else
{
Console.WriteLine("Method not implemented");
}
}
}
Avoiding Name Ambiguity
Suppose you are declaring same method definitions in two different interfaces. The compiler will naturally show an error due to the ambiguity of the implemented method. Even if you use the "is" keyword, the compiler still will show warnings. To avoid this, you have to follow the syntax as shown in Listing 5:
Listing 5
Void .
{
//Body goes here
}
Listing 6 illustrates the application of the preceding concept in detail:
Listing 6
using System;

interface Interdemo
{
void Show();
}

interface Interdemo1
{
void Show();
}


class Interclash:Interdemo,Interdemo1
{
void Interdemo.Show()
{
Console.WriteLine("Show() method Implemented");
}

void Interdemo1.Show()
{
Console.WriteLine("Display() method Implemented");
}

public static void Main(string[] args)
{
Interclash inter = new Interclash();
inter.Interdemo.Show();
inter.Interdemo1.Show();
}
}
Finalize :
1.Finalize() is called by the runtime
2.Is a destructor, called by Garbage Collector when the object goes out of scope.
3.Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.

Dispose :
1.Dispose() is called by the user
2.Same purpose as finalize, to free unmanaged resources. However, implement this when you are writing a custom class, that will be used by other users.
3.Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.
Finalize:- .NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources ( ex: Windows API created objects, File, Database connection objects, COM objects etc) is outside the scope of .NET framework we have to explicitly clean our resources. For these types of objects .NET framework provides Objects. Finalize method which can be overridden and clean up code for unmanaged resources can be put in this section.
Dispose:- Dispose method belongs to IDisposable interface. If you want to release unmanaged objects then it is the best to implement IDisposable and override the Dispose method of IDisposable interface. Now once your class has exposed the Dispose method it's the responsibility of the client to call the Dispose method to do the cleanup.

After trigger automatically get executed before the transaction get completed or rollback. After trigger created only on tables not in views. This is very useful to maintain the data integrity between the tables.
INSTEAD OF Triggers


This trigger gets executed automatically before the primary key and the foreign key column constraint are checked. Whereas the traditional trigger (After Trigger) get executes automatically after all the check constraints are checked.

Page Class in ASP.NET 2.0

All web forms are actually instances of the ASP.NET page class, which is defined in the System.Web.UI namespace. The Page class inherits from the TemplateControl class, which in turn inherits from the Control class. As a result, the Page class provides useful properties and methods that we can use in our code. The sample code snippets have been written in C#.

various objects of the Page class.
Session Application Cache Request HttpRequest Properties Response Server







What is the difference between shadow and override
________________________________________
The best way in my opinion to understand the true meaning of the effects of using the "new" modifier in a virtual hierarchy is to think of it like this... The runtime wants to start at the top of the virtual hierarchy and work towards the bottom (towards the most derived class in the chain)... it says "Is there an override in thederived class directly below me?" If so it goes down one level... and then repeats the same question. If the class directly below the current one has applied the "new" modifier to the that virtual chain that method is "hidden"... so the chain stops at the last method that did not have the "new" modifier applied to it.

This happens because the "new" modifier (when applied to a virtual chain) actually creates a brand new v-table entry... thus physically breaking the chain in the hierarchy.

Take this example:
class A
{
public virtual void CallMethod () { Method(); } protected virtual void Method() { Console.WriteLine("A"); }
}
class B : A
{
protected override void Method() { Console.WriteLine("B"); }
}
class C : B
{
protected new virtual void Method() { Console.WriteLine("C"); }
}
class D : C
{
protected override void Method() { Console.WriteLine("D"); }
}
class Program
{
static void Main(string[] args)
{
C objeckt new D();
objeckt.CallMethod();
}
}

What is printed? The answer is "B". Why?

It prints "B" because we start out by creating an actual instance of D that is "pointed to" or referenced using a C. The CallMethod method is actually on class A so we just up to A and then it tries to call "Method" from the top... down. A is virtual... but is overridden by B. It jumps down to B and since C's Method has the "new" modifier applied to it... it cannot "see" the Method instance on class C... thus it stops at B and calls that method. Wild huh!

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 non-static data member of a class.

Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.

Difference between constant and readonly


Read-only and const both are same they can never be modified. But
read-only allows initializing variables at run time.
const must be initialized to a compile time constant.

Ex:

public readonly DateTime dt = DateTime.Now

public const int i = 2;

14) What is final, finalize () and finally?
Ans: final: final keyword can be used for class, method and variables.
A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods.
A final method can’t be overridden
A final variable can't change from its initialized value.

finalize( ) : finalize( ) method is used just before an object is destroyed and can be called just prior to
garbage collection.
finally : finally, a key word used in exception handling, creates a block of code that will be executed after a
try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown.
For example, if a method opens a file upon exit, then you will not want the code that closes the file
to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this
contingency.