6.8.08

Session state management in ASP.NET

  • Define Session, SessionId and Session State in ASP.NET.

Answer - A session is the duration of connectivity between a client and a server application. SessionId is used to identify request from the browser. By default, value of SessionId is stored in a cookie. You can configure the application to store SessionId in the URL for a "cookieless" session.

  • What is Session Identifier?

Answer - Session Identifier is used to identify session. It has SessionID property. When a page is requested, browser sends a cookie with a session identifier. This identifier is used by the web server to determine if it belongs to an existing session. If not, a Session ID (120 - bit string) is generated by the web server and sent along with the response.

  • Advantages and disadvantages of using Session State

Advantages of using session state:

It is easy to implement.

It ensures data durability, since session state retains data even if ASP.NET work process restarts as data in Session State is stored in other process space.

It works in the multi-process configuration, thus ensures platform scalability.

Disadvantages of using session state:

Since data in session state is stored in server memory, it is not advisable to use session state when working with large sum of data. Session state variable stays in memory until you destroy it, so too many variables in the memory effect performance.

  • What are the Session State Modes? Define each Session State mode supported by ASP.NET

InProc Mode

This mode stores the session data in the ASP.NET worker process.This is the fastest among all of the storage modes.This mode effects performance if the amount of data to be stored is large.If ASP.NET worker process recycles or application domain restarts, the session state will be lost.

State Server mode

In this mode, the session state is serialized and stored in memory in a separate process.State Server can be maintained on a different system. State Server mode involves overhead since it requires serialization and de-serialization of objects. State Server mode is slower than InProc mode as this stores data in an external process.

SQL Server Mode

In this storage mode, the Session data is serialized and stored in a database table in the SQL Server database. This is reliable and secures storage of a session state. This mode can be used in the web farms. It involves overhead in serialization and de-serialization of the objects.SQL Server is more secure than the InProc or the State server mode.


Globalization and Localization in ASP.NET

  • What is Globalization and Localization in ASP.NET?

Answer - Localization is the process of adapting a software application for a specific locale. Globalization is the process of identifying the localizable resources of the application. You can provide support for Localization and Globalization to the application using System.Globalization, System.Resources and System.Threading namespaces.

The developer can define culture specific information using the System.Globalization namespace. The System.Resources namespace contains ResourceManager class that allows access to resources either from the main assembly or from the Satellite Assemblies. The System.Threading namespace supports for multithreaded programming.

A web form has two culture values, Culture and UICulture. Culture value is used for date and number formatting and UICulture values are used to determine culture specific resources.

You can set culture and UICulture values in the application as follows.

Using element of Web.Config.

Using @Page directive in the Page.

In Code-Behind Page

e.g.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ("en-GB");

Thread.CurrentThread.CurrentUICulture=new CultureInfo("en-GB");

  • What are the Globalization approaches possible in ASP.NET?

Answer - You can follow many approaches to have globalized application.

You can create separate web application for each culture.

You can create an application that can detect the user’s culture and adjusts output at run time using format specifiers and other tools.

You can store culture-dependent strings in resource files that are compiled into satellite assemblies.

  • Implementing ASP.NET Globalization

Answer - Create resource files and compile them into a binary resource file.

Create satellite assembly for each of the resource file for each culture.

Store them in separate folders for easy access and replacement.

Read the resources from the satellite assembly that is stored in different folders based on the locale and culture.

  • Define Resource Files and Satellite Assemblies

Answer-Resource Files: A resource file contains non-executable data that are used by the application and deployed along with it. Bitmaps, Icons etc are the examples of resource files. In ASP.NET, resource files are used to make application to support multiple cultures. You can create resource files each of them correspond to specific locale or culture of the application. You can use resgen utility to compile resource file into an assembly. You can create a satellite assembly from a compiled resource file using the AL utility provided with Microsoft .NET SDK

Advantages of resource files are as follows.

It supports Globalization features in ASP.NET.

You can have culture based information separate from the content and logic of the application.

