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

Thursday, September 15, 2011

How to disable Client Side and Proxy Caching of ASP.NET page?

In page Load
   Response.Cache.SetCacheability(HttpCacheability.NoCache);











How to prevent a Button from Validating Form on ASP.NET page?

ASP.NET Button controls have property CausesValidation.



When its set to "False" and button is clicked on ASP.NET page, validation is not triggered.



How to add Client-Side confirmation when deleting items in GridView?

In asp:TemplateField......itemtemplate
Add link button with commandname="Delete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this data Row?')"

How To Prevent Form Submission When User Presses the ENTER Key in TextBox?

protected void Page_Init(object sender, EventArgs e)
{
    TextBox1.Attributes.Add("onkeydown","if(event.which event.keyCode){if (event.keyCode == 13) return false;}");
}





How to Capitalize the First Letter of All Words in a string in C#

using System.Globalization;


TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

string capitalized = UsaTextInfo.ToTitleCase("asp.net simply rocks!!!");

What is the difference between Server.Transfer and Response.Redirect methods?

You can transfer current users page request to another page with two methods:

* Server.Transfer (HttpServerUtility.Transfer Method)
* Response.Redirect (HttpResponse.Redirect Method)

Its not always clear how these two approaches differ so let us try to clarify things a little:

Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page.
HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'.
After browser receives this code it tries to open the new location of the resource that was suggested by the server.
This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response.
All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected URL.

Also its important to say that the new URL can reside on the same server but also it can be on some other server and the redirected URL does not need to be .aspx page it can be regular HTML page also).

So we can us the Redirect method to redirect users request to another page on our server like this:

Response.Redirect("newPage.html");


or to redirect our it to some other server like this:

Response.Redirect("http://www.someotherserver.com/newPage.aspx");



In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server.
(This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc).

All posted Form variables and query strings can optionally remain available to the second Page where we transfered request (if we use second overload Server.Transfer(string path, bool preserveForm) and supply true for the second parameter).
Otherwise the Form Variables and Query String are cleared just like when we use Redirect.
WARNING: When You Use Server.Transfer and use this method
to preserve Query String and Form variables and receive error: "View State Is Invalid" its because your EnableViewStateMac attribute of the element is set to true.
Its also important to note that because of the way Server.Transfer works, after the transfer, the URL shown in the users Web Browser remains the original one that was requested, because browser has no knowledge that its request was transfered (transfer occurs on the server side).

TIP: One thing to be careful about when using the Server.Transfer is to clear the the HttpResponse object with Response.Clear method on the transfered page to avoid any output from the first page to be shown on the second page.

So now that we know what are the similarities and differences between these two approaches we can try to use them wisely.

Here is the summary:

Response.Redirect should be used when:
•we want to redirect the request to some plain HTML pages on our server or to some other web server
•we don't care about causing additional roundtrips to the server on each request
•we do not need to preserve Query String and Form Variables from the original request
•we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)
Server.Transfer should be used when:

•we want to transfer current page request to another .aspx page on the same server
•we want to preserve server resources and avoid the unnecessary roundtrips to the server
•we want to preserve Query String and Form Variables (optionally)
•we don't need to show the real URL where we redirected the request in the users Web Browser
You can transfer current users page request to another page with two methods:

* Server.Transfer (HttpServerUtility.Transfer Method)
* Response.Redirect (HttpResponse.Redirect Method)

Its not always clear how these two approaches differ so let us try to clarify things a little:

Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page.
HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'.
After browser receives this code it tries to open the new location of the resource that was suggested by the server.
This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response.
All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected URL.

Also its important to say that the new URL can reside on the same server but also it can be on some other server and the redirected URL does not need to be .aspx page it can be regular HTML page also).

So we can us the Redirect method to redirect users request to another page on our server like this:

Response.Redirect("newPage.html");


or to redirect our it to some other server like this:

Response.Redirect("http://www.someotherserver.com/newPage.aspx");



In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server.
(This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc).

All posted Form variables and query strings can optionally remain available to the second Page where we transfered request (if we use second overload Server.Transfer(string path, bool preserveForm) and supply true for the second parameter).
Otherwise the Form Variables and Query String are cleared just like when we use Redirect.
WARNING: If you use this method to preserve Query String and Form variables and receive error: "View State Is Invalid" its because your EnableViewStateMac attribute of the element is set to true.

