Tuesday, November 4, 2008

ASP.NET Interview Questions – 6

What is Ajax?
The term Ajax was coined by Jesse James Garrett and is a short form for "Asynchronous Javascript and XML". Ajax represents a set of commonly used techniques, like HTML/XHTML, CSS, Document Object Model(DOM), XML/XSLT, Javascript and the XMLHttpRequest object, to create RIA's (Rich Internet Applications).
Ajax gives the user, the ability to dynamically and asynchronously interact with a web server, without using a plug-in or without compromising on the user’s ability to interact with the page. This is possible due to an object found in browsers called the XMLHttpRequest object.

What is ASP.NET AJAX?
‘ASP.NET AJAX’ is a terminology coined by Microsoft for ‘their’ implementation of AJAX, which is a set of extensions to ASP.NET. These components allow you to build rich AJAX enabled web applications, which consists of both server side and client side libraries.
Which is the current version of ASP.NET AJAX Control Toolkit?
As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008).

Explain differences between the page execution lifecycle of an ASP.NET page and an ASP.NET AJAX page?

In an asynchronous model, all the server side events occur, as they do in a synchronous model. The Microsoft AJAX Library also raises client side events. However when the page is rendered, asynchronous postback renders only the contents of the update panel, where as in a synchronous postback, the entire page is recreated and sent back to the browser.

What role does the ScriptManager play?
The ScriptManager manages all ASP.NET AJAX resources on a page and renders the links for the ASP.NET AJAX client libraries, which lets you use AJAX functionality like PageMethods, UpdatePanels etc. It creates the PageRequestManager and Application objects, which are prominent in raising events during the client life cycle of an ASP.NET AJAX Web page. It also helps you create proxies to call web services asynchronously.


Can we use multiple ScriptManager on a page?
No. You can use only one ScriptManager on a page.


What is the role of a ScriptManagerProxy?
A page can contain only one ScriptManager control. If you have a Master-Content page scenario in your application and the MasterPage contains a ScriptManager control, then you can use the ScriptManagerProxy control to add scripts to content pages.
Also, if you come across a scenario where only a few pages in your application need to register to a script or a web service, then its best to remove them from the ScriptManager control and add them to individual pages, by using the ScriptManagerProxy control. That is because if you added the scripts using the ScriptManager on the Master Page, then these items will be downloaded on each page that derives from the MasterPage, even if they are not needed, which would lead to a waste of resources.


What are the requirements to run ASP.NET AJAX applications on a server?
You would need to install ‘ASP.NET AJAX Extensions’ on your server. If you are using the ASP.NET AJAX Control toolkit, then you would also need to add the AjaxControlToolkit.dll in the /Bin folder.
Note: ASP.NET AJAX 1.0 was available as a separate downloadable add-on for ASP.NET 2.0. With ASP.NET 3.5, the AJAX components have been integrated into ASP.NET.


Explain the UpdatePanel?
The UpdatePanel enables you to add AJAX functionality to existing ASP.NET applications. It can be used to update content in a page by using Partial-page rendering. By using Partial-page rendering, you can refresh only a selected part of the page instead of refreshing the whole page with a postback.

How can you cancel an Asynchronous postback?
Yes you can.

Difference between Server-Side AJAX framework and Client-side AJAX framework?
ASP.NET AJAX contains both a server-side Ajax framework and a client-side Ajax framework. The server-side framework provides developers with an easy way to implement Ajax functionality, without having to possess much knowledge of JavaScript. The framework includes server controls and components and the drag and drop functionality. This framework is usually preferred when you need to quickly ajaxify an asp.net application. The disadvantage is that you still need a round trip to the server to perform a client-side action.
The Client-Side Framework allows you to build web applications with rich user-interactivity as that of a desktop application. It contains a set of JavaScript libraries, which is independent from ASP.NET. The library is getting rich in functionality with every new build released.


How can you debug ASP.NET AJAX applications?
Explain about two tools useful for debugging: Fiddler for IE and Firebug for Mozilla.