You can change resource content without effecting application's code.

Satellite Assemblies

Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture-specific resources in a binary format. They store compiled localized application resources. They can be created using the AL utility and can be deployed even after deployment of the application. Satellite Assemblies encapsulate resources into binary format and thus make resources lighter and consume lesser space on the disk.

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

ASP.NET Caching Technique

Define Caching in ASP.NET
  • Answer - Caching technique allows to store/cache page output or application data on the client. The cached information is used to serve subsequent requests that avoid the overhead of recreating the same information. This enhances performance when same information is requested many times by the user.

Advantages of Caching

  • Answer - It increases performance of the application by serving user with cached output. It decreases server round trips for fetching data from database by persisting data in the memory.It greatly reduces overhead from server resources.

What are the types of Caching in ASP.NET?

  • Page Output Caching:This type of caching is implemented by placing OutputCache directive at the top of the .aspx page at design time. For example:<%@OutputCache Duration= "30" VaryByParam= "DepartmentId"%>The duration parameter specifies for how long the page would be in cache and the VaryByParam parameter is used to cache different version of the page. The VaryByParam parameter is useful when we require caching a page based on certain criteria.
  • Page Fragment Caching:This technique is used to store part of a Web form response in memory by caching a user control.
  • Data Caching: Data Caching is implemented by using Cache object to store and quick retrieval of application data. Cache object is just like application object which can be access anywhere in the application. The lifetime of the cache is equivalent to the lifetime of the application.

AJAX

Ajax is a set of client side technologies that allows asynchronous communication between client and web server. In synchronous communication, complete round trip happens with each request/response action event when small data of the page to be refreshed. Ajax has solved this problem of posting entire information every time through asynchronous communication.
XmlHttpRequest is the basic fundamental behind Ajax. This allows browser to communicate with server without making post backs.

Difference Between Constant and ReadOnly

Const Keyword :
  • Example: public const string abc = “xyz”;
  • Initialized only at declaration.
  • Value is evaluated at compile time and can not be changed at run time.An attempt to change it will cause a compilation error.
  • Const is already kind of static.
  • Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types.

Readonly Keyword:

  • Example: public readonly string abc;
  • Can be initialized in declaration code or consturctor code.
  • Value is evaluated at run time.
  • Can be declared as static or instance level attribute.
  • A read only field can hold a complex object by using the new keyword at run time.

A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. With Const fields, the compiler performs some optimization by not declaring any stack space for the field.

Constant means - > if you want to define something at compile time . after that u can't change that value that .....

Readonly means - > if you don't know value at compile time but u can find that at runtime that time u can use readonly ..

2.8.08

ADO.NET

ADO.NET Overview

ADO.NET is design to provide data access. ADO.NET supports disconnected database access model which means that connection is open long enough to perform data operation and is closed. When data is requested by the application, connection is opened, required data is loaded to the application and connection gets close. So in ADO.NET, connection is only available when it is required. This model reduces system resource usage and thus enhances performance.
ADO.NET is shipped with the Microsoft .NET Framework. It is used to access relational data sources, XML, and application data.ADO.NET uses XML for data transaction between client application and database.

To access data using ADO.NET's DataAdapter objects

  • Create connection using connection object.
  • Create Dataset object using DataAdapter object.
  • Load data into Dataset using fill method of DataAdapter.
  • Display Data using Dataset object.
  • Close connection

ADO.NET vs ADO

  • ADO.NET is considered as evolution version of ADO.
  • ADO.NET works with both connected as well as disconnected fashion whereas ADO works with connected architecture.
  • ADO.NET provides disconnected access through DataSet while ADO provides disconnected access using recordset.
  • ADO.NET use XML to transfer data between objects while ADO use binary format to transfer data.
  • ADO.NET is shipped with .Net Framework and implemented using .Net methodology whereas ADO relies on COM.

ADO.NET Data Architecture

ADO.NET has four layers.

* The Physical Data Store

