Sunday, July 31, 2011

Session Management in ASP.NET

Ques: What is session?
Ans: HTTP is stateless protocol; it can't hold any information on the page. Session provide that facility to store the information on server memory.

Ques: What is difference between session and states?
Ans: Both are used to persist certain data.
1) State is at web control level whereas session is at page level.
2) Values in a session can be shared across different pages within same app, but State can not be shared across different pages.
3) Viewstate cannot be used if the page does not post back to itself.

Ques: What is session Id?
Ans: SessionId is unique identifier by which server track each session. here are the steps:
1) Client hit the web server and store date in session.
2) Server creates session Id and stores it in Session state provider.
3) When client request goes to server to get data from session, server just look at the ID and fetches the information.
SessionID is transmitted through cookie named as ASP.NET_SessionId. If cookie is disabled from browser then ASP.NET uses modified url("munged") url to send sessionID.

Ques: What are the different modes in which we can store the session?
Ans: Following are the possible ways:

1) InProc:
It stores the session in current application domain and handled by worker process in app pool. Restarting server will cause loss of session data.
Adv:
1) Accessing data is very fast.
2) Serialization not required.
DisAdv:
1) Recycling server causes data loss.
2) Performance hit, because of memory use.

2) StateServer :
Also called as out proc session mode. State server uses a standalone windows service independent to IIS and can also run as separate server. It is managed by aspnet_state.exe.
Adv:
1) Restarting server won't cause loss of data.
DisAdv:
1) Serialization/Deserialization overhead
2) Cost of data access to retrieve session data from another process.

3)SQLServer :
More secure and reliable session management. Stores data in SQL server DB.
Adv:
1) Data don not affected if we restart IIS.
2) More reliable and secure.
DisAdv:
1) Processing is very slow.
2) Serialization/Deserialization causes overhead.

4) Custom :
We can implement custom providers to store data by deriving from sessionstatestoreproviderbase class and we can generate new session by implementing ISessionID Manager.

There is also off mode, which allows you to disable session.

Ques: What are the events associated with session?
Ans: There are 2 events:
1) Session_Start(When new session initiated)
2) Session_End(when session expired, supported by InProc mode)
both of these can be handled in global.asax file.

Ques: What is Web garden?
Ans: App pool with multiple worker process is called as web-garden. It is not supported by InProc session.

Ques: How can we remove session?
Ans:
Session.Remove(strSessionName) --> Remove an Item from Session State Collection
Session.RemoveAll() --> Remove all items from session collection
Session.Clear() --> Remove all items from session collection
Note: There is no difference between Clear and RemoveAll. RemoveAll() calls Clear(), internally.
Session.Abandon() --> Cancels the Current Session

Ques: How session gets populate in http request?
Ans: In classic ASP, the session state is implemented as a free-threaded COM object contained in the asp.dll library. This object stores data organized as a collection of name/value pairs.
In ASP.NET, any incoming HTTP request passes through a pipeline of HTTP modules. Each module can filter and modify the amount of information carried over by the request. The information associated with each request is known as the call context and is programmatically represented with the HttpContext object. As the request passes through the chain of registered HTTP modules, its HttpContext object is endowed with references to state objects. When the request is finally ready for processing, the associated call context is bound to session-specific (Session) and global state objects (Application and Cache). The HTTP module responsible for setting up the session state for each user is SessionStateModule.

Sunday, July 24, 2011

.Net Fundamentals 18(Collections in .NET)

Arraylist:

Provides a collection similar to an array, but that grows dynamically as the number of elements change.

Example

static void Main()
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
foreach(int num in list)
{
Console.WriteLine(num);
}
}

Output
1
2
3

Stack:

A collection that works on the Last In First Out (LIFO) principle,Push - To add element and Pop – To Remove element

Example

class Test
{
static void Main()
{
Stack stack = new Stack();
stack.Push(2);
stack.Push(5);
stack.Push(8);

while(stack.Count != 0)
{
Console.WriteLine(stack.Pop());
}
}
}

Output
8
5
2

Queue:

A collection that works on the First In First Out (FIFO) principle, Enqueue: To add element and Dequeue:To Remove element
Example:

static void Main()
{
Queue queue = new Queue();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);

while(queue.Count != 0)
{
Console.WriteLine(queue.Dequeue());
}
}

Output
1
2
3

Dictionary:

Dictionaries are a kind of collection that store items in a key-value pair fashion.

Hashtable:
Provides a collection of key-value pairs that are organized
based on the hash code of the key.

Example:
static void Main()
{
Hashtable h1 = new Hashtable(20);
h1.Add("key1", "val1");
h1.Add("key2", "val2");
h1.Add("key3", "val3");

foreach(string key in h1.Keys)
{
Console.WriteLine(key);
}
}

Output
val1
val2
val3

Sortedlist:

Provides a collection of key-value pairs where the items are sorted according to the key. The items are accessible by both the keys and the index.