Its also important to note that because of the way Server.Transfer works, after the transfer, the URL shown in the users Web Browser remains the original one that was requested, because browser has no knowledge that its request was transfered (transfer occurs on the server side).

TIP: One thing to be careful about when using the Server.Transfer is to clear the the HttpResponse object with Response.Clear method on the transfered page to avoid any output from the first page to be shown on the second page.

So now that we know what are the similarities and differences between these two approaches we can try to use them wisely.

Here is the summary:

Response.Redirect should be used when:
•we want to redirect the request to some plain HTML pages on our server or to some other web server
•we don't care about causing additional roundtrips to the server on each request
•we do not need to preserve Query String and Form Variables from the original request
•we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)
Server.Transfer should be used when:

•we want to transfer current page request to another .aspx page on the same server
•we want to preserve server resources and avoid the unnecessary roundtrips to the server
•we want to preserve Query String and Form Variables (optionally)
•we don't need to show the real URL where we redirected the request in the users Web Browser

Friday, August 19, 2011

Read Configuration Settings of Web.config using Javascript

In Default.aspx (Head Section)
.....Javascript......
function ReadConfigSettings()
{
var conn = '<%=ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString %>'
alert(conn);
}
....end of javascript.....
Call this function on a button click and display the values of the configuration settings
Place a button in youe wrbpage and on OnClientClick call the function

Thursday, August 18, 2011

Design Patterns

Creational Patterns
Factory - This pattern is used to create concrete class instances without specifying the exact class type.
Abstract Factory - This pattern is used to create concrete class instances without specifying the exact class type. The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme.

Flyweight - A pattern used to maximize the sharing of objects resulting in reduced memory consumption.
Singleton - This pattern insures that only a single instance of a given object can exist.
Builder - This pattern separate the construction of a complex object from its representation so that the same construction process can create different representations..

Important Questions

1.What important standard is used to connect client browsers with web servers ?
Ans:TCP/IP
2.What ASP.NET object is used to get information about the web servers ?
Ans:The Server object
3.What method(s) must be used with the Application object to ensure that only one process accesses a variable at a time ?
Ans:Lock() and UnLock()
4.When an ASP.NET server control is added to a Web Form, Visual Studio .NET adds one item to the class for the form. What item is added ?
Ans:A default event handler for the click event
5.What HTML element is the asp:Label control rendered as when the target is Internet Explorer ?
Ans:Span
6.What is the Web.config file used for ?
Ans:To store the global information and variable definitions for the application
7. After capturing the SelectedIndexChanged event for a ListBox control, you find that the event handler doesn’t execute. What could the problem be ?
Ans:The AutomaticPostBack attribute is set to False
8.What method must be overridden in a custom control ?
Ans:The render method
9.Can two different .net programming languages be mixed in a single ASPX file ?
Ans:No
10.How to protect view state from tampering when it's passed over an unencrypted channel ?
Ans:In Page directive set EnableViewStateMac="true"

What is the operation that you can not do with primitive types

Create a new instance of primitive type with New keyword

what is a resource file?

Resource files are the files containing data that is logically deployed with an application. These files can contain data in a number of formats including strings, images and persisted objects. It has the main advantage of if we store data in these files then we don't need to compile these if the data get changed. In .NET we basically require them storing culture specific information's by localizing application's resources. You can deploy your resources using satellite assemblies.

Resource Files are most benificial while developing multilingual Web applications. This feature has been included in ASP.Net 2.0, which provides a declarative model for Resource handling through Resource Expressions (Sub-feature of the overall feature). ASP.NET v2.0 provides automatic support for resource (RESX or RESOURCE) files that follow a specific naming convention and that reside in specialized folders within the application. Hence we can add resource files without any compilation step or satellite assemblies. This enables the developer to provide resources that can be scoped to a page or an application. The ASP.NET runtime uses the .NET Framework ResourceManager to perform resources lookup.
There are 2 types of Resouce files :
1.Global Resource file : This file is present in a specialized folder called /App_GlobalResources, located at the root of the application. All pages, user-controls, etc. can access these resources, so they typically are used as shared resources. The resources which should be available throughout the application are stored in this file.
2.Local Resource file : These files are present in /App_LocalResources folder. These files follow the naming convention of the associated page, user-control, or master-page, along with the culture definition. These files are only accessible by the associated page.

Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?