This can be any database, XML files or OLE.

*The DataSet

The dataset stores relevant portion of the database on the local machine. It allows data to be loaded in the memory of the machine and is disconnected from the database. The dataset can manipulate disconnected data in the memory. It contains one or more DataTable objects. The DataTable objects contain DataColumns, DataRows and Constraint collections. The DataSet contains a DataRelations collection which allow you to create associations between rows in one table and rows in another table.

*The Data Provider

A data provider provides a set of components that helps to extract data from database. The components are as follows:

Connection object

Command object

DataReader

DataAdapter

*The Dataview

This determines presentation of a table in the dataset. This is mainly used to sort or filter data in the dataset.

Type of database connection in ADO.NET

SQL Connection

This object connects to the SQL Server.

Oracle Connection

This object is used to connect oracle database.

Oledb connection

This object is used to connect MS Access or MySQL(third party database).
Apart from these connections, ADO.NET also allows access to XML files using Dataset object's ReadXML and WriteXML method.

Components of data providers in ADO.NET

The Connection Object

The Connection object represents the connection to the database. The Connection object has ConnectionString property that contains all the information, required to connect to the database.

The Command Object

The command object is used to execute stored procedures and command on the database. It contains methods to execute command on the database such as ExecuteNonQuery, ExecuteScalar and ExecuteReader.

ExecuteNonQuery

Executes commands that return no records, such as INSERT, UPDATE, or DELETE

ExecuteScalar

Returns a single value from a database query

ExecuteReader

Returns a result set by way of a DataReader object

The DataReader Object

The DataReader object provides a connected, forward-only and read-only recordset from a database. The Command.ExecuteReader method creates and returns a DataReader object. Since it is connected to the database throughout its lifetime, it requires exclusive use of connection object.

The DataAdapter Object

The DataAdapter object acts a communication bridge between the database and a dataset. It fills the dataset with data from the database. The dataset stores the data in the memory and it allows changes. The DataAdapter's update method can transmit the changes to the database.

The DataAdapter Object's properties.
SelectCommand-Contains the command text or object that selects the data from the database.
InsertCommandCont-ains the command text or object that inserts a row into a table.
DeleteCommand-Contains the command text or object that deletes a row from a table.
UpdateCommand-Contains the command text or object that updates the values of a database.

Define connected and disconnected data access in ADO.NET

You have connected data access through the DataReader objects of data provider. This object requires exclusive use of the connection object. It can provide fast and forward-only data access. It doesn't allow editing. Disconnected data access is achieved through the DataAdapter object. This object establishes connection, executes the command, load data in the DataSet. The dataset works independent of database. It contains data in the memory and can edit the data. The changes in the data can be transmitted to the database using Update method of DataAdapter object.

Describe CommandType property of a SQLCommand in ADO.NET.

A SQLCommand has CommandType property which can take Text, Storedprocedure or TableObject as value. If it is set to Text, the command executes SQL string that is set to CommandText property. When set to StoredProcedure, the command runs the stored procedure of the database. If the property is set to TableObject, the command returns the entire content of the table indicated by the CommandText property.

Define Dataview component of ADO.NET.

A DataView object allows you work with data of DataTable of DataSet object. It is associated with a DataTable and sits on the top of DataTable. It is used to filter and sort data. Data sorting is accomplished by setting the Sort property and data filter by setting the RowFilter property.

What are the ways to create connection in ADO.NET?

There are two ways to create connection supported by ADO.NET.

Steps to create connection in codeCreate instance of connection object.Set the ConnectionString property.

Steps to create connection using designerDrag connection object from the Data tab of the toolbox.Set the ConnectionString property using properties window.

ADO.NET transaction Processing
Steps to use transaction object
Open a database connection.Create the transaction object using BeginTransaction method of connection object.Create command object by using transaction object as the parameter. Execute the commands and check for the error.If no error, commit the changes to the database or restore the database state.Close the connection.

sample code

