Tuesday, May 12, 2009

Windows Authentication(Active Directory/LDAP) in ASP.Net

Sometimes, there may be requirement to get user name from end user information and authenticate against active directory group/LDAP in ASP.Net.

Following are the ways to achieve that
  • can be accomplished by enabling windows Integrated authentication in IIS server and disabling Anonymous access for this application. By doing the above config changes in IIS server, the user will be shown a Login window in the browser and prompting for windows user credentials.

  • Alternate way is to get the logon crdentials using C# code and validate again user information. Below is the code snippet which is used to capture the login info using windows integrated authentication and validate against AD group.

Write the following code sample in the Session start event and based on user validation, session will be started

using System.Security.Principal;
using System.Security.Permissions;

protected void Session_Start(Object sender, EventArgs e)
// Get the current loged in User information
WindowsPrincipal user = (WindowsPrincipal)Thread.CurrentPrincipal;

//Storing the user name in the session. If you remove the domain name, u can get user name alone
Session["userName"] =user.Identity.Name.Replace("DOMAINName\\",string.Empty);

// This session variable is used further to verify the user
Session["SecurityIsApproved"] = "false";

// Check for valid user in the AD group
if(user.IsInRole("Active Directory group name"))
Session["SecurityIsApproved"] = "true";
throw new Exception("Invalid user");

Monday, May 11, 2009

Authentication in ASP.Net

The article explains different types of Authentication available in ASP.Net framework and it's functionalities. This explains the various authentication options supported by .net and their features. Each has their own advantages as well as dis-advantages and decision of the Authentication depends on the application.

  • Forms authentication A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. The user provides credentials and submits the form. If the application authenticates the request, the system issues a cookie that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the cookie in the request headers; they are authenticated and authorized by an ASP.NET event handler using whatever validation method the application developer specifies.

  • Passport authentication Centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites.

  • Windows authentication ASP.NET uses Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication. Authentication is performed by IIS in one of three ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access.

To enable an authentication provider for an ASP.NET application, you only need to create an entry for the application configuration file as follows.

authentication mode= "[WindowsFormsPassportNone]"/>

The different authentication Methods are

  • Anonymous Authentication: Used for public areas of Internet sites.Used for public areas of Internet sites. This is supported by all browsers and uses IUSR_computername account.

  • Basic Authentication: This requires a user name and password and Transmits password unencrypted.Assumption here is that the connection between the client and server computers is secure and can be trusted. Specifically, the credentials are passed as plaintext and could be intercepted easily.One advantage of the basic access authentication is that it is supported by all popular web browsers.

  • Digest authentication addresses many of the weaknesses of basic authentication.Usable across proxy servers and other firewalls.Digest Authentication offers single sign-on only to a single Web URL protection space. If users navigate to a different Web site, or even to a different server in the same site, they will usually be prompted to enter credentials again.

  • Integrated Windows Authentication: Used for private areas of intranets.Secure form of authentication because the user name and password are not sent across the network.

  • Certificates: Widely used for secure transactions over Internet.Obtain server certificates. Configure certificate trust lists (CTLs) (for first use only).

  • Forms authentication: used for personalization, where content is customized for a known user.This is achieved using SQL Server membership provider and active directory membership provider.Controls like ASP.Net login controls are used to implement forms authentication.

Differences between NTLM and Kerberos in Windows authentication

NTLM Authentication is the well-known and loved challenge-response authentication mechanism. That is the default authentication protocol of Windows NT 4.0 and earlier Windows versions. For backward compatibility reasons, Microsoft still supports NTLM in Windows Vista, Windows Server 2003.

Kerberos, on the other hand, is a more complex ticket-based authentication mechanism that authenticates the client to the server and authenticates the server to the client. While Kerberos is more secure, it can be a bit challenging to set up properly.

