Saturday, November 21, 2009

Difference in .Net

csharpwithdj.blogspot.com
What is the difference between a Thread and Process?
A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution.

When a thread begins to execute, it continues until it is killed or until it is interrupted by a thread with higher priority (by a user action or the kernel’s thread scheduler). Each thread can run separate sections of code, or multiple threads can execute the same section of code. Threads executing the same block of code maintain separate stacks. Each thread in a process shares that process’s global variables and resources.

What is the difference between System.Array.CopyTo and System.Array.Clone in .NET?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy.

What is the difference between a DataReader and Dataset in ADO.NET?
A DataReader works in a connected environment, whereas DataSet works in a disconnected environment. A DataReader object represents a forward only, read only access to data from a source. It implements IDataReader & IDataRecord interfaces. For example, The SQLDataReader class can read rows from tables in a SQL Server data source. It is returned by the ExecuteReader method of the SQLCommand class, typically as a result of a SQL Select statement. The DataReader class' HasRows property can be called to determine whether the DataReader retrieved any rows from the source. This can be used before using the Read method to check whether any data has been retrieved.

Example

Dim objCmd as New SqlCommand("Select * from t_Employees", objCon)

objCon.Open()

Dim objReader as SqlDataReader

objReader =

objCom.ExecuteReader(CommandBehavior.CloseConnection)

If objReader.HasRows = True then

Do While objReader.Read()

ListBox1.Items.Add(objReader.GetString(0) & vbTab & objReader.GetInt16(1))

Loop

End If

objReader.Close()

(NOTE: XmlReader object is used for Forward only Read only access of XML).

A DataSet represents an in-memory cache of data consisting of any number of inter-related DataTable objects. A DataTable object represents a tabular block of in-memory data. Further, a DataRow represents a single row of a DataTable object. A Dataset is like a mini-database engine, but its data is stored in the memory. To query the data in a DataSet, we can use a DataView object.

Example

Dim objCon as SqlConnection = New SqlConnection("server=(local);database=NameOfYourDb;user id=sa; password=;)

Dim da as New SqlDataAdapter
Dim ds as DataSet = New DataSet
da.SelectCommand.Connection = objCon
'The Data Adapter manages on its own, opening & closing of connection object
da.SelectCommand.CommandText = "Select * from t_SomeTable"
da.Fill(ds,"YourTableName")

Suppose you want to bind the data in this dataset to a gridview

Gridview1.DataSource = ds
Gridview1.DataMember = "YourTableName"
Gridview1.Databind()

What is the difference between ExecuteScalar and ExecuteNonQuery? What is ExecuteReader?
ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.

ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example:

SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);

//note that con is the connection object

con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets
executed

ExecuteReader - This method returns a DataReader which is filled with the data that is retrieved using the command object. This is known as a forward-only retrieval of records. It uses our SQL statement to read through the table from the first to the last record.

What is the difference between Authorization and Authentication?
Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement.

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system.

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. When a user logs on to an application/system, the user is first Authenticated, and then Authorized.

ASP.NET has 3 ways to Authenticate a user:

1) Forms Authentication
2) Windows Authentication
3) Passport Authentication (This is obsolete in .NET 2.0)
The 4th way is "None" (means no authentication)

The Authentication Provider performs the task of verifying the credentials of the user ans decides whether a user is authenticated or not. The authentication may be set using the web.config file.

Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS.

There are 4 types of Windows Authentication methods:

1) Anonymous Authentication - IIS allows any user
2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure).
3) Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above
4) Integrated Windows Authentication - Relies on Kerberos technology, with strong credential encryption

Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information.

Authorization in .NET - There are two types:

FileAuthorization - this depends on the NTFS system for granting permission
UrlAuthorization - Authorization rules may be explicitly specified in web.config for different web URLs.

What is the difference between Server.Transfer and Response.Redirect?
Both "Server" and "Response" are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is an underlying difference.

//Usage of Server.Transfer & Response.Redirect

Server.Transfer("Page2.aspx");
Response.Redirect("Page2.aspx");

The Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this established standard works very well. By the time Page2 is requested, Page1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.

The more efficient Server.Transfer method simply renders the next page to the browser without an extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because it’s still in memory. This technique would be ideal if it wasn’t for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still show “Page1.aspx” even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. This may occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of touch with the server. Say, the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing. In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may be the deciding factor in choosing.

What is the difference between Trace and Debug?
Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and

System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds. Tracing is actually the process of collecting information about the program's execution. Debugging is the process of finding & fixing errors in our program. Tracing is the ability of an application to generate information about its own execution. The idea is that subsequent analysis of this information may help us understand why a part of the application is not behaving as it should and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in .NET via the System.Web.TraceContext class via the System.Diagnostics.Trace and System.Diagnostics.Debug classes. Tracing can be thought of as a better alternative to the response.writes we used to put in our classic ASP3.0 code to help debug pages.

If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output is appended in the web form output. Messeges can be displayed in the Trace output using Trace.Warn & Trace.Write.

NOTE The only difference between Trace.Warn & Trace.Write is that the former has output in red color. If the trace is false, there is another way to enable tracing. This is done through the application level. We can use the web.config file and set the trace attribute to true. Here we can set

Note that the Page Directive Trace attribute has precedence over th application level trace attribute of web.config. While using application level tracing, we can view the trace output in the trace.axd file of the project.

What is the difference between Web Services and Remoting?
Both Remoting and Web Services are ways of communication between applications.
Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.

Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.

Here are some of the major differences:

* ASP.NET Web Services may be accessed using HTTP only.

Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP

* Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation

* ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.

* Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.

* In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET.

But while implementing Remoting in .NET, both the applications must be built in .NET.

* Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.

What is the difference between String and StringBuilder?
Both String and StringBuilder are classes used to handle strings.

The most common operation with a string is concatenation. This activity has to be performed very efficiently. When we use the "String" object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted. This process is a little long. Hence we say "Strings are immutable".