//Connection
SqlConnection sqlConn = new SqlConnection(@"Data Source=LCHNS1403\SQLEXPRESS;Initial Catalog=ODS_Tracking718;uid=sa;pwd=Windows123;");
//Command
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlConn;
//if incase of stored procedure
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "SpName";
sqlCmd.Parameters.Add("parm1");
sqlCmd.Parameters.Add("parm2");
//SQl DataAdapter
SqlDataAdapter sqlDadp = new SqlDataAdapter();
sqlDadp.SelectCommand = sqlCmd;
DataTable sqlDT = new DataTable();
sqlDadp.Fill(sqlDT);
//Grid Bind
datagridname.DataSource = sqlDt;
datagridname.DataBind();
}

.Net Assembly

  • Question - Define .Net Assembly.
    Answer - It is a primary unit of deployment in a Microsoft .NET Framework application. It is called as building block of an application which provides all required execution information to common language runtime[CLR]. An assembly perform following functions:It contains IL code that gets executed by common language runtime. It forms a security boundary. An assembly is the unit at which permissions are requested and granted. It ensures type safety by establishing name scope for types at the runtime. It contains version information. It allows side-by-side execution of multiple versions of same assembly. Assemblies can be static or dynamic. Static assemblies are created when the program is compiled using .Net compiler. It exists as PE file either in .exe or .dll. However, dynamic assemblies are created at runtime and run from the memory without getting saved on the disk.
  • Question - What does an assembly contain?
    Answer - An assembly contains following information: Assembly manifest: Information about the assembly. Type metadata: Information about the types. IL Code Resource files.
    An assembly manifest contains the following information:
    Identity of the assemblyTypes and resourcesFilesSecurity permissions
  • Question - Define private assembly and a shared assembly.
    Answer - A private assembly is stored in the application’s directory and used by a single application. A share assembly can be used by multiple applications and is stored in the Global assembly cache, a repository of assemblies maintained by the .Net Framework.
  • Question - What are Satellite Assemblies?
    Answer - Satellite assemblies provide an application the multilingual support. Satellite assemblies contain alternate sets of resources to be used in the application for different cultures.
  • Question - What do you understand by side-by-site execution of assembly?
    Answer - This means multiple version of same assembly to run on the same computer. This feature enables to deploy multiple versions of the component.
  • Question - How do you create a resource-only assembly?
    Answer - Resources are nonexecutable data in an application and the data can be updated without recompiling application. Resource assemblies can be created as follows:Add resource files to an empty project. Built the project.The resource will get compiled into assembly.
  • Question - Explain how to retrieve resources using ResourceManager class.
    Answer - ResourceManager class is used to retrieve resources at run time. Create a ResourceManager with resource file name and the resource assembly as parameters.After having created, you can use ResourceManager.GetString method to retrieve a string.Use the ResourceManager.GetObject method to retrieve images and objects from a resource file.
  • Question - Define Strong Name. How do you apply a strong name to assembly?
    Answer - A strong name means generating public key in order to provide unique name to the assembly.The name is used to provide global name to the assembly and allows it to be shared amongst several different applications. The key generated include assembly's name, the version number, the developer's identity, and a hash number. The developer's identity identifies the author of the assembly. The hash checks if the assembly is tempered since it is created. The key pair that defines the strong name is created using the Strong Name utility, Sn.exe.
    To sign an assembly with a strong name
    Create Key pair using the Strong Name utility, Sn.exe. Open the AssemblyInfo file of your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. The strong name will be generated and signed to the assembly.
  • Question - Define Global Assembly Cache.
    Answer - Global Assembly Cache is the place holder for shared assembly. If an assembly is installed to the Global Assembly Cache, the assembly can be accessed by multiple applications. In order to install an assembly to the GAC, the assembly must have to be signed with strong name.
  • Question - How do you install assembly to the Global Assembly Cache?
    Answer - Followings are the steps to install assembly to the GAC. Sign assembly with a strong name using strong name utility, sn.exe. Open the AssemblyInfo file for your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. Install the assembly to GAC by using gacutil utility e.g. gacutil -i abc.dll

