Monday, November 28, 2011

Difference between Association, Aggregation and Inheritance relationships.

An Association is a relationship between similar objects or objects with common structures.

Example:
An employee object is associated with manager object.
Aggregation is “a part of” relationship.
Example:
A student object is a part of College object.
Inheritance is a “is a “relationship where one or more classes are derived from a base class. The derived class has the base class plus its own characteristics.
Example:
French_Student class can be a derived class of student class.

Features of Static/Shared classes.

Static classes are used when any change made to an object should not affect the data and functions of the class. They can be used to create data and functions without the need of an instance.

Following are features of Static/Shared classes:-

-They can not be instantiated. By default a object is created on the first method call to that object.
-Static/Shared classes can not be inherited.
-Static/Shared classes can have only static members.
-Static/Shared classes can have only static constructor.

Explain the concepts and capabilities of cross page posting

Cross Page Posting: It refers to the scenario where on event of some controls posts from one page to another instead of a normal postback. Normal postback is when for e.g. a button (or any control that postbacks) is clicked and web page is submits the page back to itself which means a return trip. In Cross page posting, on click of a button there would be no return trip.

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.

What are Extender provider components? Explain how to use an extender provider in the project.

An extender provider is a component that provides properties to other components.

Implementing an extender provider:

•Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider.
•Implement the provided property.
•Track which controls receive your provided property.
•Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.

What is the GAC? What problem does it solve?

Global Assembly Cache (GAC):

Any system that has the CLR (common language runtime) installed, has a machine-wide code cache known as GAC.

Assemblies deployed in the global assembly cache need to have a strong name.

The Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.

What are implementation inheritance and interface inheritance?

Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.

Interface inheritance is when a class inherits only the signatures of the functions from another class.

What is the use of System.Environment class in C#.NET?

The System.Environment class can be used to retrieve information like:
command-line arguments
the exit code
environment variable settings
contents of the call stack
time since last system boot
the version of the common language runtime.

What is the difference between const and readonly in C#.NET?

The read only can be modified by the class it is contained in. However, the const cannot be modified. It needs to be instantiated only at the compile time.

What is strong-typing versus weak-typing? Which is preferred? Why?

In weak typing, it is allowed to define a block of memory as another type (casting).
Languages like C, C++ are weakly and statically typed.
Languages like Perl and PHP are weakly typed as you can add numbers to strings and they will implicitly coerce it.

Languages like Java, C# and Python are strongly typed. In these the type conversion needs to be explicitly handled.

For scripts we use weak typing.

In big programs, we use strong typing which can reduce errors at compile time

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Interface oriented approach compels to develop the software based on the contract.
Object oriented approach emphasizes on its aspects like:
Abstraction
Encapsulation
Inheritance
Polymorphism
Cross cutting concerns cannot be implemented in object oriented programming.
That’s not the case with aspect-oriented. However, there is a risk of system failure in this situation.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

•XML Web services are more restricted than objects exposed over .NET Remoting.
•XML Web services support open standards that target cross-platform use.
•XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
•XML Web services support only SOAP message formatting, which uses larger XML text messages.
•Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
•XML Web services are designed for use between companies and organizations.
•XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
•Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET

How to add a ReadOnly property in C#.NET?

Properties can be made read-only by having only a get accessor in the implementation.

public class X
{
public X(int id)
{
x_id = id;
}
public int ID
{
get
{
return x_id;
}
}
}

How to prevent a class from being inherited in C#.NET?

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

Explain the use of virtual, sealed, override, and abstract.

The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.

The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.

Explain the use of virtual, sealed, override, and abstract.

The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.

The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.

How does the XmlSerializer work? What ACL permissions does a process using it require?

The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.

Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.

The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created

Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications

Explain the difference between Server.Transfer and response.Redirect.

Redirect and Transfer both cause a new page to be processed. The difference lies in the way the interaction between the client and the server occurs.

Response.Redirect messages the client browser asking it to request for another page.
e.g. if a browser is on page A which has a Response.Redirect, then it asked to request for another page B by the server. When the client browser requests for it, then it is provided with the requested page B.