When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed.

What is the difference between a Class Library and a Namespace?
Class Library is another major entity of the .NET Framework (the other being the CLR). This library gives the program access to runtime environment. The class library consists of lots of prewritten code that all the applications created in .NET will use. The code for all the elements like forms, controls actually comes from the class library. The main class library in .NET is mscorlib.dll. This library contains a large number of core types that encapsulate a wide variety of common tasks. When a .NET application, there is automatic access to this library. We may view the class libraries provided by the .NET Framework by seeing the Global Assembly Cache (Go to C:\Windows\Assembly OR C:\Winnt\Assembly).

Namespace is a grouping of related types contained in an assembly. For example, the System.Drawing namespace consists of classes, methods that are grouped together to achieve similar tasks.

Note that a single assembly like mscorlib.dll may contain any number of namespaces. In fact, namespaces may be nested (means a namespace within a namespace) to arrange classes in a hierarchical fashion. Also note that any language, that works on the .NET environment, targets the same set of namespaces & types provided by the .NET framework.

What is the difference between a DLL and an EXE?
In .NET, an assembly may become a DLL or an EXE. Yet, there is a major underlying difference between the two.

An EXE is an executable file, that may run on its own. Its independant. Where as a DLL is a Dynamic Link Library, that binds to an exe, or another DLL at runtime.

A DLL has an exposed interface, through which members of the assembly may be accessed by those objects that require it.

A DLL runs in tandem with the application space in memory, as the application references it. Whereas an EXE is independant, and runs as an independant process.

What is the difference between value type and reference type? Can a value type contain NULL values?
In simple words, all value based types are allocated on the stack, while all reference based types are allocated on the heap. What does this mean? A value type contains the actual value. A reference type contains a reference to the value. When a value type is assigned to another value type, it is copied. When a reference type is assigned to another reference type, a reference is assigned to the value. By saying stack, we mean things are kept one on top of the other. We keep track of each value at the top. By saying heap, we mean things are kept in a mashed order. We keep track of each value by its address, that is referenced by a pointer to it.

All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in System.Object, the base class for all objects which is a reference type itself.

Data types like integers, floating point numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes, Strings, Arrays are examples of Reference Types.

A value type may not contain NULL values. Reference types may contain NULL values.

It is not possible to derive new types from Value Types. This is possible in Reference types. However, Value Types like Structures can implement interfaces.

What is the difference between Shared and Static?
They both mean the same.

Shared is used in VB.NET.
Static is used in C#.

When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example

//Consider writing the following line of code...

Console obj = new Console(); obj.Writeline("Vishal likes static members"); //This line does'nt print

//This does'nt work, because WriteLine is a static method defined in the class Console

//The Console class is a static class

To use static members, give a reference to the exact class, as an instance in this case won't work.

To make this work, write...

Console.Writeline("Vishal likes static members");

To work with members of static classes, no need to create their instances.

Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).

Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.

Note Indexers in C# cannot be declared static.

Note Static member functions cannot access non-static members directly.

Whats the difference between a class and an object?
In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.

Example
Lets create a class named Laptop

public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}
From our code that references this class, we write...

Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor

Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.

What is the difference between Overriding and Shadowing?
Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.

When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base Class member in a derived class, by using the keyword shadows.

The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class. In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.

Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.

Explain the access specifiers Public, Private, Protected, Friend, Internal, Default
The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.

1. PUBLIC

As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.

2. PRIVATE

As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.

3. FRIEND/INTERNAL

Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.

4. PROTECTED

Protected variables can be used within the class as well as the classes that inherites this class.

5. PROTECTED FRIEND/PROTECTED INTERNAL

The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.

6. DEFAULT

A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter.

Default properties do not promote good code readability, so use this option sparingly.

What is the difference between abstract class and interface?
If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:

abstract public class Vehicle { }

Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created. Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method. Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below

Example: Abstract Class with Abstract method

namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}

Example: Abstract Class with Virtual method

namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}

}

Public class Car : Vehicle
{
Public override void Speed()

//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()

}

}

}

An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:

Public interface IVehicle //As a convention, an interface is prefixed by letter I
{

Boolean HasFourWheels()

}
 

  Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.

2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.

3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.

Whats the difference betweeen Structure, Class and Enumeration
Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory.

Classes are Reference-Types, means they are stored as a heap on the memory. Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a structure, but, remember, A No-argument constructor for a structure is not possible. The structure's constructor should always have a parameter. So if we define the following structure

struct MyStruct
{
public int y,z;
}
and we create a structure type
MyStruct st = new MyStruct();
In case of a class, no-argument constructors are possible.
Class is defined using the class keyword.

A struct cannot have an instance field, whereas a class can.
class A
{
int x = 5; //No error
...
}
struct
{
int x = 5; //Syntax Error
}


A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure.

Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1. enum colors {red, green, blue, yellow};

Here, red is 0, green is 1, blue is 2 and so on.

An explicit casting is required to convert an enum value to its underlying type

int x = (int)colors.yellow;


Difference Between Web Services and  Window Services 
An XML Web service is a component that implements program logic and provides functionality for disparate applications. These applications use standard protocols, such as HTTP, XML, and SOAP, to access the functionality. XML Web services use XML-based messaging to send and receive data, which enables heterogeneous applications to interoperate with each other. You can use XML Web services to integrate applications that are written in different programming languages and deployed on different platforms. In addition, you can deploy XML Web services within an ?intranet as well as on the Internet. While the Internet brings users closer to organizations, XML Web services allow organizations to integrate their applications.

Windows services run as background processes. These applications do not have a user interface, which makes them ideal for tasks that do not require any user interaction. You can install a Windows service on any server or computer that is running Windows 2000, Windows XP, or Windows NT. You can also specify a Windows service to run in the security context of a specific user account that is different from the logged on user account or the default computer account. For example, you can create a Windows service to monitor performance counter data and react to threshold values in a database.