Example:
static void Main()
{
SortedList sl = new SortedList();
sl.Add(8, "eight");
sl.Add(5, "five");
sl.Add(11, "eleven");
sl.Add(2, "two");

for(int i=0; i {
Console.WriteLine("\t {0} \t\t {1}", sl.GetKey(i),
sl.GetByIndex(i));
}
}


Output

2 two
5 five
8 eight
11 eleven

Saturday, July 23, 2011

.Net Fundamentals 17(TEST )

1) What is the .NET collection class that allows an element to be accessed using a unique key?
A) SortedListClass
B) HashTableClass
C) CollectionBase
D) Stack
E) Queue

Ans: (B)

2) What is true about read only variables?
A) Can be allocated at compile time.
B) Can be allocated at run time
C) Declaration and initialization can be separated
D) All of the above

Ans: (D)
-------------------------------
Explanation:
'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.
--------------------------------

3) Defining two methods with the same name but with different parameters is called:
A) Loading
B) Overloading
C) Encapsulation
D) Inheritance

Ans: (B)

4) Difference between Convert and parse methods?
A) Convert converts the values, parse is for parsing
B) Both are same
C) Convert allows null values, parse cannot
D) None of the above

Ans: (C)
---------------------------------
Explanation:
The two give identical results, except where the string is null. Convert.ToInt32(null) returns zero, whereas Int32.Parse(null) throws an ArgumentNullException.

int i = Convert.ToInt32("23");
i = 23
int i1 = Convert.ToInt32("abc");
format exception
int i2 = Convert.ToInt32("");
format exception
int i3 = Convert.ToInt32(null);
i = 0

ConverTo also handled ENUM values.
---------------------------------

5) Default return type of an event is:
A) String
B) Integer
C) Event don't have any return type
D) None of the above

Ans: (C)

6) Convert.ToString() and ToString() has main difference:
A) ToString() handle null values but Convert.ToString() don't
B) Convert.ToString() handle null values but ToString() don't
C) ToString() output as per form at supplied
D) Convert.ToString() only handle null values

Ans: (B)
------------------------------------------
Explaination:
Convert take care of null values also.
string str = Convert.ToString(null);
str = null
------------------------------------------
7) How does assembly versioning in .NET prevents DLL Hell?
A) The runtime checks to see that only one version of an assembly is on the machine at any one time.
B) .NET allows assembly to specify the name and the version of any assembly they need to run.
C) The compiler offers compile time checking for backward compatibility
D) It doesn't

Ans: (B)

8) What is delegate?
A) Light weight thread or process that can call a single method
B) A reference to an object in a different process.
C) An inter-process message channel
D) A strongly typed function pointer.

Ans: (D)

9) What is satellite assembly?
A) A peripheral assembly designed to monitor permission requests from an application
B) Any DLL file used by an EXE file
C) An assembly designed to alter the appearance or 'skin' of an application
D) An assembly containing localized resources for another assembly.

Ans: (D)

10) What is boxing in .NET?
A) Encapsulating an object in a value type
B) Encapsulating a copy of an object in a value type
C) Encapsulating a value type in an object
D) Encapsulating a copy of a value type in an object

Ans: (D)

11) The C# keyword int maps to which .NET type?
A) System.int16
B) System.int32
C) System.int64
D) System.int128
E) System.int256

Ans: (B)

12) What is the difference between Server.Transfer and Response.Redirect?
A) Response.Redirect is used to post a form to another page, Server.TRansfer is used to redirect the user to another page or site.
B) Server.TRansfer is used to post a form to another page, Response.Redirect is used to redirect the user to another page or site.
C) Server.TRansfer is used to get a form from another page, Response.Redirect is used to redirect the user to same page or site.
D) Answer B and C

Ans: (B)
--------------------------------------------
Explanation:
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.
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.

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

--------------------------------------------

13) What data type does the RangeValidator control support?
A) Interger,String,Date
B) Integer and string only
C) only String
D) Only Integer

Ans: (A)

14) In the Url listed below what does the string (nav45m672ren60vizat) represent?
http://server.com/(nav45m672ren60vizat)/page.aspx
A) CookieID
B) connectionStringID
C) DataBaseID
D) ApplicationID
E) SessionID

Ans: (E)

15) Which one of the following object oriented techniques allows you to make changes in your code without impacting calling classes:
A) Interface
B) Inheritance
C) Polymorphism
D) Abstraction
E) Encapsulation

Ans: (A)

16) Can we overwrite one web.config file with another web.config file in an ASP.NET application?
A) Yes
B) No

Ans: (A) yes

17) What is the name of the web page property that you can query to determine that a web page is being requested without data being submitted?
A) FirstGet
B) Initialized
C) IncludesData
D) IsPostBack

Ans: (D)

18) What method must be overridden in a custom control?
A) The build() method
B) The controlBuild() method
C) The render Method
D) The default constructor

Ans: (C)

19) How do you explicitly kill a user session?
A) Session.Close()
B) Session.Discard()
C) Session.Abandon()
D) Session.End()