Kerberos has the following key advantages that make it worth consideration.

  • Performance - Kerberos caches information about the client after authentication. This means that it can perform better than NTLM particularly in large farm environments.
  • Delegation - Kerberos can delegate the client credentials from the SharePoint (For Example) front-end web server to other back-end servers like SQL Server. As an example, consider a web part that access a SQL Server database and uses a connection string that relies on the end-user credentials (i. e., “Integrated Security=SSPI”). If the targeted SQL Server is not on the same physical server as SharePoint, the database log in will fail under NTLM authentication. This is the dreaded “double-hop” scenario that affects not only SharePoint, but ASP.NET applications as well. Under Kerberos, however, the log in will succeed.
  • Kerberos supports for smart card logon where as NTLM is not.

Friday, May 8, 2009

Frequently asked interview questions in SQL Server 2005

This article explains the frequently asked (FAQs) interview questions in SQL Server 2005 with answers. This covers basic and advanced concept of SQL Server

1. What are the differences between User Defined function (UDF) and Stored Procedure?

  • Stored Procedure is pre compiled execution plan where as functions are not.
  • Stored Procedure returns more than one value at a time while function returns only one value at a time.
  • We can call the UDFs in sql statements (select max (sal) from emp) whereas SP is not so
  • Function parameters are always IN, no OUT is possibleFunctions MUST return a value, procedures need not be
2. How to Create and Run a CLR SQL Server User-Defined Function?

  • Create a SQL Server Project in Visual Studio
  • From the Project menu, select Add New Item.
  • Select User-Defined Function in the Add New Item Dialog Box.
  • Type a Name for the new user-defined function.

using System.Data.SqlTypes;