From StackOverflow: Postbacks are an abstraction on top of web protocols which emulate stateful behavior over a stateless protocol. On the client side, postbacks are achieved by javascript calls and hidden fields which store the state of all controls on the page. The server side goes through a life cycle of events, port of that life cycle is the hydration of the viewstate to maintain the state of all controls on the page, and the raising of events based on the parameters that were passed into the __doPostBack call on the client side.

Depending on your requirements, you can use control events like OnClientClick to chain in your client side JavaScript, or you can use the GetPostBackEventReference method to give your scripts access to the postback method on the client side.

What are ASHX files? What are HttpHandlers? Where can they be configured?

An .ashx file is a placeholder for an HttpHandler. It allows you to create a IHttpHandler implementation as simply as you create a .aspx file, without any reconfiguration of web.config or other hoops. It provides you access to the Request and Responsie without any of the facilities or overhead of the page model.

HttpHandlers are low level implementations of the request/response http cycle. Using an HttpHandler, you can deliver responses back to the browser with minimal overhead. A good example of this would be a dynamic image generator that could be accessed using the tag.

You configure HttpHandlers by registering them in web.config. You may also need to configure IIS to send certain file extension requests to aspnet_isapi.dll.

From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what the are events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?

Object Initialization (Server object and page object instantiated)
PreInit (Add dynamic controls)
Init (Change control initialization values after control init)
InitComplete (All controls initialized)
PreLoad (Before stat loads)
Load (State has been loaded) (Page called first, then controls)
Control Events (Events caused by postback)
LoadComplete (Post post-back processing)
PreRender (last changes to viewstate)
SaveStateComplete (post-viewstate processing)
Render (generate html)
UnLoad (cleanup)
Dispose (objects destroyed)

Monday, August 8, 2011

Why we should give preference to stored procedure?

A stored procedure is a group of SQL statements that have been created and stored in a database. A procedured can accept input parameters. When the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.

Procedure Cache is the place where Execution Plan of Stored Procedure is stored. An execution plan states the efficient way in which the query(s) is executed. So whenever a normal query is executed its Execution Plan is created but when a Stored Procedure is executed, Execution plan is created and stored in Procedure Cache. Whenever the same procedure is executed and its execution plan exists in Procedure cache then it uses that execution plan rather than creating a new plan.

What is an extent?

Extent is a basic unit of storage to provide space for tables. Every extent has a number of data pages. As new records are inserted new data, pages are allocated. There are eight data pages in an extent. So as soon as the eight pages are consumed, it allocates a new extent with data pages.

While extent is basic unit storage from a database point of view, page is a unit of allocation within extent.

What are IMPLICIT TRANSACTIONS?

Implicit Transactions are those that requires a COMMIT or ROLLBACK for every transaction.

When ON, SET IMPLICIT_TRANSACTIONS sets the connection into implicit transaction mode. When OFF, it returns the connection to autocommit transaction mode.

For example if we turn it on & update a table, the changes will not be committed until COMMIT command is executed.

What is the advantage of SET NOCOUNT ON in sql procedure

SET NOCOUNT ON gives a performance boost to action queries by suppressing the "(n row(s) affected) message that results from running a query.

Qualifying an object with it's owner boosts performance because SQL does not have to work out where if there is a user specific version of the same object. It also gives benefits in the caching of execution plans.

The performance boost is due to the few bytes of information that make up the "(1 row(s) affected)" message not being transmitted to the client application.

Monday, August 1, 2011

6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing.

When you declare a variable in a .Net application, it allocates some chunk of memory in to the RAM. This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

That was a simple explanation of what happens in the memory, but depending on what kind of data type your variable is allocated on that type of memory. There are two types of memory allocation stack memory and heap memory.

Stack and Heap
In order to understand stack and heap, let’s understand what actually happens in the below code internally.

public void Method1()
{// Line 1
int i=4;
// Line 2
int y=2;
//Line 3
class1 cls1 = new class1();
}

It’s a 3 line code so let’s understand line by line how things execute internally.
Line 1:- When this line is executed compiler allocates a small amount of memory in to memory type called as stack. Stack is responsible of keeping track of running memory needed in your application.