With Server.Transfer, the browser is not requested to ask for another page. Instead it is directly provided with the page B. In this scenario, the browser address bar continues to show the address of the previous URL.

Navigation methods in ASP.NET

Hyperlink control
Response.Redirect method
Server.Transfer method
Server.Execute method
Window.Open method

Hyperlink control
This is server control use for navigation to another page specified in the NavigateURL property. Hyperlink control doesn’t expose any server side event.

Response.Redirect method
This method is used to navigate to another page from code. You can use this method to navigate from a Linkbutton or ImageButton control.
For example

Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Response.Redirect("Page2.aspx")
End Sub

Server.Transfer method
This method can be used only with .aspx file. It allows to retain some information between the requests when its preserveForm argument is set to true.

Server.Execute method
Like Server.Transfer, this method is also used with .aspx file only. This method enables new page execution while still displaying the current web form.

Window.Open method
Display a page in a new browser window on the client.

What are circular references? Explain how garbage collection deals with circular references.

A circular reference is a run-around wherein the 2 or more resources are interdependent on each other rendering the entire chain of references to be unusable.

There are quite a few ways of handling the problem of detecting and collecting cyclic references.

1. A system may explicitly forbid reference cycles.
2. Systems at times ignore cycles when they have short lives and a small amount of cyclic garbage. In this case a methodology of avoiding cyclic data structures is applied at the expense of efficiency.
3. Another solution is to periodically use a tracing garbage collector cycles.
Other types of methods to deal with cyclic references are:
•Weighted reference counting
•Indirect reference counting

What is Finalize method in .NET?

Object.Finalize method in .NET is typically used to clean and release unmanaged resources like OS files, window etc. Even though Garbage collector in .NET has the ability to determine the life time of such objects, however, with no knowledge how to clean them. The Finalize method allows an object to clean up such unmanaged resources when the garbage collector wishes to reclaim the memory. However, Finalize method should be avoided until necessary as it affects the performance because reclaiming the memory used by objects with Finalize methods requires at least two garbage collections.

What is Finalize method in .NET?

Object.Finalize method in .NET is typically used to clean and release unmanaged resources like OS files, window etc. Even though Garbage collector in .NET has the ability to determine the life time of such objects, however, with no knowledge how to clean them. The Finalize method allows an object to clean up such unmanaged resources when the garbage collector wishes to reclaim the memory. However, Finalize method should be avoided until necessary as it affects the performance because reclaiming the memory used by objects with Finalize methods requires at least two garbage collections.

Explain the concepts of CTS and CLS(Common Language Specification).

CTS
When different languages are integrated and want to communicate, it is certain that the languages have their own data types and different declaration styles. CTS define how these different variables are declared and used in run time. E.g. VB offers an Integer data type while C++ offers long data type. Using CTS, these data types are converted to System32 which itself a data type of CLS.

CLS
Any language(s) that intend to use the Common Language Infrastructure needs to communicate with other CLS-Compliant language. This communication is based on set of rules laid by CLS. These rules define a subset of CTS.

Explain different properties of Object Oriented Systems.

An object oriented system revolves around a Class and objects. A class is used to describe characteristics of any entity of the real world. An object is a pattern of the class. An actual object created at runtime is called as an instance. A class, apart from characteristics has some functions to perform called as methods. For.e.g A class named "Food" has attributes like 'price', 'quantity'. "Food" class has methods like Serve_food(), bill_food().

•Objects in Object Oriented Systems interact through messages.
Inheritance:- The main class or the root class is called as a Base Class. Any class which is expected to have ALL properties of the base class along with its own is called as a Derived class. The process of deriving such a class is Derived class. For the "Food" class, a Derived class can be "Class Chinesefood".
Abstraction:- Abstraction is creating models or classes of some broad concept. Abstraction can be achieved through Inheritance or even Composition.
Encapsulation:- Encapsulation is a collection of functions of a class and object. The "Food" class is an encapsulated form. It is achieved by specifying which class can use which members (private, public, protected) of an object.
Polymorphism:- Polymorphism means existing in different forms. Inheritance is an example of Polymorphism. A base class exists in different forms as derived classes. Operator overloading is an example of Polymorphism in which an operator can be applied in different situations.