using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions{
public static SqlDouble addTax(SqlDouble originalAmount) {
SqlDouble taxAmount = originalAmount * .3;
return originalAmount + taxAmount;

Select Deploy project from the Build menu
Note : The common language runtime (CLR) integration feature is turned off by default in Microsoft SQL Server and must be enabled in order to use SQL Server project items.
To enable CLR integration, use the clr enabled option of the sp_configure stored procedure.

EXEC sp_configure 'clr enabled' , '1'

To learn more, click here

3. What is SQL Cache Dependency in ASP.NET 2.0?

SQL cache dependencies are new technique in ASP.NET 2.0 which can automatically invalidate a cached data object just like a Dataset. when the related data is modified in the database. So for instance if you have a dataset which is tied up to a database tables any changes in the database table will invalidate the cached data object which can be a dataset or a data source.
To enable this we need a syntax that is as follows:- aspnet_regsql -ed -E -d Northwind

4.What are the different types of temporary tables in SQL Server?
  • Local temporary tables are created using a single pound (#) sign and are visible to a single connection and automatically dropped when that connection ends.
  • Global temporary tables are created using a double pound (##) sign and are visible across multiple connections and users and are automatically dropped when all SQL sessions stop referencing the global temporary table.

5.What is the difference between UNION ALL and UNION Statement?

The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION. The reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

6. What is the use of Cascade and Restrict when we use DROP table in SQL SERVER?

When we are using Drop table in SQL the syntax is simple. SQL92 specifies some additional capabilities for DROP TABLE:
Drop table table_name(CASCADE / RESTRICT)

If we use cascade to drop table although it have some dependencies just like triggers, views, stored procedure, primary key, foreign key it will delete first.But if we use restrict a error message is shown on using of DROP if the table have relation Trigger or stored procedure

7. What is the use of SCHEMABINDING Option in creation of view in SQL Server?

Imagine that you have created a view without SCHEMABINDING option and you have altered the schema of underlying table (deleted one column). Next time when you run your view, it will fail. Here is when SCHEMABINDING comes into picture. Creating a view with SCHEMABINDING option locks the underlying tables and prevents any changes that may change the table schema.

E.g CREATE VIEW testview
SalesTerritoryID, CustomerID,
FROM testtable a INNER JOIN testtable2 b
ON (a.column1 = b.column1)

8. What are the differences between DELETE TABLE and TRUNCATE TABLE commands?

  • DELETE TABLE syntax logs the deletes thus make the delete operation slow. TRUNCATE table does not log any information but it logs information about deallocation of data page of the table so TRUNCATE table is faster as compared to delete table.
  • DELETE table can have criteria while TRUNCATE cannot.
  • TRUNCATE table cannot trigger

9. What is Normalization and what are the advantages?

It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization.

Benefits of normalizing your database will include:

  • Avoiding repetitive entries
  • Reducing required storage space
  • Preventing the need to restructure existing tables to accommodate new data.
  • Increased speed and flexibility of queries, sorts, and summaries.

10. What are the different types of Keys?

Different types of Keys

  • Primary key:- The attribute or combination of attributes that uniquely identifies a row or record.
  • Foreign Key:- an attribute or combination of attribute in a table whose value match a primary key in another table.
  • Composite key:- A primary key that consists of two or more attributes is known as composite key
  • Candidate key:- is a column in a table which has the ability to become a primary key. Candidate Key (Primary Key) is a Key which Maintains the Row Unique .
    A table may have more than one combination of columns that could uniquely identify the rows in a table; each combination is a candidate key.
  • Alternate Key:- Any of the candidate keys that is not part of the primary key is called an alternate key. Alternate Key or Unique Key is similar to PK , except it accepts null Values .

11. What is DBCC and explain it's use?

DBCC (Database Consistency Checker Commands) is used to check logical and physical consistency of database structure. DBCC statements can fix and detect problems.
They are grouped in to four categories:-

  • Maintenance commands like DBCC DBREINDEX , DBCC DBREPAR etc ,they are mainly used for maintenance tasks in SQL SERVER.
  • Miscellaneous commands like DBCC ROWLOCK , DBCC TRACEO etc ,they are mainly used for enabling row-level locking or removing DLL from memory.
  • Status Commands like DBCC OPENTRAN , DBCC SHOWCONTIG etc ,they are mainly used for checking status of the database.
  • Validation Commands like DBCC CHECKALLOC, DBCCCHECKCATALOG etc, they perform validation operations on database.

12. What are the types of replication supported by SQL SERVER 2005?

  • Snapshot Replication takes snapshot of one database and moves it to the other database. After initial load data can be refreshed periodically. The only disadvantage of this type of replication is that all data has to be copied each time the table is refreshed.
  • In transactional replication data is copied first time as in snapshot replication, but later only the transactions are synchronized rather than replicating the whole database. You can either specify to run continuously or on periodic basis.
  • Merge replication combines data from multiple sources into a single central database. Again as usual the initial load is like snapshot but later it allows change of data both on subscriber and publisher, later when they come on-line it detects and combines them and updates accordingly.

Configuring SQL server Replication using SQL Server Publication and Subscription, click here

13.What is BCP in SQL Server?

BCP (Bulk Copy Program) is a command line utility by which you can import and export large amounts of data in and out of SQL SERVER database.

14. What is the use of SQL Server Agent?

It is a Microsoft Windows service that executes scheduled administrative tasks, which are called jobs. SQL Server Agent uses SQL Server to store job information. Jobs contain one or more job steps. Each step contains its own task, for example, backing up a database. SQL Server Agent can run a job on a schedule, in response to a specific event, or on demand.

15. What are the types of Triggers?

1. DML Triggers

These triggers are fired when a Data Manipulation Language (DML) event takes place. These are attached to a Table or View and are fired only when an INSERT, UPDATE and/or DELETE event occurs. The trigger and the statement that fires it are treated as a single transaction. Using this we can cascade changes in related tables, can do check operations for satisfying some rules and can get noticed through firing Mails. We can even execute multiple triggering actions by creating multiple Triggers of same action type on a table.

  • AFTER Triggers: As the name specifies, AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. AFTER triggers can be specified on tables only. Here is a sample trigger creation statement on the Users table.

E.g To Create a DML trigger in T-SQL


CREATE TABLE UserTable (User_ID int IDENTITY, User_Name varchar(30), Type varchar(10))




INSERT UserTable (User_Name, Type) VALUES ('James', 'ADMIN')

  • INSTEAD OF Triggers INSTEAD OF triggers are executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates a view can support.

2. DDL Triggers

DDL triggers are new to SQL Server 2005. This type of triggers, like regular triggers, fire stored procedures in response to an event. They fire in response to a variety of Data Definition Language (DDL) events. These events are specified by the T-SQL statements that are start with the keywords CREATE, ALTER, and DROP. Certain stored procedures that perform DDL-like operations can also fire this. These are used for administrative tasks like auditing and regulating database operations.

3. CLR Triggers

A CLR triggers can be any of the above, e.g. can be a DDL or DML one or can also be an AFTER or INSTEAD OF trigger. Here we need to execute one or more methods written in managed codes that are members of an assembly created in the .Net framework. Again, that assembly must be deployed in SQL Server 2005 using CREATE assembly statement.

Creating CLR Trigger is available here

Wednesday, May 6, 2009

Frequently asked interview questions in ASP.Net web services

This article explains the frequently asked interview questions in ASP.Net web services with answers. This covers basic and advanced concept of Web service

1. What is Service Orientated Architecture(SOA)?

A service-oriented architecture (SOA) is a group of services that communicate with each other. The process of communication involves either simple data-passing between a service provider and service consumers, or a more complicated system of two or more service providers. Intercommunication implies the need for some means of connecting two or more services to each other.

Simply, SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications.

2. What are the approaches for implementing SOA?

Web services can implement a service-oriented architecture. Implementers commonly build SOAs using Web services standards (for example, using SOAP) that have gained broad industry acceptance.

Building blocks of SOA are

  • The service provider creates a Web service and possibly publishes its interface and access information to the service registry. Each provider must decide which services to expose, how to make trade-offs between security and easy availability, how to price the services, or (if no charges apply) how to exploit them for other value.
  • The service requester or Web service client

3. When do you require doing an Update a Project Web Reference?

The application contains a Web reference to an XML Web service that has been recently modified on the server; you might need to update the reference in your project. While updating web service, it generates a new proxy for the Web service so you can access the new method.

4. What are the Components of Web service?

The componets of ASP.Net web services are

  • SOAP (Simple Object Access Protocol) is a communication protocol it is for communication between applications. Its platform and language independent. It is based on XML and also help to get from Firewall.
  • WSDL(WebService description language) is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. It explains Service, method, input and output parameters.
  • UDDI stands for Universal Description, Discovery, and Integration. It is like a "Yellow Pages" for Web Services and is designed to provide detailed information regarding registered Web Services for all vendors. It is maintained by companies like Microsoft, IBM etc

5. What are the different Web Services Protocols?

  • Http-Get protocol This is standard protocol that helps client to communicate with server with HTTP. When client send a request to server via HTTP request and reuired parameter are attached with the querystring.

    E.g http://dotnet/interview.aspx?param1=value1&param=value2 and we get the value from query string.

  • Http-Post is same as Http-Get but the difference is that in place of sending parameters onto the URL information is send with HTTP request message with some extra information which contains Parameters and their values. These Protocols is limited to sending name/value pairs.

  • SOAP: The only difference is that its relies on the XML as compares to Http-Get, Http-Post. SOAP can send not only the name/value pairs but also some complex object also as for example data types, class, objects. SOAP can also uses request/response model as Http-Get, Http-post but it is not limited to Request/Response it can also send types of message. Because its uses XML that is pure text and hence pass firewalls easily.

6. What is Web Service Enhancement 3.0 (WSE)?

Web Services Enhancements for .NET (WSE) is a product that enables you to build secure Web services quickly and easily.This gives wizard based approach for developing and securing web services.

  • The Web Services Enhancements for Microsoft .NET (WSE) has many features to augment applications built on Web services using the .NET Framework 2.0.
  • Securing Applications That Use Web Services
  • Integration with .NET Framework 2.0 and Visual Studio 2005
  • Sending Large Amounts of Data in a SOAP Message Using WSE

7. What are the different types of Security supported in ASP.Net Web services?

The type of Security supported in ASP.Net Web services

  • Anonymous
  • Username
  • Windows(Kerberos)
  • Certificate

8.What are the differences between ASP.net Web Service and .Net Remoting?

  • Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET or another framework that supports .NET Remoting which means a homogeneous environment.

  • Web services work in a stateless environment where each request results in a new object created to service the request. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects. .NET Remoting supports state management options using Singleton and can correlate multiple calls from the same client and support callbacks.

  • Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.

  • In terms of performance, the .NET Remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In the case of Web services, the primary issue is performance.

  • Web service Can be accessed only over HTTP where as .net Remoting Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

  • Web services are Easy-to-create and deploy where as Remoting is Complex to program

9. How to avoid timeout in .net web service?

For long running process, the ASP.Net web service may timeout. To avoid this time out error, increase the timeout in Server and client side

At Server Side
<configuration> <system.web>

<httpRuntime executionTimeout="300"/>

</system.web> </configuration>

The above configuration increases request timeout to 5 minutes

At Client side, increase the timeout of the web service proxy
Service1 proxy = new Service1 ();

proxy.Timeout = 300;

10. How to pass the client credentials to a web service using proxy?

To Pass the client credential at the client side using service proxy, write the following code using proxy credentials

// Create a new instance of the proxy class to an XML Web service method.

Service1 proxy = new Service1();

// Add the CredentialCache to the proxy class credentials.

proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Call the method on the proxy class.

int result = proxy.myWebMethod(5,5);

Monday, May 4, 2009

Create Hierarchical Grid using WPF. A sample Application Using WPF

This article explains the creation of the hierarchical grid using .net Windows presentation foundation concept. This also explains a sample application using WPF.

To do this, we need

  • Listview to display the items

  • Groupstyle Property to group items.

  • To get the number of items, define ContainerStyle for the GroupStyle and ItemCount will give the number of items in that category.

  • GridView to show the grid

The xaml code for the above sample looks like

<Window x:Class="WpfSampleApp.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Heirarchial Grid Sample" Height="300" Width="300">


<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
<XmlDataProvider x:Key="MyData" XPath="/Info">
<Info xmlns="">
<Item ID="ISBN 45-F1" Name="Winner" Price="$32.05" Author="Aka" Catalog="Business"/>
<Item ID="ISBN 54-32" Name="C++ Inside" Price="$10.00" Author="John" Catalog="Language"/>
<Item ID="ISBN 14-A0" Name="Java Inside" Price="$9.00" Author="Tom" Catalog="Language"/>
<Item ID="ISBN 56-78" Name="Stock Market" Price="$8.50" Author="Bob" Catalog="Business"/>
<Item ID="ISBN AA-02" Name="Guideline for Health" Price="$19.00" Author="Lee" Catalog="Health"/>
<Item ID="ISBN A4-07" Name="C# Inside" Price="$8.50" Author="Bob" Catalog="Language"/>
<CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}">
<d:PropertyGroupDescription PropertyName="@Catalog" />

<ListView ItemsSource='{Binding Source={StaticResource src}}' BorderThickness="0">
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" BorderBrush="#FFA4B97F" BorderThickness="0,0,0,1">
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
<TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}"/>
<ItemsPresenter />
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding XPath=@ID}" Width="100" />
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding XPath=@Name}" Width="140" />
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding XPath=@Price}" Width="80" />
<GridViewColumn Header="Author" DisplayMemberBinding="{Binding XPath=@Author}" Width="80" />