Line 2:- Now the execution moves to the next step. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartment or boxes put on top of each other.
Memory allocation and de-allocation is done using LIFO (Last in first out) logic. In other words memory is allocated and de-allocated at only one end of the memory i.e. top of the stack.

Line 3:- In line 3 we have a created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called as ‘Heap’. ‘Heap’ does not track
running memory it’s just pile of objects which can reached at any moment of time. Heap is used for dynamic memory allocation.

One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword it allocates on "HEAP".

Execution:-
Now finally the execution control starts exiting the method. When it passes the end control it clears all the memory variables which are assigned on stack. In other words all variables which are related to ‘int’ data type are de-allocated in ‘LIFO’ fashion from the stack.
The BIG catch – It did not de-allocate the heap memory. This memory will be later de-allocated by “GARBAGE COLLECTOR”.

Value types and reference types
Now that we have understood the concept of ‘Stack’ and ‘Heap’ it’s time to understand the concept of value types and reference types.
Value types are types which hold both data and the memory on the same location. While a reference type has a pointer which points to the memory location.
Below is a simple integer data type with name ‘i’ whose value is assigned to an other integer data type with name ‘j’. Both these memory values are allocated on the stack.
When we assign the ‘int’ value to the other ‘int’ value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as ‘Value types’.

When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. So when we assign ‘obj’ to ‘obj1’ they both point to the same memory location.
In other words if we change one of them the other object is also affected this is termed as ‘Reference types’.

So which data types are ref type and value type?
In .NET depending on data types the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types and any other .NET primitive data types are assigned on the stack.

Boxing and Unboxing
When we move a value type to reference type the data is moved from the stack to the heap. When we move reference type to a value type the data is moved from the heap to the stack.This movement of data from the heap to stack and vice-versa creates a performance hit.

When the data moves from value types to reference types its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.

SQL Server: JOIN vs IN vs EXISTS - the logical difference

There is a common misconception that IN behaves equaliy to EXISTS or JOIN in terms of returned results.

This is simply not true. To see why not, let's review what each statement does.

IN:
Returns true if a specified value matches any value in a subquery or a list.

Exists:
Returns true if a subquery contains any rows.

Join:
Joins 2 resultsets on the joining column.

From where we can set the Session Time Out in IIS ?

We can set the Session time out settings from the Virtual Directory for that site.

Right Click on Virtual Directory > Properties > Click on "Configuration" Button.Goto the "Option" Tab. There in Enable Session State Section you can configure the Session Timeout .

What is the default user name of an anonymous login in IIS?

In IIS, an anonymous user will be given with a user name of "IUSR_MachineName"

what are the Error & Status codes in IIS 6.0?

100 Series - Informational
200 Series - Success
300 Series - Redirection
400 Series - Client Error
500 Series - Server Error

What are the Different steps to be followed to get SSL(Secure Sockets Layer) for our Web Application ?

1.Intially we have to Generate a certificate request from our IIS

2. Now we have to request a certificate from the certificate authority(CA)

3. This CA is an entity which issues Digital Certificates.

4. After receiving the certificate we have to install that particular certificate on our Web Server using IIS

5. We have to use Secure Hyper Text Transfer Protocol(HTTPS) when accessing secure pages in our application.

By this way we could make our web page as SSL protected. !!!

Find Duplicate Records in SQL

select employee, firstname, lastname, dob
from employees (nolock)
where employee in
(select employee from employees (nolock)
group by employee
having count(employee)>1)
order by employee

What is AL.EXE and Resgen.EXE

Resgen.exe performs conversion of .txt / .restext files to .resources / .resx files and vice-versa. These (.resources/.resx) files can be embedded in a runtime binary executable or compiled into satellite assemblies.

Assembly Linker (Al.exe) generates a file that has an assembly manifest from modules or resource files. A module does not have an assembly manifest.

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 implement the methods in it, the class can be separated and written in different files as partial class.

The keyword partial must appear in each class.


//syntax for C#
Public partial class MyPartialClass1
{
//code
}

// this code could be in file1

Public partial class MyPartialClass1
{
//code
}
// this code could be in file2

Partial classes allow us to divide the class definition into multiple files (physically). Logically, all the partial classes are treated as a single file by the compiler.

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.

What are the various components in crystal reports?

When .NET application uses crystal reports, the following components are required:

•Report files: .rpt or report files needs to be distributed which can either be compiled into the application (Embedded) or independently (non embedded) from the application.
•Crystal reports merge module: The merge module ensures that the correct report components and component versions are installed with the application.
•.Net Framework: - .Net framework must be available on the client machine

Explain the situations you will use a Web Service and Remoting in projects.

Web services should be used if the application demands communication over a public network and require to work across multiple platforms. Remoting is faster comparatively and hence can be used in .Net components when performance is a high priority. Few applications can also make use of BOTH web services and Remoting to send and receive data not just across multiple platforms but also between .Net applications where performance and speed is a key priority.

Explain the situations you will use a Web Service and Remoting in projects.

Web services should be used if the application demands communication over a public network and require to work across multiple platforms. Remoting is faster comparatively and hence can be used in .Net components when performance is a high priority. Few applications can also make use of BOTH web services and Remoting to send and receive data not just across multiple platforms but also between .Net applications where performance and speed is a key priority.

What is Service Oriented architecture?

Service oriented architecture is based on services. Service is a unit of some task performed by a service provider in order to satisfy the consumer. Example of such a service is the web services used in .NET. Even though the main purpose of web services is to enable communication, it may differ from application to application. SOA provides a set of policies and frameworks to ensure the desired services are delivered to the consumer.

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 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 is a PID? How is it useful when troubleshooting a system?

PID stands for Process Identifier.
It is a uniquely assigned integer that identifies a process in an OS.
It is used in diagnosing the problems with the process in Multi-Tasking systems.

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.

What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

A service opens before one log in. However, a standard exe can be opened after a log in only.

Windows Service applications are long-running applications that do not have a user interface. They do not even produce any visual output.
The user messages are written to the Windows Event Log.
Services can run under the context of any user or a system. They are controlled by the Service Control Manager by which they can be stopped, paused, and started.

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 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

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

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.

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 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.

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.

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.

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 benefit do you get from using a 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.

What is the use of GetCommandLineArgs() method in C#.NET?

With GetCommandLineArgs() method, the command line arguments can be accessed.
The value returned is an array of strings.

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.

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 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

Change date format mm/dd/yy to dd/mm/yy using query?

Select CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘/’ + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + ‘/ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS DATE

Can you edit the data in repeater control?

No, we can only display data.

Can you edit the data in repeater control?

No, we can only display data.

Can you declare the override method static while the original method is non-static?

No, you can’t the signature of the virtual method must remain the same, only the keyword ‘virtual is changed to keyword override’.

What does the Keyword ‘virtual’mean in the method definition?

The method can be over-ridden

Is it possible to insert hyperlinks in ListBox?

It can’t possible adding hyperlinks/links to listbox.
Its just a collection items not child items and are not render while anyone put some html tags. So, its not possible

How can I get the date of Last Monday of specified week?

declare @dt datetime

set @dt=’1/1/2010′ –Want to know January’s Last Monday Date

SELECT dateadd(d,-datepart(dw,DATEADD(d, -datepart(d,dateadd(mm,1,@dt)),dateadd(mm,1,@dt))-1)+1,DATEADD(d, -datepart(d,dateadd(mm,1,@dt)),dateadd(mm,1,@dt)))

Can we store filtered DataView in ViewState?

We can store only objects of the following types:
1. string
2. integers
3. boolean
4. Array
5. ArrayList
6. Hash tables
7. Custom types etc.
Apart from above we can share some other types too but the class must be serialized.
In view of above theory, we can say ‘yes, we can store DataView in ViewState for serialized class.

Can I inherit two difference classes to partial classes?

We can’t inherit two difference classes to partial class because in C# multiple inheritance is not possible using classes.

What are Classes and structures

Structures

A structure in C# is simply a composite data type [you are well aware from composite data type, refer to data types for more details], which consists number of members of other types. The structure define simply by using the struct keyword.

eg. struct enroll
{
public string name, fname, mname;
public string char sex;
Public int age;
public string address;
}

Classes

It is cleared from above study that Classes are reference type. A class is a collection of its data members. Data members are those members of class which contains the data of class like fields, constants and events etc. Class is declared simply just followed by class keyword with optional modifiers; by default C# classes are public.

eg. class myClass
{
public int xyz;
public string name;
public const int y=22;
}

Define interface in own words

