30.8.08

Creating StrongName and develop Com / Assembly in C#.Net

  1. Create a new Project Class Library

  2. Open .net command prompt andGo to the folder contanig DLL ie. navigate to the project’s folder eg: E:\Test Application\AssenblyLibry\AssenblyLibry\bin\Debug>

  3. Type sn -k keyname.snk, This will create keyname.snk file in that folder.

  4. A Properties folder with an AssemblyInfo.cs file was created right click on the folder and open properties. The default should be ‘Class Library’ / Open the assemblyinfo.cs file of project, Type file path in this tag [assembly:AssemblyKeyFile@"E:\hemant\practice\HP\bin\Debug\HP.snk")] Build application, finally your strong name created for your DLL.

  5. Goto the signing tab and check Sign the assembly, browse and point it to the ‘key.snk’ file.

  6. open the AssemblyInfo.cs , add [assembly: AssemblyKeyFileAttribute(@”..\..\key.snk”)]

  7. in the AssemblyInfo.cs set [assembly: ComVisible(true)], now copy the assembly GUID that was auto created with the file

  8. put [System.Runtime.InteropServices.GuidAttribute(”paste guid here”)] in your main class file in between the Namespace and Class.

  9. Build the solution.

  10. Register the Assembly. [”regasm xxxx.dll /tlb:xxxx.tlb /codebase xxxx” at the command prompt, while in the directory that contains xxxx.dll]

  11. The assembly is now accessible using COM
    Steps for Installing in GAC
  • After giving strong name in .net command prompt type gacutil in DLL path this will install file in assembly.
  • Copy the DLL file C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 folder
  • You can add references to another project using .net tab.




























Exceptions In C#.NET

In C# Exception / Error can be classified into
  • compile-time errors
  • runtime errors

Compile-time errors are errors that can be found during compilation process of source code. Most of them are syntax errors. Runtime errors happen when program is running. It is very difficult to find and debug the run-time errors. These errors also called exceptions.Exception generates an exception call at runtime. Exceptions in C# can be called using two methods:

  • Using the throw operator. It call the manage code anyway and process an exception.
  • If using the operators goes awry, it can generate an exception.

All Exception are inherited from base class named System.Exception.These class process many kind of exception:

  • out of memory exception,
  • stack overflow exception,
  • null reference exception,
  • index out of range exception,
  • invalid cast exception,
  • arithmetic exception etc.

28.8.08

From command line creating exe, dll ....

  • Compiles File.cs producing File.exe: csc File.cs
  • Compiles File.cs producing File.dll: csc /target:library File.cs
  • Compiles File.cs and creates My.exe: csc /out:My.exe File.cs
  • Compiles all of the C# files in the current directory, with optimizations on and defines the DEBUG symbol. The output is File2.exe: csc /define:DEBUG /optimize /out:File2.exe *.cs
  • Compiles all of the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed:
    csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs
  • Compiles all of the C# files in the current directory to Something.xyz (a DLL): csc /target:library /out:Something.xyz *.cs

Creating Assembly in VS C#.NET

Create an Empty Class Library Project
Select File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory using Browse button and click OK. See Figure 1.




















Figure 1.
Project and Its files
The Solution Explorer adds two C# classes to your project. First is AssemblyInfo.cs and second is Class1.cs. We don't care about AssemblyInfo. We will be concentrating on Class1.cs. See Figure 2.



























Figure 2
The mcMath Namespace
When you double click on Class1.cs, you see a namespace mcMath. We will be referencing this namespace in our clients to access this class library.
using System;


namespace mcMath
{
///
/// Summary description for Class1.
///

public class Class1
{
public Class1()
{
// // TODO: Add constructor logic here //
}
}
}
Now build this project to make sure every thing is going OK. After building this project, you will see mcMath.dll in your project's bin/debug directory.
Adding Methods
Open ClassView from your View menu. Right now it displays only Class1 with no methods and properties. Lets add one method and one property. See Figure 3.
















Figure 3.
Build the DLL
Now build the DLL and see bin\debug directory of your project. You will see your DLL. Piece of cake? Huh? :).
Building a Client Application
Calling methods and properties of a DLL from a C# client is also an easy task. Just follow these few simple steps and see how easy is to create and use a DLL in C#.
By adding the Dll to the reference of the project to get all the features
Call mcMath Namespace, Create Object of mcMathComp and call its methods and properties.
You are only one step away to call methods and properties of your component. You follow these steps:
  1. Use namespace
    Add using mcMath in the beginning for your project. using mcMath;
  2. Create an Object of mcMathComp. mcMathComp cls = new mcMathComp();
  3. Call Methods and Properties

Now you can call the mcMathComp class method and properties as you can see I call Add method and return result in lRes and print out result on the console.
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;