The Output of the above code looks like below


Saturday, May 2, 2009

Frequently asked interview questions in ASP.Net

This article explains the frequently asked interview questions in ASP.Net with answers

1. How to bring COM Component Compatibility in ASP.NET?

When using single-threaded apartment (STA) COM components, such as components developed using Visual Basic, from an ASP.NET page, you must include the compatibility attribute AspCompat=true in an Page tag on the ASP.NET page, as shown in the following code example.
<%@ Page AspCompat="true" Language = "C#" %>

2. What is the difference between login controls in ASP.Net and Forms authentication?

Login controls are an easy way to implement Forms authentication without having to write any code. For example, the Login control performs the same functions you would normally perform when using the FormsAuthentication class

  • prompt for user credentials
  • validate them, and
  • issue the authentication ticket

But with all the functionality wrapped in a control that you can just drag from the Toolbox in Visual Studio. Under the covers, the login control uses the FormsAuthentication class (for example, to issue the authentication ticket) and ASP.NET membership (to validate the user credentials). Naturally, you can still use Forms authentication yourself, and applications you have that currently use it will continue to run.

3.Since there can be multiple ASP.NET configuration files on one computer, how does ASP.NET configuration handle inheritance?

ASP.NET integrates the settings in configuration files (the Machine.config and Web.config files) into a single inheritance hierarchy. With a few exceptions, you can place a Web.config file wherever you need to override the configuration settings that are inherited from a configuration file located at a higher level in the hierarchy.