Can we call Server-Side code (C# or VB.NET code) from javascript?
Yes. You can do so using
PageMethods in ASP.NET AJAX or using webservices.
Can you nest UpdatePanel within each other?
Yes, you can do that. You would want to nest update panels to basically have more control over the Page Refresh.


How can you to add JavaScript to a page when performing an asynchronous postback?
Use the ScriptManager class. This class contains several methods like the RegisterStartupScript(), RegisterClientScriptBlock(), RegisterClientScriptInclude(), RegisterArrayDeclaration(),RegisterClientScriptResource(), RegisterExpandoAttribute(), RegisterOnSubmitStatement() which helps to add javascript while performing an asynchronous postback.

Explain the AJAX Client life-cycle events
Here’s a good article about the same.
Is the ASP.NET AJAX Control Toolkit(AjaxControlToolkit.dll) installed in the Global Assembly Cache?
No. You must copy the AjaxControlToolkit.dll assembly to the /Bin folder in your application.
Those were some frequently asked questions you should have knowledge about


Can I use ASP.NET AJAX with any other technology apart from ASP.NET?

To answer this question, check out this example of using ASP.NET AJAX with PHP, to demonstrate running ASP.NET AJAX outside of ASP.NET. Client-Side ASP.NET AJAX framework can be used with PHP and Coldfusion.

Monday, November 3, 2008

ASP.NET interview questions - 5

1. What are Satellite Assemblies?
Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed.

2. What is Global Assembly Cache (GAC) and what is the purpose of it?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.

3. What is Reflection in .NET?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.

4. What is the managed and unmanaged code in .net?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services

5. What are Namespaces?
The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable.

6. What are the access-specifiers available in c#?
Private, Protected, Public, Internal, Protected Internal.

7. Advantage of ADO.Net?
ADO.NET Does Not Depend On Continuously Live Connections
Database Interactions Are Performed Using Data Commands
Data Can Be Cached in Datasets
Datasets Are Independent of Data Sources
Data Is Persisted as XML
Schemas Define Data Structures

8. Difference between OLEDB Provider and SqlClient ?
SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.

9. Differences between dataset.clone and dataset.copy?
Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints.Does not copy any data
Copy - Copies both the structure and data for this DataSet.

10. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?
WebService will support only DataSet.

11. What is Remoting?
The process of communication between different operating system processes, regardless of whether they are on the same computer. The .NET remoting system is an architecture designed to simplify communication between objects living in different application domains, whether on the same computer or not, and between different contexts, whether in the same application domain or not.

12. What’s the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

13. What’s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

14. What’s an interface class?
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes

15. What is the transport protocol you use to call a Web service
SOAP is the preferred protocol.

ASP.NET interview questions - 4

1. Does C# support multiple inheritance?
No, use interfaces instead

2. What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and its datatype depends on whatever variable we’re changing

3. What’s the top .NET class that everything is derived from?
System.Object.

4. How’s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

5. What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.

6. What is CTS?
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.

7. What is CLS?
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture", http://msdn.microsoft.com/net/ecma

8. What is strong name?
A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

9. What is Application Domain?
The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages.


10. What is serialization in .NET? What are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

MS SQL Interview Questions -1

1. What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

2. Write a SQL Query to find first Week Day of month?
SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay

3. How to find 6th highest salary from Employee table
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee
ORDER BY salary DESC) a ORDER BY salary

4. What is a join and List different types of joins.
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS Joints. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

5. How can I enforce to use particular index?
You can use index hint (index=index_name) after the table name. SELECT au_lname FROM authors (index=aunmind)

6. What is sorting and what is the difference between sorting and clustered indexes?
The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table.

7. What are the differences between UNION and JOINS?
A join selects columns from 2 or more tables. A union selects rows.

8. What is the Referential Integrity?
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value

9. What is the row size in SQL Server 2000?
8060 bytes.

10. How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. eg: Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 3)

11. What is the purpose of UPDATE STATISTICS?
Updates information about the distribution of key values for one or more statistics groups (collections) in the specified table or indexed view.

12. What is the use of SCOPE_IDENTITY() function?
Returns the most recently created identity value for the tables in the current execution scope.

13. What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

14. How do you transfer data from text file to database (other than DTS)?
Using the BCP (Bulk Copy Program) utility.

15. What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can't be rolled back.

16. What is a deadlock?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

17. What is a LiveLock?
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

