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