Design Pattern Interview Question

What is a Design Pattern?


Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how to solve a problem.

Because design patterns consist of proven reusable architectural concepts, they are reliable and they speed up software development process.

Design Patterns are in a continious phase of evolution, which means that they keep on getting better & better as they are tested against time, reliability and subjected to continious improvements. Further, design patterns have evolved towards targeting specific domains. For example, windows-based bankin applications are usually based on singleton patterns, e-commerce web applications are based on the MVC (Model-View-Controller) pattern.

Design Patterns are categorized into 3 types:

Creational Patterns
Structural Patterns
Behavioral Patterns

What are Creational Design Patterns?

The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of when and how objects are created, keeping in mind whats the best way these objects should be created. Listed below are some of the commonly known Creational Design Patterns:

 Abstract Factory Pattern
Factory Pattern
Builder Pattern
Lazy Pattern
 Prototype Pattern
 Singleton Pattern

Whats the difference between Abstract Factory Pattern and Factory Pattern?

In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component.

In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface comprises of the generic method declarations that are passed on to the sub-components. TNote that not just interfaces, but even abstract classes can provide the platform of creating an application based on the abstract factory pattern. Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like ShouldHavePolice() and ShouldHaveCourts(). There may be several sub-classes like State1Rules, State2Rules etc. created that inheriting the class CentralGovernmentRules, and thu deriving its methods as well.Note that the term "Factory" refers to the location in the code where the code is created.

A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object. Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's constructor. So basically the Factory Pattern is used wherever sub classes are given the priviledge of instantiating a method that can create an object.

Describe the Builder Design Pattern

In a builder design pattern, an object creation process is separated from the object design construct. This is useful becuase the same method that deals with construction of the object, can be used to construct different design constructs.

What is the Lazy Design Pattern?

The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches, object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?

A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent overheads.

What is the Singleton Design Pattern?

The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object needs to perform the role of a coordinator between various instances of the application that depend on a common object, we may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial and Travel based applications where the singleton object consists of the network related information.

A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists, a reference to the existing object is given. A singleton object has one global point of access to it.

An ASP.NET Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web servers. The session state is handled by a Singleton object in

the form of the aspnet_state.exe, that interacts with the ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine one of the web servers shutting down, the singleton object aspnet_state.exe still maintains the session state information across all web servers in the web farm.

In .NET, in order to create a singleton, a class is created with a private constructor, and a "static readonly" variable as the member that behaves as the instance.


What are Structural Design Patterns?

A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an application to interact with each other. Following are some of the commonly known structural patterns:

 Adapter Pattern - Interfaces of classes vary depending on the requirement.
 Bridge Pattern - Class level abstraction is separated from its implementation.
 Composite Pattern - Individual objects & a group of objects are treated similarly in this approach.
Decorator Pattern - Functionality is assigned to an object.
Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
Flyweight Pattern - The concept of sharing a group of small sized objects.
Proxy Pattern - When an object is complex and needs to be shared, its copies are made.

These copies are called the proxy objects.

What are the different types of Proxy Patterns?

1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a same machine.

2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.

3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example,

in ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the ASP.NET web server.


What is a behavioral design pattern?

Behaviorial design patterns focus on improving the communication between different objects.

Following are different types of behavioral patterns:

 Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions made by a class.

 Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.  Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.


What is the MVC Pattern (Model View Controller Pattern)?

The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set of re-usable classes like classes pertaining to data access, custom control classes, application configuration classes etc. The Controller component interacts with the Model whenever required. The control contains events and methods inside it, which are raised from the UI which is the View component.Consider an ASP.NET web application. Here, all aspx, ascx, master pages represent the View.The code behind files (like aspx.cs, master.cs, ascx.cs) represent the Controller.The classes contained in the App_Code folder, or rather any other class project being referenced from this application represent the Model component.


Advantages: * Business logic can be easily modified, without affecting or any need to make changes in the UI.

* Any cosmetic change in the UI does not affect any other component.


What is the Gang of Four Design Pattern?

The history of all design patterns used in modern day applications derive from the Gang of Four (GoF) Pattern. Gang of Four patterns are categorized into 3 types:

1 - Creational
2 - Structural
3 - Behavioral

The term "Gang of Four" (or "GoF" in acronym) is used to refer to the four authors of the book Design Patterns: Elements of Reusable Object-Oriented Software. The authors are Erich Gamma, Ralph Johnson, Richard Helm and John Vlissides.


When should design patterns be used?

While developing software applications, sound knowledge of industry proven design patterns make the development journey easy and successful. Whenever a requirement is recurring, a suitable design pattern should be identified. Usage of optimal design patterns enhance performance of the application. Though there are some caveats. Make sure that there are no overheads imposed on a simple requirement, which means that design patterns should not be unnecessarily be used.


How many design patterns can be created in .NET?

As many as one can think. Design patterns are not technology specific, rather their foundation relies on the concept of reusability, object creation and communication. Design patterns can be created in any language.


Describe the Ajax Design Pattern.

In an Ajax Design Pattern, partial postbacks are triggered asyncronously to a web server for getting live data. A web application would not flicker here, and the web site user would not even come to know that a request is being sent to the web server for live data. Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Webites for live news, Sports websites for live scores etc.

Wednesday, November 11, 2009

How to: Schedule a Job (SQL Server Management Studio)

csharpwithdj.blogspot.com

How to: Schedule a Job (SQL Server Management Studio)
This topic describes how to schedule a SQL Server Agent job. Before running the procedure in this topic, review Creating and Attaching Schedules to Jobs.

To create and attach a schedule to a job

1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.

2. Expand SQL Server Agent, expand Jobs, right-click the job you want to schedule, and click Properties.

3. Select the Schedules page, and then click New.

4. In the Name box, type a name for the new schedule.

5. Clear the Enabled check box if you do not want the schedule to take effect immediately following its creation.