Console.WriteLine(lRes.ToString());

Entire Project

using System;
using mcMath;
namespace mcClient
{
///


/// Summary description for Class1.
///

class Class1
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;
Console.WriteLine(lRes.ToString());
}
}
}

Difference Between Namespace and Assembly in C# .Net

Assembly will contain Namespaces, Classes, Data types it’s a small unit of code for deployment. Assembly defines the name of the .dll file.Namespace is used in order to avoid conflict of user defined classes
Namespace:
1) it is a Collection of names wherein each name is Unique.
2) They form the logical boundary for a Group of classes.
3) Namespace must be specified in Project-Properties.
Assembly:
1) It is an Output Unit.
2) It is a unit of Deployment & a unit of versioning.
3) Assemblies contain MSIL code.
4) Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).
7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

Keyboard Shortcuts for Visual c# 2005

The following keyboard shortcuts I find invaluable. It's amazing how many people still use the mouse to do everything.
Document navigation :
Ctrl+Tab Switch documents
Ctrl+Shift+Tab Reverse switch documents
Ctrl+kk Drop a bookmark
Ctrl+kn Itterate through bookmarks
F7 Switch from HTML to Codebehind view
Ctrl+- Navigate backward through last cursor locations
Code Navigation :
F12 Goto Definition
Ctrl+] Jump to matching brace
Editing :
Ctrl+c Copy a whole line
Ctrl+v When a whole line in the clipboard (as above) this will instet a whole copied line.. handy for quick duplication
Ctrl+u Change to lower case
Ctrl+Shift+U Change to UPPER case
Macros :
Ctrl+Shift+R Record a quick Macro
Ctrl+Shift+P Run the quick Macro you just recordedComments
Ctrl+kc Comment out selected lines
Ctrl+ku Uncomment selected lines
Formatting
Ctrl+kd Autoformat selected lines

20.8.08

Get VersionInfo

Steps :
*******
  • In assemblyinfo.cs
    [assembly: AssemblyVersion("x.x.x.x")]
GetVersion Info from any .cs:
**************************
  • System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString(); --Version
  • System.Reflection.Assembly.GetEntryAssembly().GetName().Name.ToUpper(); --Name

6.8.08

State management in ASP.NET

  • Define state management in ASP.NET

Answer - State management is implemented in order to retain information about the user requests. Web pages are stateless. Each request creates new page without retaining any previous information about the user requests. ASP.NET supports several State management techniques to maintain state information.

State management in ASP.NET can be classified into

Client-side state management & Server-side state management

  • Define each mechanism of Client-side state management and Server-side state management.

Client-side state management

This maintains information on the client's machine using Cookies, View State, and Query Strings.

Cookies.

A cookie is a small text file on the client machine either in the client's file system or memory of client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be disabled on the browser. Thus, you can't rely on cookies for state management.

View State

Each page and each control on the page has View State property. This property allows automatic retention of page and controls state between each trip to server. This means control value is maintained between page postbacks. Viewstate is implemented using _VIEWSTATE, a hidden form field which gets created automatically on each page. You can't transmit data to other page using view state.

View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive.

View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.// Add item to ViewStateViewState["myviewstate"] = myValue;//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);

Advantages:

Simple for page level data

Encrypted

Can be set at the control level

Disadvantages:

Overhead in encoding View State values.

Makes a page heavy

Querystring

Querystring can maintain limited state information. Data can be passed from one page to another with the URL but you can send limited size of data with the URL. Most browsers allow a limit of 255 characters on URL length.

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.

Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes:string productid;productid=Request.Params["productid"];

Advantages:

Simple to Implement

Disadvantages:

Human Readable

Client browser limit on URL length

Cross paging functionality makes it redundant

Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.

For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server-side state management

As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage of sessions object for state management can create load on server causing performance degradation

Application State

The data stored in an application object can be shared by all the sessions of the application. The application object stores data in the key value pair.

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.

In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea

Application.Lock();

Application["mydata"]="mydata";

Application.UnLock();

Session State

Session state stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application's configuration settings. By default, SessionID values are stored in a cookie.

Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.

Configuration information: cookieless = <"true" "false"> timeout = sqlconnectionstring= server = port =

Mode:This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:This identifies the database connection string that names the database used for mode SQLServer.

Server:In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

In process mode:

In process mode (in-memory)- State information is stored in memory of web server.This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server

Advantages:

Fastest mode

Simple configuration

Disadvantages:

Session data will be lost if the worker process or application domain recycles

Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):

session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line. This mode is ideal for scalable and highly available applications.

Advantages:

Supports web farm and web garden configuration

Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state

Disadvantages:

Out-of-process mode provides slower access compared to In processRequires serializing data

Database

Database can be used to store large state information. Database support is used in combination with cookies or session state.

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.

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.