Difference between abstract classes and interfaces.

When a derived class is inherited from an Abstract class, no other class can be extended then. Interface can be used in any scenario. Abstract class contains abstract method, i.e. actual implementation logic. On the other hand, interfaces have no implementation logic. Every method in an interface must be abstract. This is not necessary in case of abstract classes.

Abstract class in NET

An Abstract class is only used for inheritance. This means it acts as a base class for its derived classes. One cannot use it to create objects. When a class is declared as “Abstract”, it can only be inherited and not instantiated. MustInherit Keyword can be used to declare a class as abstract.
Abstract classes can also specify abstract members.

Abstract class in NET

An Abstract class is only used for inheritance. This means it acts as a base class for its derived classes. One cannot use it to create objects. When a class is declared as “Abstract”, it can only be inherited and not instantiated. MustInherit Keyword can be used to declare a class as abstract.
Abstract classes can also specify abstract members.

How to achieve polymorphism in C#.NET?

Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.

It can be achieved in the following ways:
Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.

To completely take over a class member from a base class, the base class has to declare that member as virtual.

What is QueryString? Benefits and limitations of using querystring.

Advantages:

a. Supported by all the browsers
b. No extra effort is needed to code.
c. Easy to use.

Disadvantages:


a. All the attributes and values are visible to the end user. Therefore, they are not secure.
b. There is a limit to URL length of 255 characters.

Explain when should we use StringBuilder class instead of the String class.

Whenever any of the methods of String class is used to modify the string, a new object is created and memory is allocated to that object. If there are repeated modifications on the string, the performance can get hampered making it costly. Whereas, the StringBuilder class can be used for modifications over and over again without creating a new object. So one situation where a StringBuilder class might be of use is, if we are manipulation string in a loop.

Explain when should we use StringBuilder class instead of the String class.

Whenever any of the methods of String class is used to modify the string, a new object is created and memory is allocated to that object. If there are repeated modifications on the string, the performance can get hampered making it costly. Whereas, the StringBuilder class can be used for modifications over and over again without creating a new object. So one situation where a StringBuilder class might be of use is, if we are manipulation string in a loop.

What are code groups in .NET?

Code group is a logical grouping of code that follows some given conditions for membership. Code groups have some permission sets that are checked before to grant the membership of the code group.

What are code groups in .NET?

Code group is a logical grouping of code that follows some given conditions for membership. Code groups have some permission sets that are checked before to grant the membership of the code group.

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.

Benefit of Primary Interop Assembly (PIA)

A primary interop assembly contains type definitions (as metadata) of types implemented with COM.

Only a single PIA can exist, which needs to be signed with a strong name by the publisher of the COM type library.

One PIA can wrap multiple versions of the same type library.

A COM type library imported as an assembly can be a PIA only if it has been signed and published by the same publisher.

Therefore, only the publisher of a type library can produce a true PIA, that can be considered as the unit of an official type definition for interoperating with the underlying COM types.

Explain why we use XML Serialization

Serialization allows persisting objects. XML serializations stores objects in form of XML which has become a storage standard. The main advantage with XML is that it is platform, language independent. Any other software can practically read XML and write data, hence interoperability is an added advantage with XML serialization. XML also has the power to show relationships between various objects which is also advantageous when performing serialization of objects along with other related objects.

Explain why we use XML Serialization

Serialization allows persisting objects. XML serializations stores objects in form of XML which has become a storage standard. The main advantage with XML is that it is platform, language independent. Any other software can practically read XML and write data, hence interoperability is an added advantage with XML serialization. XML also has the power to show relationships between various objects which is also advantageous when performing serialization of objects along with other related objects.

Why is an object pool required?

The request for the creation of an object is served by allocating an object from the pool.

This reduces the overhead of creating and re-creating objects each time an object creation is required.

To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

How does object pooling and connection pooling differ?

In Object pooling, you can control the number of connections.