6. For Schedule Type, select one of the following:

• Click Start automatically when SQL Server Agent starts to start the job when the SQL Server Agent service is started.

• Click Start whenever the CPUs become idle to start the job when the CPUs reach an idle condition.

• Click Recurring if you want a schedule to run repeatedly. To set the recurring schedule, complete the Frequency, Daily Frequency, and Duration groups on the dialog.

• Click One time if you want the schedule to run only once. To set the One time schedule, complete the One-time occurrence group on the dialog.

To attach a schedule to a job

1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.

2. Expand SQL Server Agent, expand Jobs, right-click the job that you want to schedule, and click Properties.

3. Select the Schedules page, and then click Pick.

4. Select the schedule that you want to attach, and then click OK.

5. In the Job Properties dialog box, double-click the attached schedule.

6. Verify that Start date is set correctly. If it is not, set the date when you want for the schedule to start, and then click OK.

7. In the Job Properties dialog box, click OK.

Monday, November 2, 2009

ASP .Net Interview Question

csharpwithdj.blogspot.com

1.What are steps in an asp .net page lifecycle?


Init() - when the page is instantiated

Load() - when the page is loaded into server memory

PreRender() - the brief moment before the page is displayed to the user as HTML

Unload() - when page finishes loading.

2.What is the main difference between Response.Write() and Response.Output.Write()?

With Response.Outout.Write options are available to you to write the formatted out put.

3.When implementing classes what are the specifics of an abstract method?

An Abstract method does not provide any implementation. The class containing it can not be instantiated it must be inherited. The deriving class must override abstract methods declared in parent class, unless it is an abstract class it self.

4.List all Validation Controls available in asp .net?

RequiredFieldValidator : Checks if a control has a value.

RangeValidator : Checks if the control’s value is within a certain range.

RegularExpressionValidator : Checks whether the value of an input control matches a certain pattern

CompareValidator : Checks a control’s value against a constant or another control value.

CustomValidator : Checks a control’s value against a customized validation logic.

ValidationSummary : Displays a list of all validation errors

5.What data types do the RangeValidator control support?

Integer, String, and Date.

6.Is C# .net case sensitive?

Yes it is.

7.What is the difference between a class and struct ?

A struct is a value type while a class is a reference type. There’s no inheritance with struct.


8.When passing a variable by reference to a method what is the difference between keywords ref and out?

When using the key word ref the variable must be initialize before calling the method,

while initialization is not mandatory when using out.

9.What are specifics for Static class?

Static class is implemented with the Keyword Static in the class definition.

It must contain only static members and methods. Public members of static class can be accessed without the class instantiation. Static class are sealed by default therefore can not be inherited. Static class cannot be instantiated.

10.What part of the code is usually called Code-Behind?

The Server side code is usually called Code-behind as reference to the fact that in a web application it is actually the part of the code handling the large part of the execution.

11.What part of the code is called Inline Code?

The asp .net client side code is usually call inline code. From most browsers it can be

view by choosing 'View source' from the page menu.

12.What is the difference between doing a Dataset.Clone() and Dataset.Copy()?

Dataset.Clone() will copy just the dataset structure including all the datatables,

schemas, relations and constraints; it will not copy the data. Dataset.Copy() will copy

both dataset structure and data.

13.What is the role of Global.asax file?

The Global.asax include its code behind file Global.asax.cs, it is use to implement

application and session level events.

14.What utility is used to manually deploy an assembly?

The GacUtil is a utility tool that comes with visual studio, it is use to deploy an

assembly by adding it into the GAC(Global Assembly Cache).

Ex: Type at the command line prompt

C:\gacutil /i ASPMyComponent.dll

will install ASPMyComponent into the GAC

15.Define MSIL. How is it use in the .Net framework?