18. How to restart SQL Server in single user mode?
From Startup Options :- Go to SQL Server Properties by right-clicking on the Server name in the Enterprise manager. Under the 'General' tab, click on 'Startup Parameters'. Enter a value of -m in the Parameter.

19. Does SQL Server 2000 clustering support load balancing?
SQL Server 2000 clustering does not provide load balancing; it provides failover support. To achieve load balancing, you need software that balances the load between clusters, not between servers within a cluster.

20. What is DTC?
The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction manager that allows client applications to include several different sources of data in one transaction. MS DTC coordinates committing the distributed transaction across all the servers enlisted in the transaction.

21. What is DTS?
Microsoft® SQL Server™ 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets you extract, transform, and consolidate data from disparate sources into single or multiple destinations.

22. What are defaults? Is there a column to which a default can't be bound?
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.

23. What are the constraints ?
Table Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity. SQL Server 2000 supports five classes of constraints. NOT NULL , CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY.

24. What is Transaction?
A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction.

25. What is Isolation Level?
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. A lower isolation level increases concurrency, but at the expense of data correctness. Conversely, a higher isolation level ensures that data is correct, but can affect concurrency negatively. The isolation level required by an application determines the locking behavior SQL Server uses. SQL-92 defines the following isolation levels, all of which are supported by SQL Server:

Read uncommitted (the lowest level where transactions are isolated only enough to ensure that physically corrupt data is not read).
Read committed (SQL Server default level).
Repeatable read.
Serializable (the highest level, where transactions are completely isolated from one
another).

SQL Query Fundamentals

The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:
SELECT select_list[INTO new_table_name]FROM table_list[WHERE search_conditions][GROUP BY group_by_list][HAVING search_conditions][ORDER BY order_list [ASC DESC] ]
select_list
Describes the columns of the result set. It is a comma-separated list of expressions. Each expression defines both the format (data type and size) and the source of the data for the result set column. Each select list expression is usually a reference to a column in the source table or view the data is coming from, but can be any other expression, such as a constant or a Transact-SQL function. Using the * expression in a select list specifies that all columns in the source table are returned.
INTO new_table_name
Specifies that the result set is used to create a new table. new_table_name specifies the name of the new table.
FROM table_list
Contains a list of the tables from which the result set data is retrieved. These sources can be:
· Base tables in the local server running Microsoft® SQL Server™.
· Views in the local SQL Server. SQL Server internally resolves a view reference to references against the base tables that make up the view.
· Linked tables, which are tables in OLE DB data sources made accessible to SQL Server. This is called a distributed query. OLE DB data sources can be accessed from SQL Server by linking them as a linked server, or referencing the data source in an OPENROWSET or OPENQUERY function.
The FROM clause can also contain join specifications, which define the specific path SQL Server is to use in navigating from one table to another.
The FROM clause is also used on the DELETE and UPDATE statements to define the tables that are modified.
WHERE search_conditions
The WHERE clause is a filter that defines the conditions each row in the source tables must meet to qualify for the SELECT. Only rows that meet the conditions contribute data to the result set. Data from rows that do not meet the conditions are not used.
The WHERE clause is also used on the DELETE and UPDATE statements to define the rows in the target tables that are modified.

GROUP BY group_by_list
The GROUP BY clause partitions the result set into groups based on the values in the columns of the group_by_list. For example, the Northwind Orders table has three values in ShipVia. A GROUP BY ShipVia clause partitions the result set into three groups, one for each value of ShipVia.

HAVING search_conditions

The HAVING clause is an additional filter that is applied to the result set. Logically, the HAVING clause filters rows from the intermediate result set built from the application of any FROM, WHERE, or GROUP BY clauses in the SELECT statement. HAVING clauses are most commonly used with a GROUP BY clause, although a GROUP BY clause is not required before a HAVING clause.
ORDER BY order_list [ ASC DESC ]

The ORDER BY clause defines the order in which the rows in the result set are sorted. order_list specifies the result set columns that make up the sort list. The ASC and DESC keywords are used to specify if the rows are sorted in an ascending or descending sequence.

ORDER BY is important because relational theory specifies that the rows in a result set cannot be assumed to have any sequence unless ORDER BY is specified. ORDER BY must be used in any SELECT statement for which the order of the result set rows is important.
The clauses in a SELECT statement must be specified in the proper order.
Each reference to a database object must be unambiguous. Ambiguity can come from these sources:


· There may be multiple objects with the same name in a system. For example, both User1 and User2 may have defined a table named TableX. To resolve the ambiguity and specify the TableX owned by User1, qualify the table name with at least the user ID: ·

SELECT * FROM User1.TableX


· The database in which the object resides may not always be the current database when the SELECT statement is executed. To ensure that the proper object is always used, regardless of the current database setting, qualify the object name with the database and owner: ·

SELECT * FROM Northwind.dbo.Shippers

Sunday, November 2, 2008

ASP.NET interview questions - 3

What is different b/w webconfig.xml & Machineconfig.xml?
Web.config & machine.config both are configuration files.Web.config contains settings specific to an application where as machine.config contains settings to a computer. The Configuration system first searches settings in machine.config file & then looks in application configuration files.Web.config, can appear in multiple directories on an ASPNET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. There is only Machine.config file on a web server.
If I'm developing an application that must accomodate multiple security levels though secure login and my ASPNET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config.

You can specify mode as ?stateserver? or ?sqlserver?.
Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one"One of ASPNET's most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASPNET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.

How do you turn off cookies for one page in your site?Since no Page Level directive is present, I am afraid that cant be done.

How do you create a permanent cookie?Permanent cookies are available until a specified expiration date, and are stored on the hard disk.So Set the 'Expires' property any value greater than DataTime.MinValue with respect to the current datetime. If u want the cookie which never expires set its Expires property equal to DateTime.maxValue.

Which method do you use to redirect the user to another page without performing a round trip to the client?Server.Transfer and Server.Execute

What property do you have to set to tell the grid which page to go to when using the Pager object?CurrentPageIndex

Should validation (did the user enter a real date) occur server-side or client-side? Why?It should occur both at client-side and Server side.By using expression validator control with the specified expression ie.. the regular expression provides the facility of only validatating the date specified is in the correct format or not. But for checking the date where it is the real data or not should be done at the server side, by getting the system date ranges and checking the date whether it is in between that range or not.

What does the "EnableViewState" property do? Why would I want it on or off?Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip, then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive.
Response.Dedirect() :client know the physical location (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component?
* Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option. * Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors. * Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically. * Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet. * When not to use Web Services: Single machine Applicatons When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Componets as there is very little overhead. * Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps

Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It's a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.

What are the advantages and disadvantages of viewstate?The primary advantages of the ViewState feature in ASPNET are:
1. Simplicity. There is no need to write possibly complex code to store form data between page submissions.2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to persist the values of some fields but not others.
There are, however a few disadvantages that are worth pointing out:
1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the sessionapproach, values can be stored in the session and accessed from other pages. This is not possible with ViewState, so storingdata into the session must be done explicitly.
2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to the backend using some form of data object.

ASP.NET interview questions - 2

What are the different types of caching?Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASPNET has 3 kinds of caching strategies Output Caching
Fragment Caching
Data Caching

Output Caching: Caches the dynamic output generated by a request. Some times it is useful to cache the output of a website even for a minute, which will result in a better performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching ASPNET provides a cache object for eg: cache["States"] = dsStates;

What do you mean by authentication and authorization?
Authentication is the process of validating a user on the credentials (username and password) and authorization performs after authentication. After Authentication a user will be verified for performing the various tasks, It access is limited it is known as authorization.

What are different types of directives in .NET?
@Page: Defines page-specific attributes used by the ASPNET page parser and compiler. Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %> @Control:Defines control-specific attributes used by the ASPNET page parser and compiler. Can be included only in .ascx files.
<%@ Control Language="VB" EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @ Import Namespace="System.web" %>@Implements: Indicates that the current page or user control implements the specified .NET framework interface.
<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>@Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.
<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %>
<%@ Assembly Src="MySource.vb" %>@OutputCache: Declaratively controls the output caching policies of an ASPNET page or a user control contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any Client Downstream Server None" Shared="True False" VaryByControl="controlname" VaryByCustom="browser customstring" VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared.

How do I debug an ASPNET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASPNET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list,check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASPNET to build debug executables by placing a<%@ Page Debug="true" %> statement at the top of an ASPX file or a statement in a Web.config file.

Can a user browsing my Web site read my Web.config or Global.asax files?No. The section of Machine.config, which holds the master configuration settings for ASPNET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. You can modify it by editing Machine.config or including an section in a local Web.config file.

What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>

Is it necessary to lock application state before accessing it?
Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:Application.Lock ();Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;Application.UnLock (); By locking application state before updating it and unlocking it afterwards, you ensure that another request being processed on another thread doesn't read application state at exactly the wrong time and see an inconsistent view of it. If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state?Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASPNET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event.

Do ASPNET forms authentication cookies provide any protection against replay attacks? Do they, for example, include the client's IP address or anything else that would distinguish the real client from an attacker?
No. If an authentication cookie is stolen, it can be used by an attacker. It's up to you to prevent this from happening by using an encrypted communications channel (HTTPS). Authentication cookies issued as session cookies, do, however,include a time-out valid that limits their lifetime. So a stolen session cookie can only be used in replay attacks as long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes.You can change that by modifying the timeout attribute accompanying the element in Machine.config or a local Web.config file. Persistent authentication cookies do not time-out and therefore are a more serious security threat if stolen.

How do I send e-mail from an ASPNET application?
MailMessage message = new MailMessage ();message.From = ;message.To = ;message.Subject = "Scheduled Power Outage";message.Body = "Our servers will be down tonight.";SmtpMail.SmtpServer = "localhost";SmtpMail.Send (message);
MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's System.Web.Mail namespace. Due to a security change made to ASPNET just before it shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though "localhost" is the default. In addition, you must use the IIS configuration applet to enable localhost (127.0.0.1) to relay messages through the local SMTP service.

What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host directory and any subdirectories not noted in elements:


How does dynamic discovery work?
ASPNET maps the file name extension VSDISCO to an HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.Note that VSDISCO files are disabled in the release version of ASPNET. You can reenable them by uncommenting the line in the section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security.

Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here:
<%@ Page Language="C#" %>
<% Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); %>SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.