In connection pooling, you can control the maximum number reached.

When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.

In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy

What is an object pool in .NET?

An object pool is a container of objects that holds a list of other objects that are ready to be used.

It keeps track of:

•Objects that are currently in use
•The number of objects the pool holds
•Whether this number should be increased
The request for the creation of an object is served by allocating an object from the pool.

This reduces the overhead of creating and re-creating objects each time an object creation is required.

What is the JIT? What is NGEN? What are limitations and benefits of each?

Just In Time Compiler compiles the code just before it is run.
Due to this the code takes longer time to start however it is more efficient compilation since the compiler has more information about the target system.

NGen is used to pre-just in time code which yields faster startup time but the compiler produces less efficient code because it has less information.

Explain the use of static members with example using C#.NET.

Static members are not associated with a particular instance of any class.
They need to be qualified with the class name to be called.
Since they are not associated with object instances, they do not have access to non-static members.
i.e.: "this" cannot be used, which represents the current object instance.

What are generics in C#.NET?

Generic types to maximize code reuse, type safety, and performance.
They can be used to create collection classes.
Generic collection classes in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace.

The classes and the methods can treat the values of different types uniformly with the use if generics.

The usage of generics is advantageous as:

•They facilitate type safety
•They facilitate improved performance
•They facilitate reduced code
•They promote the usage of parameterized types
•The CLR compiles and stores information related to the generic types when they are instantiated. (The generic type instance refers to the location in memory of the reference type to which it is bound for all the instances of the generic type.)

Define most commonly used interfaces in .Net Framework

IComparable: It is implemented by types for ordering and sorting. The implementation types must implement one single method i.e. CompareTo.

IDisposable:This is implemented to manage release of unmanaged resources from memory. The garbage collector acts on its own and hence the Dispose method is used to call the garbage collector to free unmanaged resources through this interface.

IConvertible: It is implemented to convert value of the implementing type into another CLR compatible type. If the conversion fails then an invalidcastexception is thrown.

ICloneable: Allows creating objects of a class having same values as another instance using the Clone method.

IEquatable:Implemented to create type specific methods to know the equality between various objects.

IFormattable:Implemented to convert object into string representations. Objects can define their own specific string representation through this interface’s ToString() method.

How do you create a resource-only assembly?

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.

What does an assembly contain?

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 assembly
Types and resources
Files
Security permissions

Define .Net Assembly.

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.

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.

Which .exe performs conversion of .txt / .restext files to .resources / .resx files and vice-versa ?

Resgen.Exe

Which .exe performs conversion of .txt / .restext files to .resources / .resx files and vice-versa ?

Resgen.Exe

Thursday, November 24, 2011

Page.AsyncTimeout Property

'<'asp:Page AsyncTimeout="TimeSpan" '/>'
A TimeSpan that contains the allowed time interval for completion of the asynchronous task. The default time interval is 45 seconds.

page.ClientQueryString

The ClientQueryString property contains the query string portion of the URL requested by the browser.
For example, if the requested URL is "http://www.xyz.com/default.aspx?id=100", the ClientQueryString property will contain "id=100".

supprted in following versions:
4, 3.5, 3.0, 2.0

How do I use the aspnet_merge.exe command line to merge precompiled assemblies?

aspnet_merge.exe d:\PrecompiledWebSiteDemo -w YourAssemblyName.dll

What is the difference between the updatable and without non-updatable option while precompiling ASP.NET website?

When precompiling the ASP.NET website, there is an option "Allow this precompiled site to be updatable" in Publish Utility using Visual Web Developer or the –u option while using aspnet_compiler command line. If we enable "Allow this precompiled site to be updatable" option, it doesn’t mean that we can change everything on the precompiled website. Let’s see what the difference is while the "Allow this precompiled site to be updatable" option is enabled or not:
Precompiling without the updatable option checked:

If this option is disabled, the compiler will not only compile source code into assembly, but also produces assemblies from markup of page, resource files, etc. In the output, compiler removes all the source code and markup from page which will leave a placeholder with empty content. To change the website except for its configuration, we need to recompile the website and redeploy the layout.