MSIL stand for Microsoft Intermediate Language. During the compilation process, code written in any .NET compatible languages(J#, C#, VB,C++) is converted into MSIL. MSIL then create a compatibility bridge among these language before execution by the virtual machine.

16. What are differences between ASP.Net and Classic ASP?

-ASP programming is based on scripting languages like Jscript or VBScript which evolves around a mixture of scripting and HTML. ASP .net is base on an advance structured compiled language.

-ASP .net gives the option of separating the code behind (compiled code) from the design code or client code (HTML).

-ASP .net with visual studio .net provides an advanced application and session state

management, while ASP performs poorly at providing it.

-ASP has a poor error handling capability compare to ASP .net which has it much completed and much advanced.

-ASP does not have a built-in mechanism for XML while ASP .net comes with a full XML capability support.

-ASP .net has a fully distributed data source support which is missing from classic ASP

17.What property is use to set alternate color scheme in a Repeater control?

AlternatingItemTemplate.

18.What is the base class for Web Forms?

The System.Web.UI.Page class.

19.What are the meaning of terms boxing and un-boxing?

Boxing: Implicit conversion of a value type into a reference type.

Un-Boxing: Explicit conversion of a reference type into a value type. Can also be call casting.

20.Give a brief description of how the heap and stack are managed in .Net.

Stack and heap are memory sections of the .net application. The CLR(Common Language Runtime) is in charge of managing those sections.

Value type variables are stored in the stack where storing order is Last in first out.

When a variable is out of scope it basically fall off the stack.

Refence type variable are stored on the heap where storing order is First in first out.

When a variable becomes out of scope it is mark for collection.

The GC(Garbage Collector) is the part of the CLR responsible for cleaning up the heap releasing resources occupied by Reference type variables.

21.What is the difference between login controls and Forms authentication?

Login control provides form authentication. If we implement for authentication through form authentication then we do it through code. On the other hand, login control allows the easy implementation...............
22.What is Fragment Caching in ASP.NET?

.Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing the page in different parts............

23.What is partial classess in .net?

When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers............
24.Explain how to pass a querystring from an .asp page to aspx page.

.From HTML in asppage:Test Query String

From server side code: ...............
25.What is a ViewState?

.If a site happens to not maintain a ViewState, then if a user has entered some information in a large form with many input fields and the page is refreshes, then the values filled up in the form are lost...........

26.What is the difference between src and Code-Behind?

.With the ‘src’ attribute, the source code files are deployed and are compiled by the JIT as needed.

Though the code is available to everyone with an access to the server (NOT anyone on the web)................

27.What is the difference between URL and URI?

.A URL (Uniform Resource Locator) is the address of some resource on the Web. A resource is nothing but a page of a site. There are other type of resources than Web pages, but that's the easiest conceptually...........

28.What is the Pre-Compilation feature of ASP.NET 2.0?

.Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient............

29.How can we create custom controls in ASP.NET?

.Custom controls are user defined controls. They can be created by grouping existing controls, by deriving the control from System.Web.UI.WebControls..........

30.What is an application domain?

.It's a way in CLR to maintain a boundary between various applications to ensure that they do not interfere in working of any other application...........

31.Explain the two different types of remote object creation mode in .NET. [Hint SAO and CAO]

.SAO Server Activated Object (call mode): lasts the lifetime of the server. They are activated as SingleCall/Singleton objects. It makes objects stateless...........

32.Describe SAO architecture of Remoting.

.Remoting has at least three sections:-

1. Server

2. Client: This connects to the hosted remoting object

3. Common Interface between client and the server .i.e. the channel..........

33.Explain Singleton architecture of Remoting.

.Singleton architecture is to be used when all the applications have to use or share same data...........

34.Define LeaseTime, SponsorshipTime, RenewOnCallTime, LeaseManagePollTime.

.The LeaseTime property protects the object so that the garbage collector does not destroy it as remoting objects are beyond the scope of the garbage collector. Every object created has a default leasetime for which it will be activated..........

35.Briefly explain how to specify remoting parameters using config files.

.The remoting parameters can be specified through both programming and in config files. All the settings defined in config files are placed under ...........

36.What is marshalling? Explain types of marshalling.

.Marshaling is a process of transforming or serializing data from one application domain and exporting it to another application domain...........

37.What is ObjRef object in remoting?

.ObjRef is a searializable object returned by Marshal() that knows about location of the remote object, host name, port number, and object name........

38.Explain the steps of acquiring a proxy object in web services.

.Every service listed has a URI pointing to the service's DISCO or WSDL document, which is needed to access the webservice and its 'webmethod" methods..........

39.Explain the steps to create a web services and consume it.

.Create a new website by selecting "ASP.NET Web Site" and giving it a suitable name. service.cs file appears inside the solution with a default webmethod named as "HelloWorld()"........
40.Explain the difference between cache object and application object.

.Application Object: Application variable/object stores an Object with a scope of availability of the entire Application unless explicitly destroyed.............
41.What is Cache Callback in Cache?

.The cache object has dependencies e.g. relationships to the file it stores. Cache items remove the object when these dependencies change. As a work around we would need to simply execute a callback method............

42.What is Scavenging?

.A process where items are removed from cache in order to free the memory based on their priority. A property called "CacheItemPriority" is used to figure out the priority of each item inside the cache...........

43.Explain the types of Caching using Cache object of ASP.NET.

.Page output: Is used to fetch information or data at page level. It is best used when the site is mainly static. Used by declaring the output page directive............

44.Show with an example how to Cache different version of same page using ASP.NET Cache object.

.The ways to cache different versions on the same page using ASP.NET cache object is using OutputCache object............

45.Explain how to implement Fragment Cache.

.Fragment cache is to store user controls individually within a web form in cache instead of the whole webform as such. The idea is to simply have different cache parameters for different user controls.............

46.Explain the various modes of storing ASP.NET session.

.Types of sessions: InProc: The default way to use sessions. InProc is the fastest way to store and access sessions...........

47.What are the benefits and limitations of using hidden fields?

.Advantages: Easy to implement, Hidden fields are supported by all browsers, Enables faster access of information because data is stored on client side............

48.What are the benefits and limitations of using Hidden Frames?

.Advantages: Hidden frames allow you to cache more than one data field, The ability to cache and access data items stored in different hidden forms...........

49.What are benefits and limitations of using Cookies?

.Advantages: They are simple to use. Light in size, thus occupy less memory. Stores server information on client side. Data need not to be sent back to server........

50.What is QueryString and what are benefits and limitations of using querystring?

.Querystring is way to transfer information from one page to another through the URL........
51.What is Absolute and Sliding expiration in .NET?

.Absolute and sliding expiration are two Time based expiration strategies. Absolute Expiration: Cache in this case expires at a fixed specified date or time..............

52.Explain the concepts and capabilities of cross page posting.

.Cross-page posting is done at the control level. It is possible to create a page that posts to different pages depending on what button the user clicks on. It is handled by done by changing the postbackurl property of the controls..........

53.Explain how to access ViewState value of this page in the next page.

.PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page. Page poster = this.PreviousPage;..........

54.What is SQL Cache Dependency in ASP.NET?

.SQL Cache Dependency in ASP.NET: It is the mechanism where the cache object gets invalidated when the related data or the related resource is modified.........

55.Explain the concepts of Post Cache Substitution in .NET

.Post Cache Substitution: It works opposite to fragment caching. The entire page is cached, except what is to be kept dynamic. When [OutputCache] attribute is used, the page is cached............

56.Explain the use of localization and Globalization.

.Users of different countries, use different languages and others settings like currency, and dates. Therefore, applications are needed to be configurable as per the required settings based on cultures, regions, countries........

57.Explain the concepts of CODE Page approach. What are the disadvantages of this approach?

.Code Page was used before Unicode came into existence. It was a technique to represent characters in different languages..........

58.What are resource files and explain how do we generate resource files?

.Resource files are files in XML format. They contain all the resources needed by an application. These files can be used to store string, bitmaps, icons, fonts........
59.What are Satellite assemblies and how to generate Satellite assemblies?

.To support the feature of multiple languages, we need to create different modules that are customized on the basis of localization. These assemblies created on the basis of different modules are knows as satellite assemblies...........

60.Define AL.EXE and RESGEN.EXE.

.Al.exe: It embeds the resources into a satellite assembly. It takes the resources in .resources binary format.......

61.Explain the concepts of resource manager class.

.ResourceManager class: It provides convenient access to resources that are culture-correct. The access is provided at run time.........

62.What is Windows communication foundation, WCF?

.WCF is a framework that builds applications that can inter-communicate based on service oriented architecture consuming secure and reliable web services.............

63.Explain the important principle of SOA.

.A service-oriented architecture is collection of services which communicate with one another other......

64.Explain the components of WCF - Service class, Hosting environment, END point.

.WCF Service is composed of three components: Service class: It implements the service needed, Host environment: is an environment that hosts the developed service.............

65.Difference between WCF and Web Services.

.WCF can create services similar in concept to ASMX, but has much more capabilities. WCF is much more efficient than ASP.Net coz it is implemented on pipeline............

66.What are different bindings supported by WCF?

.BasicHttpBinding, WSHttpBinding, WSDualHttpBinding.......

67.What is duplex contract in WCF?

.Duplex contract: It enables clients and servers to communicate with each other. The calls can be initiated independently of the other one.............

68.Explain the different transaction isolation levels in WCF.

.Read Uncommitted: - Also known as Dirty isolation level. It makes sure that corrupt Data cannot be read. This is the lowest isolation level............

69.What are Volatile and Dead letter queues?

.Volatile Queues: There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is very more important and to ensure they are not lost is important too. Volatile queues are used for such purposes.............

70.What is Windows workflow foundation?

.Windows Workflow Foundation (WF): It is a platform for building, managing and executing workflow-enabled applications, for designing and implementing a programming model ..........

71.Explain the types of Workflow in Windows Workflow Foundation.

.There are 3 types of workflows in WWF: Sequential Workflow: The sequential workflow style executes a set of contained activities in order, one by one and does not provide an option to go back to any step...........

72.What are XOML files? Explain their uses.

.XOML is an acronym for Extensible Object Markup Language. XOML files are the markup files. They are used to declare the workflow and are then compiled with the file containing the implementation logic..............





C# Interview Question

1. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

2. Can you store multiple data types in System.Array?
No.


3. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
 The first one performs a deep copy of the array, the second one is shallow.

4. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

5. What’s the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

6. What’s class SortedList underneath?
 A sorted HashTable.

7. Will finally block get executed if the exception had not occurred?
Yes.

8. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

9. Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

10. Why is it a bad idea to throw your own exceptions?
 Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

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

12. What’s a multicast delegate?
 It’s a delegate that points to and eventually fires off several methods.

13. How’s the DLL Hell problem solved in .NET?
 Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

14. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.

15. What’s a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

16. What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.

17. What’s the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

18. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with a /doc switch.

19. What’s the difference between and XML documentation tag?
Single line code example and multiple-line code example.

20. Is XML case-sensitive?
Yes, so and are different elements.

21. What debugging tools come with the .NET SDK?
CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

22. What does the This window show in the debugger?
It points to the object that’s pointed to by this reference. Object’s instance data is shown.

23. What does assert() do?
 In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

24. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

26. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

27. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

28. What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

29. Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

30. Explain the three services model (three-tier application).
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

31. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

32. What’s the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.

33. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

34. Explain ACID rule of thumb for transactions.
 Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

35. What connections does Microsoft SQL Server support?
 Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

36. Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

37. Why would you use untrusted verificaion?
Web Services might use it, as well as non-Windows applications.

38. What does the parameter Initial Catalog define inside Connection String?
The database name to connect to.

39. What’s the data provider name to connect to Access database?
Microsoft.Access.

40. What does Dispose method do with the connection object?
Deletes it from the memory.

41. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

42. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

43. Why does DllImport not work for me?
 All methods marked with the DllImport attribute must be marked as public static extern.

44. Why does my Windows application pop up a console window every time I run it? 
 Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.

45. Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)

