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
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
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
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:
OnClick="btn_CustModel_Click" />
Get name for customer
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