We can have web config file at each folder or sub folder of the web application which overrides the higher level config. To learn more about web config hierarchy, click here

4. What is the difference between Web server control and HTML control?

Server Control

  • Runs at the serverY
  • ou prefer a Visual Basic-like programming model.
  • You are writing a Web Forms page that might be used by both HTML 3.2 and HTML 4.0 browsers.

HTML control

  • Runs in the Browser
  • You prefer an HTML-like object model.
  • You are working with existing HTML pages and want to quickly add Web Forms functionality. Because HTML server controls map exactly to HTML elements, they can be supported by any HTML design environment.
  • The control will also interact with client script.

HTML Server Controls, By default, HTML elements within an ASP.NET file are treated as literal text and you cannot reference them in server-side code. To make these elements programmatically accessible, you can indicate that an HTML element should be treated as a server control by adding the runat="server" attribute. You can also set the element's id attribute to give you way to programmatically reference the control. You then set attributes to declare property arguments and event bindings on server control instances. Sample controls are HtmlAnchor, HtmlButton, HtmlForm, HtmlLink etc.

5. Explain ASP.NET State Management?

States in ASP.Net is maintained at client and server sides.

Client-Based State Management Options

  • View state : The web is stateless. But in ASP.NET, the state of a page is maintained in the page itself automatically. The values are encrypted and saved in hidden controls. This is done automatically by the ASP.NET. This can be switched off / on for a single control
    This is done using EnableViewState property for each control.

  • Control state

  • Hidden fields ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control.