What does AspCompat="true" mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components by placing unmanaged wrappers around the equivalent ASPNET objects. Second, it improves the performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually, the thread that processes the request for the page) and the COM objects it creates share an apartment. AspCompat="true" forces ASPNET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment boundaries.Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both.

Explain the differences between Server-side and Client-side code?
Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn't have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.

What type of code (server or client) is found in a Code-Behind class?
C#

Should validation (did the user enter a real date) occur server-side or client-side? Why?Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.

What are ASPNET Web Forms? How is this technology different than what is available though ASP?
Web Forms are the heart and soul of ASPNET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

What is the difference between Server.Transfer and Response.Redirect?
Why would I choose one over the other?In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems.As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

How can you provide an alternating color scheme in a Repeater control?AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties.
Which template must you provide, in order to display data in a Repeater control?ItemTemplate

What event handlers can I include in Global.asax?
Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_EndYou can optionally include "On" in any of method names. For example, you can name a BeginRequest event handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web Services (they're designed for ASPNET applications in general, whereas .NET XML Web Services are specialized instances of an ASPNET app). For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASPNET Forms authentication.

ASP.NET interview questions - 1

What is view state and use of it?The current property settings of an ASPNET page and those of any ASPNET server controls contained within the page. ASPNET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.

What are user controls and custom controls?Custom controls:A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASPNET pages). A custom client control is used in Windows Forms applications.
User Controls:In ASPNET: A user-authored server control that enables an ASPNET page to be re-used as a server control. An ASPNET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASPNET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.


What are the validation controls?A set of server controls included with ASPNET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script.

What's the difference between Response.Write() andResponse.Output.Write()?The latter one allows you to write formattedoutput.


What methods are fired during the page load?

Init()When the page is instantiated, Load() - when the page is loaded into server memory,PreRender () - the brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.

Where does the Web page belong in the .NET Framework class hierarchy?System.Web.UI.Page

Where do you store the information about the user's locale?System.Web.UI.Page.Culture

What's the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?CodeBehind is relevant to Visual Studio.NET only.


What's a bubbled event?

When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.Suppose you want a certain ASPNET function executed on MouseOver over a certain button.

Where do you add an event handler?

It's the Attributesproperty, the Add function inside that property. e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();")


What data type does the RangeValidator control support?

Integer,String and Date.