Net Framework

  • Question - Explain the .Net Framework.
    Answer - The .Net framework allows infrastructural services to all the applications developed in .net compliant language. It is an engine that provides runtime services using its component like Common Runtime Language. It consists of two main components such as Common Language Runtime and Framework Class Library.
  • Question - Describe the .Net Framework Architecture.
    Answer - The .Net Framework has two main components: .Net Framework Class Library: It provides common types such as data types and object types that can be shared by all .Net compliant language. The Common language Runtime: It provides services like code execution, type safety, security, thread management, interoperability services.
  • Question - What are the components of the .Net Framework.
    Answer - Class Loader, Compiler, Garbage Collection, Type checker, Debug engine, Exception Manager, Security engine, Thread manager, COM Marshallar, Class Library.
  • Question - Explain the role of assembly in the .Net Framework.
    Answer - .Net Framework keeps executable code or DLL in the form of assembly. .Net Framework maintains multiple versions of the application in the system through assembly. The assemblies have MSIL code and manifest that contains metadata. The metadata contains version information of the assembly.
  • Question - Describe the GAC in the .Net Framework.
    Answer - .Net Framework provides Global Assembly cache, a machine-wide cache. It stores shared assemblies that can be accessed by multiple languages

.Net Debugging and tracing

Question - What is break mode? What are the options to step through code?
Answer - Break mode lets you to observe code line to line in order to locate error.VS.NET provides following option to step through code.Step Into Step Over Step Out Run To Cursor Set Next Statement
Question - Debug Vs Trace.
Answer - Both these objects are found in the System.Diagnostics namespace. Both are used for diagnose problems without interrupting application execution. Debug statement can only be used in debug mode while trace statement can be used both in debug and released mode.Debug statements can't be compiled into a release version.
Question - Define trace class.
Answer - The trace class in the code is used to diagnose problem. You can use trace messages to your project to monitor events in the released version of the application.The trace class is found in the System.Diagnostics namespace.
Question - Define Listeners collection of Trace and Debug objects.
Answer - The Trace and Debug objects contain a Listeners collection. These Listeners collection collect output from the trace statements. There are three types of predefined listeners: DefaultTraceListenerTextWriterTraceListenerEventLogTraceListener
DefaultTraceListener: This is default listener and writes trace statements in the Output window. TextWriterTraceListener: can write output to the text file or to the console window. EventLogTraceListener: can write messages to the Event Log.
Question - Define Trace Switches.
Answer - Trace switches are used to configure tracing behavior. There are two kinds of trace switches: BooleanSwitch and TraceSwitch. BooleanSwitch: It is either on or off. TraceSwitch : It has property to determine trace behaviour. Trace switches can be configured through application's .config file even after the application is compiled.

C#.NET Interview Questions

Question - Define assembly.
Answer - An assembly is the primary unit of a .NET application. It includes an assembly manifest that describes the assembly.
Question - What is Constructor?
Answer - It is the first method that are called on instantiation of a type. It provides way to set default values for data before the object is available for use. Performs other necessary functions before the object is available for use.
Question - What is Destructor?
Answer - It is called just before an object is destroyed. It can be used to run clean-up code. You can't control when a destructor is called since object clean up by common language runtime. Question - Define Abstract class in C#.NET.
Answer - Abstract class cannot be instantiated.
Same concept in C++ known as pure virtual method.
A class that must be inherited and have the methods over-ridden.
A class without any implementation.
Question - Explain serialization?
Answer - Serialization is a process of converting an object into a stream of bytes. .Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer. Serialization is maily used in the concept of .Net Remoting.
Question - C#.Net support multiple inheritance, comment.
Answer - No, but we can use interface instead.
Question - Can private virtual methods be overridden in C#.NET?
Answer - No, moreover, you cannot access private methods in inherited classes,
They have to be protected in the base class to allow any sort of access.