<asp:hiddenfield id="ExampleHiddenField" value="Example Value" runat="server"/>

  • Cookies : A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.

To store Cookies

// Use this line when you want to save a cookie

Response.Cookies["MyCookieName"].Value = "MyCookieValue";

// How long will cookie exist on client hard disk

Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

To get cookies

if (Request.Cookies["MyCookieName"] != null)

MyCookieValue = Request.Cookies["MyCookieName"].Value;

Server-Based State Management Options

  • Application state : ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.

Application["WelcomeMessage"] = "Welcome to test site.";

  • Session state: ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session.Session state is similar to application state, except that it is scoped to the current browser session.

Session["FirstName"] = FirstNameTxtBox.Text;

  • Profile Properties: ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. To learn more, click here

6. What is smart navigation in .net?

The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

7. How do I create pages in ASP.Net for mobile devices?

ASP.NET will automatically detect the type of browser making the request. This information is used by the page and by individual controls to render appropriate markup for that browser. You therefore do not need to use a special set of pages or controls for mobile devices. Whether you can design a single page to work with all types of browsers will depend on the page, on the browsers you want to target, and on your own goals.

8.What is ASP.NET Application Life Cycle Overview?. Or What happens when a user request a page from the browser?

  • User requests an application resource from the Web server. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

  • ASP.NET receives the first request for the application. When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.There will be only one application domain created for an application and all the clients use the same.

  • ASP.NET core objects are created for each request. After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects.

  • An HttpApplication object is assigned to the request. After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