Precompiling with updatable option checked:

With this option enabled, the compiler will not remove the markup of page and so we can make limited changes, such as change the arrangement of controls, colors, fonts, and other appearance aspects of pages. Additionally, when the page is requested, ASP.NET will perform further compilation in order to create output from the markup.

What is smart navigation?

Smart Navigation is obsolete in .NET 2.0. It works with 1.1 & versions before it. The SetFocus and MaintainScrollPositionOnPostBack are used instead

Smart Navigation basically enhances a web pages' performance by doing the following:

* It eliminates the flash caused during navigation
* It persists element focus during postbacks
* It persists scroll position during postbacks between pages
* It retains the lasts page information in the history of the browser

I suggest not to use SmartNavigation because it does not work with many browsers.
From .Net2.0 versions Page.MaintainScrollPositionOnPostBack is used in the place of smartnavigation

Wednesday, November 23, 2011

How to use more than one web.config in asp.net

By default when a webspplication in created we get root folder web.config
set the appsettings tag as follows
(Iam removing the start and end tag symbols due to publishing problems,instead i use '(' and ')' in place of '<' and '>'.Please replace while you test this code)
(appsettings)
(add key="rootfolder" value="Root Folder web.config"/)
(add key="test1" value="Testing the application for root folder web.config"/)
(/appSettings )

in Default.aspx
(html xmlns="http://www.w3.org/1999/xhtml")
(head runat="server")
(title)RootFolder web.config(/title)
(/head)
(body)
(form id="form1" runat="server")
(div)
(b)
Root Folder values
(/b)
(/div)
(br /)
(div)
AppKey value:
(b)
(asp:Label ID="lbltxt" runat="server" Text="(%$appSettings:rootfolder %)"/)
(/b)
(br /)
Appkey Test value:
(b)
(asp:Label ID="Label1" runat="server" Text="(%$appSettings:test1 %)"/)
(/b)
(/div)
(/form)
(/body)
(/html)

Run your application
Output:
AppKey value:Root Folder web.config
AppKey Test value:Testing the application for root folder web.config

Create SubRoot Folder and add web.config and one aspx page and name it as test.aspx

add settings in web.config in subroot folder
(appSettings)
(add key="subrootfolder" value="Sub Root Folder web.config"/)
(add key="test1" value="Testing the application for sub root folder web.config"/)
(/appSettings )

in Test.aspx
(html xmlns="http://www.w3.org/1999/xhtml")
(head id="Head1" runat="server")
(title)SubRoot Folder web.config(/title)
(/head)
(body)
(form id="form1" runat="server")
(div)
(b)
SubRoot Folder values
(/b)
(/div)
(br /)
(div)
AppKey value:
(b)
(asp:Label ID="lbltxt" runat="server" Text="(%$appSettings:subrootfolder %)"/)
(/b)
(br /)
Appkey Test value:
(b)
(asp:Label ID="Label1" runat="server" Text="(%$appSettings:test1 %)"/)
(/b)
(/div)
(/form)
(/body)
(/html)

Run application and test.aspx as start page
Output
AppKey value:Sub Root Folder web.config
AppKey Test value:Testing the application for sub root folder web.config

If you observe above outputs Default.aspx page getting values from root folder web.config file and ChildPage.aspx page getting values from subroot folder web.config file.

Modifying Configuration Settings at Runtime

Adding New Key-Value Pairs
// Adds a key and value to the App.config
public void AddKey(string strKey, string strValue)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
try
{
if (KeyExists(strKey))
throw new ArgumentException("Key name: <" + strKey + "> already exists in the configuration.");
XmlNode newChild = appSettingsNode.FirstChild.Clone();
newChild.Attributes["key"].Value = strKey;
newChild.Attributes["value"].Value = strValue;
appSettingsNode.AppendChild(newChild);
//We have to save the configuration in two places,
//because while we have a root App.config,
//we also have an ApplicationName.exe.config.
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
catch (Exception ex)
{
throw ex;
}
}