46. Why do I get a syntax error when trying to declare a variable called checked? 
 The word checked is a keyword in C#.

47. Why do I get a security exception when I try to run my C# app?
 Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.

48. Why do I get a CS5001: does not have an entry point defined error when compiling? 
 The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }

49. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? 
 The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

50. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }

51. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? 
 Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.

52. What is the difference between a struct and a class in C#?
From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

53. My switch statement works differently than in C++! Why? 
 C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

switch(x)

{

case 0: // do something

case 1: // do something as continuation of case 0

default: // do something in common with

//0, 1 and everything else

break;

}

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test

{

public static void Main() {

int x = 3;

switch(x)

{

case 0: // do something

goto case 1;

case 1: // do something in common with 0

goto default;

default: // do something in common with 0, 1, and anything else

break;

}

}

}

54. Is there regular expression (regex) support available to C# developers? 
 Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.

55. Is there any sample C# code for simple threading? 
 Yes:

using System;

using System.Threading;

class ThreadTest

{

public void runme()

{

Console.WriteLine("Runme Called");

}

public static void Main(String[] args)

{

ThreadTest b = new ThreadTest();

Thread t = new Thread(new ThreadStart(b.runme));

t.Start();

}

}

56. Is there an equivalent of exit() for quitting a C# .NET application? 
 Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.

57. Is there a way to force garbage collection?
Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().

58. Is there a way of specifying which block or loop to break out of when working with nested loops? 
 The easiest way is to use goto:

using System;

class BreakExample

{

public static void Main(String[] args) {

for(int i=0; i<3; i++)

{

Console.WriteLine("Pass {0}: ", i);

for( int j=0 ; j<100 ; j++ )

{

if ( j == 10)

goto done;

Console.WriteLine("{0} ", j);

}

Console.WriteLine("This will not print");

}

done:

Console.WriteLine("Loops complete.");

}

}

59. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? 
 There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

60. What is the modifier protected internal in C#?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself. In VB.NET, the equivalent of protected internal is protected friend.The access of this modifier is limited to the current assembly or the types derived from the defining class in the current
assembly.

Collection in C#

csharpwithdj.blogspot.com
The .NET Framework has powerful support for Collections. Collections are enumerable data structures that can be assessed using indexes or keys. This article discusses Collections in .NET with code examples.


The System.Collections namespace

The System.Collections namespace provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. The interfaces that are defined in this namespace include:

• IEnumerable

• IEnumerator

• ICollection

• IList

• IDictionary

The following are the classes that are derived from the ICollection interface.

• System.Collections.Stack

• System.Collections.Queue

• System.Collections.BitArray

• System.Collections.Specialized.NameValueCollection

The IDictionary interface represents collections that have name value pairs. The collections that inherit the IDictionary interface include:

• System.Collections.SortedList

• System.Collections.Hashtable

• System.Collections.Specialized.HybridDictionary

• System.Collections.Specialized.ListDictionary

The IList interface represents collections that only have value. The following are the classes that extend this interface.

• System.Array

• System.Collections.ArrayList

• System.Collections.Specialized.StringCollection

The IEnumerable Interface

An enumerator is an object that provides a forward, read-only cursor for a set of items. The IEnumerable interface has one method called the GetEnumerator() method. This method returns an object that implements the IEnumerator interface. The code snippet below illustrates how an enumerator can be used to iterate though a list or collection of items.

Listing 1

String names[]=new String[2] {”Joydip”,”Jini”};

for(IEnumerator e =names.GetEnumerator();e.MoveNext();Response.Write(e.Current));

Note that the GetEnumerator() method returns an enumerator object each time it is called. Further, the loop contains the Response.Write statement in its re-initializer portion, which is perfectly valid. The condition being evaluated is whether the MoveNext() method returns a value of true. The MoveNext() method returns true as long as there are items in the collection. The Current property returns the current object and is automatically typecast to string by making a call to the ToString() method implicitly.

The foreach method can also be used in this case, as it calls the enumerator implicitly. The above code can be re-written using a foreach loop as follows:

Listing 2

String names[]=new String[2] {”Joydip”,”Jini”};

foreach(string str in names)

Response.Write(str);

ArrayList

The ArrayList class is a dynamic array of heterogeneous objects. Note that in an array we can store only objects of the same type. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only. We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object type. An ArrayList uses its indexes to refer to a particular object stored in its collection. The Count property gives the total number of items stored in the ArrayList object. The Capacity property gets or sets the number of items that the ArrayList object can contain. Objects are added using the Add() method of the ArrayList and removed using its Remove() method. An example of usage of an ArrayList is given below.

Listing 3

using System;
using System.Collections;
class Test
{

static void Main()

{

int i = 100;
double d = 20.5;
ArrayList arrayList = new ArrayList();
arrayList.Add("Joydip");
arrayList.Add(i);
arrayList.Add(d);
for (int index = 0; index
Console.WriteLine(arrayList[index]);
}

}

It is to be noted here that the initial capacity of an ArrayList is 16, which is increased once the 17th item is stored onto it. This repeated memory allocation and copying of the items can be quite expensive in some situations. For performance reasons we can set the initial capacity of the object of an ArrayList by using the Capacity property or an overloaded constructor of the ArrayList class. This is shown in the example below.

Listing 4

using System;

using System.Collections;

class Test

{

static void Main()

{

int i = 100;

double d = 20.5;
ArrayList arrayList = new ArrayList();

arrayList.Capacity = 2;

arrayList.Add("Joydip");

arrayList.Add(i);

arrayList.Add(d);

for (int index = 0; index

Console.WriteLine(arrayList[index]);

}

}

StringCollection

The StringCollection class implements the IList interface and is like an ArrayList of strings. The following code example shows how we can work with a StringCollection class.

Listing 5

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

StringCollection stringList = newStringCollection();

stringList.Add("Manashi");

stringList.Add("Joydip");

stringList.Add("Jini");

stringList.Add("Piku");

foreach (string str in stringList)

{

Console.WriteLine(str);

}

}

}

StringDictionary

Similar to the StringCollection class we have the StringDictionary class, which is just a Hashtable that has its keys as strings only. Remember that a Hashtable can contain any object type in its key. The following code shows how we can work with a StringDictionary class.

Listing 6

using System;
using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

StringDictionary stringList = newStringDictionary();

stringList.Add("A", "Manashi");

stringList.Add("B","Joydip");

stringList.Add("C","Jini");

stringList.Add("D","Piku");
foreach (string str in stringList.Values)

{

Console.WriteLine(str);

}



}

}

Stack

The Stack class is one that provides a Last-in-First-out (LIFO) collection of items of the System.Object type. The last added item is always at the top of the Stack and is also the first one to be removed. The following code sample shows how we can use a Stack class for LIFO operation on its collection of items.

Listing 7

using System;

using System.Collections;

class Test

{

static void Main()

{

Stack stackObject = new Stack();

stackObject.Push("Joydip");

stackObject.Push("Steve");

stackObject.Push("Jini");

while (stackObject.Count > 0)

Console.WriteLine(stackObject.Pop());

Console.ReadLine();

}

}

The Push() method is responsible for storing items in the Stack and the method Pop() removes them one at a time from the top of the Stack.

Queue

Unlike the Stack class, the Queue is a data structure that provides a First-in-First-out collection of items of the System.Object type. The newly added items are stored at the end or the rear of the Queue and items are deleted from the front of the Queue. The following code shows how the Queue class can be used.

Listing 8

using System;
using System.Collections;

class Test