9. Explain ASP.NET Page Life Cycle Overview?

  • Page request: The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

  • Start: In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

  • Page initialization: During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

  • Load: During load, if the current request is a postback (First load is not a post back or response to any client action is a postback) control properties are loaded with information recovered from view state and control state.

  • Validation: During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
    Postback event handling If the request is a postback, any event handlers are called.

  • Rendering: Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

  • Unload: Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

10. what is the difference between Themes and Cascading Style Sheets?

Themes are similar to cascading style sheets in that both themes and style sheets define a set of common attributes that can be applied to any page. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.

  • Themes can include graphics.
  • Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property. For more information, see the Theme Settings Precedence section above.
  • Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.

To apply a theme to a Web site.

In the application's Web.config file, set the Pages element to the name of the theme, either a global theme or a page theme, as shown in the following example:

<pages theme="ThemeName" />

To apply a theme to an individual pageSet the Theme or StyleSheetTheme attribute of the @ Page directive to the name of the theme to use, as shown in the following example:Theme="ThemeName"

11. What are the different types of Caching in ASP.Net?

The main difference between the Cache and Application objects is that the Cache object provides cache-specific features, such as dependencies and expiration policies.

Different types of caching using cache object of ASP.NET

  • Page Output Caching: Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static.
    Page Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique. The syntax looks like this:
    <%@OutputCache Duration="60" VaryByParam="none" %>

  • Page Fragment Caching: If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.

12.What are the various modes of storing ASP.NET session?

  • InProc: In this mode Session state is stored in the memory space of the Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web application restarts then session state is lost.

  • StateServer: In this mode Session state is serialized and stored in a separate process (Aspnet_state.exe); therefore, the state can be stored on a separate computer (a state server).

  • SQL SERVER: In this mode Session state is serialized and stored in a SQL Server database.

Session state can be specified in sessionState element of application configuration file. Using State Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over network again and again.
Session_End event occurs only in “Inproc mode”. ”State Server” and “SQL SERVER” do not have Session_End event.

13. What is the difference between Absolute and Sliding expiration in Cache?

Absolute Expiration allows you to specify the duration of the cache, starting from the time the cache is activated. The following example shows that the cache has a cache dependency specified, as well as an expiration time of one minute.


Sliding expiration: The following code specifies that the cache will have a sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be reset to another minute:

Cache.Insert("key","value",dependencies,DateTime.Now.AddMinutes(1), TimeSpan.FromMinutes(1))

14. Compare Datagrid, Datalist and repeater?

A Datagrid, Datalist and Repeater are all ASP.NET data Web controls. They have many things in common like DataSource Property, DataBind Method ItemDataBound and ItemCreated
Itemtemplate can be used for design. Datagrid has a in-built support for Sort, Filter and paging the Data, which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.Repeater is fastest followed by Datalist and finally datagrid.

15. What are WebFarm and WebGarden Differences?

Web farms are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic(Load Balancer) which decides which web server from the farm handles the request. For instance we have two servers “Server1” and “Server2” which have the same configuration and content. So there is a special switch which stands in between these two servers and the users and routes the request accordingly.

The routing logic can be a number of different options:-

  • Round-robin: Each node gets a request sent to it “in turn”. So, server1 gets a request, then server2 again, then server1, then server2 again.
  • Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes
  • Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be “equal” in performance.

Web Garden: All requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e. with out web garden we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all requests. This one instance of worker process uses the CPU processor as directed by the operating system. But when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. In short we can define a model in which multiple processes run on multiple CPUs in a single server machine are known as a Web garden. To configure Web Garden for asp.net application in web config

<processModel enable ="true" webGarden="true" cpuMask="12" />

cpuMask Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100. then convert to binary to decimal.