Updating Key-Value Pairs
// Updates a key within the App.config
public void UpdateKey(string strKey, string newValue)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
childNode.Attributes["value"].Value = newValue;
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Deleting Key-Value Pairs
// Deletes a key from the App.config
public void DeleteKey(string strKey)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
appSettingsNode.RemoveChild(childNode);
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Helper Method
// Determines if a key exists within the App.config
public bool KeyExists(string strKey)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
return true;
}
return false;
}

Tuesday, November 22, 2011

Side-by-side Execution

Side-by-side execution is the ability to install multiple versions of code so that an application can choose which version of the common language runtime or of a component it uses. Subsequent installations of other versions of the runtime, an application, or a component will not affect applications already installed.

Benefits of Side-by-Side Execution
Prior to Microsoft Windows XP and the .NET Framework, DLL conflicts occurred because applications were unable to distinguish between incompatible versions of the same code. Type information contained in a DLL was bound only to a file name. An application had no way of knowing if the types contained in a DLL were the same types that the application was built with. As a result, a new version of a component could overwrite an older version and break applications.

Side-by-side execution and the .NET Framework provide the following features to eliminate DLL conflicts:

•Strong-named assemblies.Side-by-side execution uses strong-named assemblies to bind type information to a specific version of an assembly. This prevents an application or component from binding to an invalid version of an assembly. Strong-named assemblies also allow multiple versions of a file to exist on the same computer and to be used by applications.
•Version-aware code storage.The .NET Framework provides version-aware code storage in the global assembly cache. The global assembly cache is a computer-wide code cache present on all computers with the .NET Framework installed. It stores assemblies based on version, culture, and publisher information, and supports multiple versions of components and applications.
•Isolation. Using the .NET Framework, you can create applications and components that execute in isolation, an essential component of side-by-side execution. Isolation involves being aware of the resources you are using and sharing resources with confidence among multiple versions of an application or component. Isolation also includes storing files in a version-specific way.

What is the Common Language Specification?

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the common type system; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these help you determine whether your managed code conforms to the CLS and to what extent a given tool supports the development of managed code that uses CLS features.

If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components.

Most of the members defined by types in the .NET Framework class library are CLS-compliant. However, some types in the class library have one or more members that are not CLS-compliant. These members enable support for language features that are not in the CLS. The types and members that are not CLS-compliant are identified as such in the reference documentation, and in all cases a CLS-compliant alternative is available.

The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it. In addition, any language construct that makes it impossible to rapidly verify the type safety of code was excluded from the CLS so that all CLS-compliant languages can produce verifiable code if they choose to do so.

Difference between CTS ans CLS

CTS And CLS are the major components through which the interoperability is acheived in .Net Framework. CLS ( Common Language Specification) specifies some set of rules for all the .Net Compilers.

In this process it makes use of CTS(Common Type System) which is a subset OF CLS.CTS consists of types ( both Value-Type And Referrence Types).

To make clear about the use of CTS:

If we are declaring a INTEGER Type in VB.NetDim I As Integer If we are declaring the same INTEGER Type in C#.Netint i.

both of these are converted to the form i as int32 so, irrespective of the language written in they are convreted to Intermediate Language which CLR can read and understand.

What are Design Patterns?

A Software design pattern provides us a general solution to a common problem in software design.

It is a description or template for how to solve a problem.

Large majority of Software development teams tend to face similar problems in Software development.

Patterns provide us reusable solutions to commonly encountered programming challenges

This helps us speed up the Design and overall Development Time and Effort thereby resulting in cost savings. At the same time since these patterns are time tested they provide solutions with known benefits and drawbacks. Over a period of time patterns get improvised and new patterns emerge.

There are various types of Software Design Patterns:

Design patterns can be classified based on multiple criteria, the most common of which is the basic underlying problem they solve.

List below are some of the most important categories of Software Design Patterns:
A) Creational patterns:Creational design patterns deal with object creation mechanisms.
* Factory Method
* Abstract Factory
* Builder
* Prototype
* Singleton

B) Structural patterns: Structural design patterns focus on relationships/interfaces between entities and objects.
* Adapter
* Bridge
* Composite
* Proxy