Ans: (C)

20) How many web.config files can be there in an ASP.NET application?
A) only 1
B) Only 2
C) More than one
D) Upto 10

Ans: (C)

Windows DNA to .NET

What is windows DNA?
Short for Windows Distributed internet Applications Architecture, a marketing name (Architecture) for a collection of Microsoft technologies that enable the Windows platform and the Internet to work together. It was programming model that companies use when designing n-tier distributed component based applications for windows platform.

What are advantages of .NET over Windows DNA?
1) Application deployment:
To replace a dll in windows DNA was not straight. You have to stop entire web site, copy file across and restart web site, sometimes reboot the machine. This is because the way COM manages the Dlls, once they are loaded you can not over ride them until unloaded. In case of .NET these can be overridden any time because of feature called shadow copy, which is part of CLR. It is feature that prevents PE(portable executable) files (DLL, EXE) being locked.
2) Side by side execution:
in windows DNA it was not easy to run 2 different versions of same application component side by side, either on same machine of same process. But in .NET different version of same component can co exist.
3) Scripting limitation:
In ASP pages we can not access Win32API directly and have many COM related restrictions, because every thing we write is on script side, thus using any component is little tricky here. But in case of ASP .NET we can write code in page/component, using any component is not a problem here.
4) Versioning Hell (DLL Hell):
An application may be dependent upon several DLLs. If any dependency is broken application will stop working. Thus it was very easy to break any application by installing any other application or changing registry using tool regedit. In .NET this problem got sorted our by GAC. If any other application comes with other DLLs also, the old DLL will not get affected, thus application will work fine.
5) Performance:
Every time we hit any ASP page, the scripts get compiled, but in case of ASP .net it is compiled only once, thus improves the performance.

How CLR and COM are related?
Ans: There is always adoubt that where exactly COM fits into CLR. The simple answer is it doesn't. CLR is written from ground, it is not like CLR is built on COM. COM is only used for interoperability and hosting, i.e. it enables us to use CLR classes as COM component on non-CLR environments. Hosting the CLR inside application(such as IIS) is achieved using COM, as CLR provides set of COM components for loading and executing CLR code.

 What are advantages of ASP .NET over ASP?
1) Remove the dependency on script debugging:
ASP is built using Active script, a technology originally designed to enable developers to script and control applications in uniform way. It has many problems, like:
--Code is interpreted not compiled(results in average performance)
--Weak type system(Code harder to develop,read,debug)
--Only support late binding(many times slower than early bound)
--Each instance of active scrip engine consumes memory
In ASP .NET we use assembly(DLLs), which are compiled 1st time only.

2)Easy deployment:
ASP .NET hs feature of shadow copy which makes our life easier. The shadow copy feature of the CLR only works for ASP .NET component files located in BIN directory.(what about GAC?)
3) Easy debugging in ASP.NET.
4)ASP.NET was built on HTTP run time, which has its own advantages.
5) Rich authentication model

What are the advantages of HTTP run time over ISAPI?
In the past, changing/extending the functionality of IIS required the use of C/C++ and the Internet Information Server API (ISAPI) to develop this functionality. With the ASP.NET HTTP Runtime, advanced functionality can now be easily created using the .NET Framework and any .NET Language.
The ASP.NET HTTP Runtime exposes an object-oriented, event-drive architecture. This easily allows developers to create advanced ASP.NET Web Applications that can participate during different stages of the Request/Response cycle. This ASP.NET HTTP Runtime infrastructure can be considered as the logical replacement for ISAPI filters. Because of the event-driven architecture of the ASP.NET HTTP Runtime, developers are able to participate at various stages of the application lifecycle using the .NET Languages.
Another ISAPI-based advantage is that the programming model allowed responding to particular URLs and to particular file extensions. This model is referred to as an ISAPI Application (or extension). As a well-known example, the classic ASP.DLL is an ISAPI application mapped to process files with an extension of .asp.  Therefore, when IIS receives an HTTP request for a .asp file, the incoming request is dispatched (via internal mapping maintained by IIS) to ASP.DLL file. ASP.DLL in turn loads the file, interprets and executes its contents,  and then sends the response back to IIS which in turn forwards it on to the requesting browser. The ASP.NET Runtime can provide much of the same functionality by creating DLLs that implement the IHttpHandler interface. This kind of DLL is known as an HTTP Handler. An HTTP Handler can be developed using any .NET language. It can be developed either as a manually compiled and configured DLL, or it can developed by writing a special .ashx file. Both techniques accomplish the same functionality
Another commonly used interface in the ASP.NET Runtime is IHttpModule. ASP.NET comes with a number of pre-built classes that implement IHttpModule that are responsible for handling session state, authentication, authorization, logging, and output caching. The design of the ASP.NET HTTP Runtime allows for the removal of any un-needed IHttpModule from the application or the machine itself. This addresses the situation where you simple do not want to have a particular piece of default functionality in your application.