{

static void Main()

{

Queue queueObject = new Queue();

queueObject.Enqueue("Joydip");

queueObject.Enqueue("Steve");

queueObject.Enqueue("Jini");

while (queueObject.Count > 0)

Console.WriteLine(queueObject.Dequeue());

Console.ReadLine();

}

}

The Enqueue() method is responsible for storing items at the rear of the Queue and the method Dequeue() removes them one at a time from the front of the Queue.

BitArray

The BitArray class can be used to store bits in an array. They can be set to true or false, depending on the parameter supplied at the time of creating the BitArray object. The following is an example of its usage.

BitArray bitArray = new BitArray(5,false);

Or

BitArray bitArray = new BitArray(5,true);

Similar to the other collections discussed above, the BitArray class also contains the Count property to get the number of items stored in this collection of bit values. The following methods of the BitArray class allow logical bit operation.

• And

• Or

• Not

• Xor

Hashtable

The Hashtable provides a faster way of storage and retrieval of items of the object type. The Hashtable class provides support for key based searching. These keys are unique hash codes that are unique to a specific type. The GetHashCode() method of the Hashtable class returns the hash code for an object instance. The following code snippet shows how we can use a Hashtable class.

Listing 9

using System;
using System.Collections;

class Test

{

static void Main()

{

Hashtable hashTable = new Hashtable();

hashTable.Add(1, "Joydip");

hashTable.Add(2, "Manashi");

hashTable.Add(3, "Jini");

hashTable.Add(4, "Piku");

Console.WriteLine("The keysare:--");

foreach (int k in hashTable.Keys)

{

Console.WriteLine(k);

}

Console.WriteLine("Please enter the keyto search");

int p = int.Parse(Console.ReadLine());

Console.WriteLine(hashTable[3].ToString());

}

}

To remove an item from the Hashtable class, the Remove() method is used. The statement hashTable.Remove(3) would remove the item “Jini” from the Hashtable object created in the above code. The code shown above can also be written as shown below to display the contents of the Hashtable object using IDictionaryEnumerator.

Listing 10

using System;

using System.Collections;

class Test

{

static void Main()

{

Hashtable hashTable = new Hashtable();

hashTable.Add(1, "Joydip");

hashTable.Add(2, "Manashi");

hashTable.Add(3, "Jini");

hashTable.Add(4, "Piku");

Console.WriteLine("The keysare:--");

IDictionaryEnumerator en =hashTable.GetEnumerator();

string str = String.Empty;

while (en.MoveNext())

{

str = en.Value.ToString();

Console.WriteLine(str);

}

}

}

SortedList

The SortedList class allows items of the System.Object type to be placed in the collection using key value pairs and, at the same time, supports sorting. The following code shows how we can use a SortedList.

Listing 11

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

SortedList sortedList = new SortedList();

sortedList.Add(1, "Manashi");

sortedList.Add(3, "Joydip");

sortedList.Add(2, "Jini");

sortedList.Add(4, "Piku");

Console.WriteLine("Displaying thenames");

foreach (string str in sortedList.Values)

{

Console.WriteLine(str);

}

}

}

The output of the above code is:

Manashi

Jini

Joydip

Piku

The same code can be written using IDictionaryEnumerator to display all the items of the SortedList object, as shown below.

Listing 12

using System;

using System.Collections;

using System.Collections.Specialized;

class Test

{

static void Main()

{

SortedList sortedList = new SortedList();

sortedList.Add(1, "Manashi");

sortedList.Add(3, "Joydip");

sortedList.Add(2, "Jini");

sortedList.Add(4, "Piku");

Console.WriteLine("Displaying thenames");

IDictionaryEnumerator en = sortedList.GetEnumerator();

string str = String.Empty;

while (en.MoveNext())

{

str = en.Value.ToString();

Console.WriteLine(str);

}

}

}

Type Safe Collections

Type safe collections are those that comprise of a known type. It would support indexing as an array and has a lot of benefits. A strong typed collection is implemented using any of the following classes.

• CollectionBase

• ReadOnlyCollectionBase

• DictionaryBase

The following are the advantages of using strong typed collections.

• Supports indexing

• Supports enumeration

• Supports dynamic resizing

• Supports serialization

Implementing a Custom Collection Class

The following section shows how we can implement a custom collection class. The following code shows how we can use the "design a custom collection class" by sub-classing the CollectionBase class.

Listing 13

using System;

using System.Collections;

public class Product: CollectionBase

{

public Product this[int index]

{

get

{

return ((Product)(List[index]));

}

set

{

List[index] = value;

}

}

public bool Contains(Product product)

{

return List.Contains(product);

}

public int Add(Product Product)

{

return List.Add(Product);

}

public void Insert(int index, Product product)

{

List.Insert(index, product);

}

public void Remove(Product product)

{

List.Remove(Product);

}

}

The following code shows how we can use the "design a custom collection class" by sub-classing the DictionaryBase class.

Listing 14

using System;

using System.Collections;


public class Product: DictionaryBase

{

public Product this[int index]

{

get

{

return ((Product)(Dictionary[index]));

}

set

{

Dictionary[index] = value;

}

}


public bool Contains(Product product)

{

return Dictionary.Contains(product);

}


public int Add(Product Product)

{

return Dictionary.Add(Product);

}


public void Insert(int index, Product product)

{

Dictionary.Insert(index, product);

}


public void Remove(Product product)

{

Dictionary.Remove(Product);

}

}


Suggested Readings

http://www.15seconds.com/issue/030429.htm

http://www.csharphelp.com/archives/archive183.html

http://www.ondotnet.com/pub/a/dotnet/2003/03/10/collections.html

Conclusion

Though Collections are quite powerful, they should be used judiciously. One should always choose the right type of collection when working with them, as collections can degrade performance due to the overhead involved in boxing and unboxing when used with value types. Try and always choose the simplest collection possible that will provide the functionality required.