C) Behavioral patterns: Behavioral design patterns focus on common communication patterns between objects.
* Iterator
* Observer

How do the Layers communicate with each other in N-Tier application?

Each Layer comprises of one or more components. Each component being a part of the app may communicate with one or more component. The component may "speak"to the other components using one of the many protocols, HTTP, FTP, TCP/IP and mechanisms such as XML/RPC, SOAP, REMOTING etc. The data as such may be “passed” across in many formats such as binary, string , XML.

N-Tier Applications?

1) The Presentation Layer: Also called as the client layer comprises of components that are dedicated to presenting the data to the user. For example: Windows/Web Forms and buttons, edit boxes, Text boxes, labels, grids, etc.

2) The Business Rules Layer: This layer encapsulates the Business rules or the business logic of the encapsulations. To have a separate layer for business logic is of a great advantage. This is because any changes in Business Rules can be easily handled in this layer. As long as the interface between the layers remains the same, any changes to the functionality/processing logic in this layer can be made without impacting the others. A lot of client-server apps failed to implement successfully as changing the business logic was a painful process.

3) The Data Access Layer: This layer comprises of components that help in accessing the Database. If used in the right way, this layer provides a level of abstraction for the database structures. Simply put changes made to the database, tables, etc do not effect the rest of the application because of the Data Access layer. The different application layers send the data requests to this layer and receive the response from this layer.

The database is not accessed directly from any other layer/component. Hence the table names, field names are not hard coded anywhere else. This layer may also access any other services that may provide it with data, for instance Active Directory, Services etc. Having this layer also provides an additional layer of security for the database. As the other layers do not need to know the database credentials, connect strings and so on.

4) The Database Layer: This layer comprises of the Database Components such as DB Files, Tables, Views, etc. The Actual database could be created using SQL Server, Oracle, Flat files, etc.

What Happens During a Garbage Collection?

A garbage collection has the following phases:


1.A marking phase that finds and creates a list of all live objects.

2.A relocating phase that updates the references to the objects that will be compacted.

3.A compacting phase that reclaims the space occupied by the dead objects and compacts the surviving objects. The compacting phase moves objects that have survived a garbage collection toward the older end of the segment.

Because generation 2 collections can occupy multiple segments, objects that are promoted into generation 2 can be moved into an older segment. Both generation 1 and generation 2 survivors can be moved to a different segment, because they are promoted to generation 2.

The large object heap is not compacted, because this would increase memory usage over an unacceptable length of time.

The garbage collector uses the following information to determine whether objects are live:
Stack roots. Stack variables provided by the just-in-time (JIT) compiler and stack walker.

Garbage collection handles. Handles that point to managed objects and that can be allocated by user code or by the common language runtime.

Static data. Static objects in application domains that could be referencing other objects. Each application domain keeps track of its static objects.

Before a garbage collection starts, all managed threads are suspended except for the thread that triggered the garbage collection.

Generations in Garbage Collector

After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects. This memory is called the managed heap, as opposed to a native heap in the operating system.

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0: This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.

Generation 1: This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

Generation 2: This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).

Keywords in C#

abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using virtual void
volatil while

Inheritance in C#

C# supports two types of Inheritance mechanisms
1) Implementation Inheritance
2) Interface Inheritance

Implementation Inheritance:
When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance

Interface Inheritance:
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance


C# does not support multiple implementation inheritance A class cannot be derived from more than one class However, a class can be derived from multiple interfaces

What are types in .net?

An object can be of the following types – Class or Struct There are many differences between the two 'types'. The main difference between the two is the way in which they are stored in memory and the way they are accessed Classes are also called reference types Structs are known as value types Classes are stored in a memory space called 'heap' and Structs are stored in a memory space known as 'stack'.

Tuesday, November 8, 2011

Disable Browser Back Button Using Javascript ASP.NET

Javascript in head section
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);

body section
body onload="disableBackButton()">

Disable cut,copy and paste in textbox

Set oncopy="return false" onpaste="return false" oncut="return false"
in textbox tag