An interface is simply a collection of function prototypes. An Interface is a reference type like a class, but interface can contain only abstract members. In other words, Interface is a contract that defines the signature of the functionality.

An interface looks like a class definitions, but its only purpose is to define a set of methods and not to implement them. For this reason the interface definition includes only the definition of methods [in other words the abstract methods]. Interface contains only methods, properties and delegates but can not contain fields, constructors, destructor and any type of static members.

Tuesday, July 12, 2011

Download Image from URL

public System.Drawing.Image DownloadImageFromUrl(string imageUrl)
{
System.Drawing.Image image = null;
try
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 30000;
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
image = System.Drawing.Image.FromStream(stream);
webResponse.Close();
}
catch (Exception ex)
{
return null;
}
return image;
}




protected void btnSave_Click(object sender, EventArgs e)
{
System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());
string rootPath = @"C:\DownloadedImageFromUrl";
string fileName = System.IO.Path.Combine(rootPath, "test.gif");
image.Save(fileName);
}

Shutdown, Restart and LogOff windows using C#

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.InteropServices;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { }
[DllImport("user32.dll")]
public static extern int ExitEx(int operationFlag, int operationReason);
protected void btnRestart_Click(object sender, EventArgs e)
{ ExitEx(2, 0); }
protected void btnLogOff_Click(object sender, EventArgs e)
{ ExitWindowsEx(0, 0); }
protected void btnShutDown_Click(object sender, EventArgs e)
{ ExitEx(1, 0); }
}

Mobile Number Validation Javascript

function ValidateMobileNumber()
{
var InputText = document.getElementById('TextBox1').value;
var Expression = /^[0-9]{10}$/
if (InputText.search(Expression) == -1)
{
alert("Invalid Mobile Number. Must Contain Exactly 10 Numbers");
return false;
}
}

Monday, July 11, 2011

Working program that uses SqlParameter objects

using System;
using System.Data;
using System.Data.SqlClient;

class ParamDemo
{
static void Main()
{
// conn and reader declared outside try
// block for visibility in finally block
SqlConnection conn = null;
SqlDataReader reader = null;

string inputCity = "London";
try
{
// instantiate and open connection
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// don't ever do this!
// SqlCommand cmd = new SqlCommand(
// "select * from Customers where city = '" + inputCity + "'";

// 1. declare command object with parameter
SqlCommand cmd = new SqlCommand(
"select * from Customers where city = @City", conn);

// 2. define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "@City";
param.Value = inputCity;

// 3. add new parameter to command object
cmd.Parameters.Add(param);

// get data stream
reader = cmd.ExecuteReader();

// write each record
while(reader.Read())
{
Console.WriteLine("{0}, {1}",
reader["CompanyName"],
reader["ContactName"]);
}
}
finally
{
// close reader
if (reader != null)
{
reader.Close();
}

// close connection
if (conn != null)
{
conn.Close();
}
}
}
}
The code simply retrieves records for each customer that lives in London

Rememberme in Login Control

protected void Page_init(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UserCookie"] != null)
{
HttpCookie cookie = Request.Cookies.Get("UserCookie");
Login1.UserName = cookie.Values["username"];
TextBox txtPassword = Login1.FindControl("Password") as TextBox;
txtPassword.Attributes.Add("value", Request.Cookies["UserCookie"]["Password"]);
CheckBox checkMe = (CheckBox)Login1.FindControl("RememberMe");
checkMe.Checked = true;
}
TextBox txtUser = Login1.FindControl("UserName") as TextBox;
if (txtUser != null)
this.SetFocus(txtUser);
}
}

protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
//your login code
//if login is sucess
HttpCookie UserCookie = new HttpCookie("UserCookie ");
Boolean remember = Login1.RememberMeSet;

if (remember)
{
Int32 persistTime = 5;
UserCookie .Values.Add("username", Login1.UserName);
UserCookie .Values.Add("password", Login1.Password);
UserCookie .Expires = DateTime.Now.AddYears(persistTime);
}
else
{
UserCookie .Values.Add("username", string.Empty);
UserCookie .Values.Add("password", string.Empty);
UserCookie .Expires = DateTime.Now.AddMinutes(1);
}
Response.Cookies.Add(UserCookie );
}

Return last date of the current month using sql

SELECT datepart(dd,DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, getdate())+1, 0))) AS Dateval