Sunday, November 20, 2011

ASP.NET page lifecycle

Here are the details about ASP.NET page life cycle. Browser Sends a request to IIS. IIS completes following 2 steps:
 - ASP.Net Environment ( App, Request,Response and context object creation)
 - Process request ( handers,modules and page events).
Environment Creation:
Browser sends Request to IIS. IIS decides who will serve the request. In IIS properties there are ISAPI extensions installed, which actually keep information about dll who is going to take care of which extenstion. For example for .aspx the dll is  aspnet_isapi.dll.
If it is a 1st request then using ApplicationManager IIS creates new application domain, This application domain creates the hosting environment.
Create HttpApplication Object.
Then core objects like HTTPRequest,HTTPResponse and HTTPContext are created and assigned to HttpApplication object. If there are 2nd or 3rd request then this HttpApplication object is reused(or can be new also,depending upon settings). If we have global.asax file in our website, then global.asax object is also created.
Process Request:




There are different stages of processing the request.
Page request:


1) occurs before the page life cycle begins.
2) At this stage ASP.NET determines whether the page needs to be parsed and compiled or whether a cached version of the page can be sent in response without running the page.
Start:
1) page properties such as Request and Response are set.
2) Determine whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.
Initialization:
1) Controls on the page are available and each control's UniqueID property is set.
Load:
1) If the current request is a postback, control properties are loaded with information recovered from view state and control state.
Postback event handling:
1) If the request is a postback, control event handlers are called.
2) The Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)
Rendering:
1)Before rendering, view state is saved for the page and all controls.
2) During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.
Unload:
The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

LifeCycle event:
Here are the list of events that play their role during asp.net page life cycle:

PreInit:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
-Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
-Create or re-create dynamic controls.Set a master page dynamically.
-Set the Theme property dynamically.Read or set profile property values.
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init:
Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page. The Init event for each child control occur before the corresponding event is raised for its container (bottom-up).
Use this event to read or initialize control properties.
InitComplete:
Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.
PreLoad:
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load:
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.The Load event for a container occurs before the Load events for its child controls (top-down). Use the OnLoad event method to set properties in controls and to establish database connections.
NoteNote:In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete:
Raised at the end of the event-handling stage. Use this event for tasks that require that all other controls on the page be loaded.
PreRender:
Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.The PreRender event of individual controls occurs after the PreRender event of the page. Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
PreRenderComplete:
Raised after each data bound control whose DataSourceID property is set calls its DataBind method.
SaveStateComplete:
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render:
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser. A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload:
Raised for each control and then for the page. The Unload event for each child control occur before the corresponding event is raised for its container (bottom-up) In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.





Reference: http://msdn.microsoft.com/en-us/library/ms178472.aspx

Saturday, November 19, 2011

DataBase Basic1 (Inner and outer join)

Que: What is Referential integrity?
Ans: Referential integrity is database principle which ensure references between data is valid and intact. It prevents user/application to enter invalid data into database.

Que: What is difference between inner join and outer join?
Que: We will try to understand the difference by an example. Suppose we have 2 tables:
Table A              Table B
Id   Name           Id   Name
1    Pankaj          1    Subbu
2    Aman            2    Pankaj
3    Abhay           3    Anil
4    Manish          4    Abhay
Inner Join:It is the intersection of the tables i.e. the rows they have in common.
So the following inner join query will return the result as follows:

SELECT * FROM TableA INNER JOIN TableB
ON TableA.Name = TableB.Name

id   name          id   name
1   Pankaj        2    Pankaj
3   Abhay         4    Abhay

Left Outer Join:
A left outer join will give all rows in A, plus any common rows in B.

SELECT * FROM TableA LEFT OUTER JOIN TableB
ON TableA.Name = TableB.Name

id      name          id        name
1      Pankaj        2         Pankaj
2      Aman          null       null
3      Abhay         4         Abhay
4      Manish        null        null

Full outer join:
A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B.

SELECT * FROM TableA FULL OUTER JOIN TableB
ON TableA.name = TableB.name

id      name          id      name
1       Pankaj       2       Pankaj
2       Aman        null    null
3       Abhay       4       Abhay
4      Manish      null     null
null     null           1      Subbu
null     null           3      Anil

Que: Write a query to achieve following result.
1)







Ans:  SELECT * FROM TableA INNER JOIN TableB ON TableA.name = TableB.name

2)








Ans:  SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.name = TableB.name

3)







Ans:  SELECT * FROM TableA LEFT OUTER JOIN TableB ON TableA.name = TableB.name

4)







Ans: SELECT * FROM TableA LEFT OUTER JOIN TableB ON TableA.name = TableB.name
        WHERE TableB.id IS null
5)







Ans: SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.name = TableB.name
         WHERE TableA.id IS null  OR TableB.id IS null

Sunday, September 18, 2011

Static constructor

Que: Where static members are allocated?
Ans: Data Segment.
Here is memory model which shows static member's location in memory -

Que: Is it possible to make constructor private?
Ans: yes. It is useful if we know that a class has only static member in it.Or when we want to control object creation with its constructor(Ex. Singleton pattern)

Que: Is it possible to have constructor static?
Ans: Yes. Here is the signature:
class A
{
public static int a;
    static A()
    {
       a = 5;
    }
}
It doesn't have any access modifier in it. It is class level.

Que: What is the use of static constructor?
Ans: It is used to initialize static variables in the class or to perform some action which needs to be performed only once.

Que: When is static constructor called?
Ans:  It is called when we try to create an object of class or when we try to access the static variable in class(whichever comes first.).

Que: What if the static constructor throws some exception?
Ans: If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Override and overload


Que: What is overriding?
Ans: Redefine a method in derived class that is in base class, i.e. same method name in base and derived class with different implementation.

Que: What is difference between override and new keyword?
Ans:  New -> Method is not overridden, it is different in derived.It means if a reference of base type which is pointing at derived type will execute a method of base class, althod same signature is available in derived class.
override-> Indicates that this method is overridden. If a reference of base type is pointing at derived class then method of derived class should get execute.

Que: What is the use of virtual keyword?
Ans: Virtual keyword is to show that this method can be overridden. A method which is not virtual can not be overridden.

Exercise: Find the output of the program.
1)  r1=?,r2=?
public class A
        {
            public A(){}                                   
            public string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }
Ans: r1 = "B"; r2="A"

2) r1=?,r2=?
public class A
        {
            public A(){}                                   
            public virtual string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }


Ans: r1 = "B"; r2="A"

3)r1=?,r2=?
public class A
        {
            public A(){}                                   
            public virtual string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public override string myMethod()
            {
                return "B";
            }
        }

static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }
Ans: r1 = "B"; r2="B"

4)r1=?,r2=?
public class A
        {
            public A(){}                                   
            public string myMethod()
            {
                return "A";
            }
        }
        public class B:A
        {
            public B():base(){}                                   
            public override string myMethod()
            {
                return "B";
            }
        }
static void Main(string[] args)
        {       
            B b1 = new B();
            A a1 = new B();
            string r1 = b1.myMethod();
            string r2 = a1.myMethod();
        }

Ans: compile error, cannot override inherited member because it is not marked virtual, abstract, or override.

5) r1,r2,r3,r4?
public class A
        {
            public A(){}
            public string method1()
            {
                return "A->method1";
            }           
        }

        public class B:A
        {
            public B():base(){}          
            public string method2()
            {
                return "B->method2";
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();           
            string r1 = a1.method1();
            string r2 = b1.method1();
            string r3 = ab1.method1();
            string r4 = b1.method2();
            // string r5 = ab1.method2(); -- method2 will not be found in ab1.
        }

Ans: r1= "A->method1" ; r2= "A->method1" ; r3= "A->method1" ; r4= "B->method1"

6)what is the output?
public class A
        {
            public A(){}
            public void method1()
            {
                Console.WriteLine("A->method1");
            }    
        public void method2()
            {
                Console.WriteLine("A->method2");
            }     
        }

        public class B:A
        {
            public B():base(){}         
            public void method2()
            {
                Console.WriteLine("B->method2");
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();          
            a1.method1();
            b1.method1();
            ab1.method1();
            b1.method2();
            ab1.method2();
        }
Ans:
A->method1
A->method1
A->method1
B->method2
A->method2

7)what is the output?
public class A
        {
            public A(){}
            public void method1()
            {
                Console.WriteLine("A->method1");
            }   
        public void method2()
            {
                Console.WriteLine("A->method2");
            }    
        }
        public class B:A
        {
            public B():base(){}        
            public void method2()
            {
                Console.WriteLine("B->method2");
            }
        }

static void Main(string[] args)
        {
            A a1 = new A();
            B b1 = new B();
            A ab1 = new B();         
            a1.method1();
            a2.method2();
            b1.method1();
            b1.method2();
            ab1.method1();          
            ab1.method2();
        }
Ans:
A->method1
A->method2
A->method1
B->method2
A->method1
A->method2

8) Find the output-
    class A { };   
    class B : A { };   
    class C
    {
        public virtual void Collide(A a)
        {
            Console.WriteLine("C -> A");
        }
        public virtual void Collide(B b)
        {
            Console.WriteLine("C -> B");
        }
    }
    class D : C
    {
        public override void Collide(A a)
        {
            Console.WriteLine("D -> A");
        }
        public override void Collide(B b)
        {
            Console.WriteLine("D -> B");
        }
    }
static void Main(string[] args)
        {
            C c = new C();
            A a = new A();
           
            B b = new B();

            c.Collide(a);
            c.Collide(b);

            D d = new D();
            d.Collide(a);
            d.Collide(b);

            C cd = new D();
            cd.Collide(a);
            cd.Collide(b);

            A ab = new B();
            c.Collide(ab);
            cd.Collide(ab);
        }
Ans -
C -> A
C -> B
 D -> A
 D -> B
 D -> A
 D -> B
 C -> A
 D -> A

Sunday, September 11, 2011

Thread Synchronization

Que: What are different mechanism provided by c# for thread synchronization?
Ans: 
Monitor:
Static class available in System.Threading namespace
Method available: Enter/Try Enter, Wait, Pulse/PulseAll,Exit
Code between Monitor.Enter and Monitor.Exit is considered in synch block.
It has some disadvantages like the code can end up in deadlock also if we don't use Enter and Exit method cleverly. That is why we prefer to use lock statement instead.

ReadWriterLock:
Available in System.Threading namespace.
It is generally used to secure shared resources for writing and reading. Main disadvantage of this is Reading thread is given preference over writing. Thus sometimes there is performance hit on writing method.

WaitHandle:
Available in System.Threading namespace.It is Abstract class.
Mutex,Semaphore and EventWaitHandle(AutoResetEvent and ManualResetEvent) are classes that are derived from this abstract class. Semaphore is available in System.dll and others are in MSCoreLib.Dll.

AutoResetEvent Class:
This class notifies one or more waiting threads that an event has occurred. It automatically changes the status to signaled when a waiting thread is released.This class cannot be inherited.

ManualResetEvent Class
This class also notifies one or more waiting threads that an event has occurred. The state of the event can be manually set or reset. The state of a manually reset event remains signaled until the ManualResetEvent.Reset method sets it to the nonsignaled state and the state remains nonsignaled until the ManualResetEvent.Set method changes the state back to signaled. This class cannot be inherited.

Interlocked Class
This class (in the System.Threading namespace) helps to synchronize access to variables that are shared amongst threads. It thus provides atomic operations for variables that are shared by multiple threads. You can increment or decrement a shared variable by calling Interlocked.Increment or Interlocked.Decrement on the shared variable.

Que: What is the advantage of Waithandle class over Monitor/ReadWriteLock?
Ans: Monitor and ReadWriteLock methods allow synchronization of thread in a single appdomain, whereas being a Kernel level Waithandle does allow to have thread synch in different Appdomain and different process also.

Que: Effect of passing value type in monitor:
Ans: Unboxed value type instance do not have a sync block index member therefore, they can not be used for synchronization. That is why when we pass Value type instance in Monitor.Enter c# compiler will generate code to box the instance.And if we pass the same value in Monitor.Exit,it gets boxed again. Our code endup locking one object and unlocking another. and we dont get any thread safety. In case of lock statement compiler will generate error saying valuetype not a reference type as required by lock statement.

Que: How to apply lock in static class?
Ans: We can use lock(typeOf(Class_Name)).

Que: What is difference between Mutex and Semaphore?
Ans: In Mutex we can have only one thread accessing the object whereas with Semaphore we can have more than one thread(upto certain max limit) accessing the object simultaneously.

Saturday, September 10, 2011

Garbage Collection

Que: What is Garbage collection?
Ans: Method of de-allocating and acquiring object unused objects.

Que: Is it possible to force Garbage collection?
Ans: Different people have different view on this, but there is method available GC.Collect(), which can help us to request Garbage collector to be invoked.

Que: What is the meaning of Generation?
Ans: Generation is term used by GC to identify how new an object is. object in generation 0 are newly created. Objects that survive the garbage collection once are in Generation 1 and objects that survive the garbage collection 2 or more are in generation 2.

Que: Explain the process of generational garbage collection.
Ans: Generational garbage collection makes following assumptions:
a) The newer an object is, the shorter is lifetime will be.
b) The older an object is, the longer its lifetime will be.
c)Collecting a portion of heap is faster than collecting the whole heap.
When CLR initializes, it selects a budget size for generation 0(say 256). Once this budget get full, it start garbage collection. Those object that survive are considered in generation 1(which also have some specific limit of memory). Once generation 1 budget get full CLR again call GC and collect the object in generation 1 and those which survived are considered in generation 2. CLR doesn't have more than generation 2. Objects which survived in generation 2 are still considered in generation 2 only. For optimization purpose CLR dynamically can change the budget of different generation.

Que:Explain the behavior of following program.
public static void main(){
Timer t = new Timer(TimerCallBack, null , 0 , 2000);
Console.ReadLine();
}
private static void TimerCallBack(object o)
{
    GC.Collect();
}
Ans: Ideally timer should be called every 2 sec, but as in call back GC.Collect is there thus through GC timer object will be collected as GC will see it is no longer used in main.

Que: What is drawback of finalization method?
Ans: IF we are using finalize method in our class then while creating an object of this class a separate pointer to this object is allocated(other than heap memory) on finalization list (a separate datastructure controlled by GC) and when this object is no longer in used GC will move this pointer from finalization to freachable queue. Next time when GC runs it will collect this memory. Hence we can understand it is taking more time to release memory.

Que: What is difference between Dispose and finalize?
Ans: Dispose method is used to clean up unmanaged resources and can be controlled by program while Finalize does the same thing but done by GC. We recommend to use IDispose interface and implemet Dispose method instead of using finalize method if we are using unmanaged resources.

Que: What is the meaning of resurrection?
Ans:In finalization object required and is dead, then GC forces the object back in life so that its finalize method can be called(freachable queue). After this finalize method is called and object is permanently dead. Act of preparing to call an object's finalize method is a form of resurrection.

.Net Fundamentals 20(Test 2)

1) A local variable:
A. Can be used anywhere in the program
B. Is declared within a method
C. Must accept a class
D. Represents a class object

Ans: B

2) An instance variable:
A. Is an object of class
B. Represents an attribute of an object
C. is a method of a class
D. A and C

Ans: B

3) An instance method
A. Represents the behavior of an object
B. Represents the attribute of an object
C. Represents another class
D. A and B

Ans: A

4) A constructor
A. Is used to create objects
B. must have the same name as the class it is declared with
C. May be overloaded
D. All of the above

Ans: D

5) class Test: Form()
A. Creates the class Test:Form
B. Creates the class Test that inherits the class Form
C. Creates the class form that inherits the class Test
D. A and B

Ans: B

6) Defining two method with the same name but with different parameters is called:
A. Loading
B. Overloading
C. Multiplexing
D. Duplexing

Ans: B

7) In order for a class to use an interface it must:
A. inherit the properties of the interface
B. Contain the same method as the interface
C. Create an interface objects
D. All of the above

Ans: All of the above

8) Every class directly or indirectly extends the ...... class
A. System
B. Object
C. Drawing
D. Console

Ans: B

9) The concept of composition specifies that you can
A. Compose good code with c#
B. Compose C# projects with different objects
C. Reduce errors by remaining composed during programming
D. All of the above

Ans: B
--
Def: Object composition is a way to combine simple objects or data types into more complex ones
--

10) Polymorphism occurs when the methods of child class
A. Override the parent class methods but maintain the implementation
B. Maintain the same return type and arguments as the parent class but implement it differently
C. Have different return types and arguments than the parent class
D. Are virtual

Ans: B

11) To output the value of multidimensional array, console.Writeline(...)
A. myArray[1][3]
B. myArray[1,3]
C. myArray(1)(3)
D. myArray(1),(3)

Ans: A

12) All methods in an abstract class must be declared abstract
A. True
B. False

Ans: B

13) Methods that are declared abstract in the base class must show implementation at the time of declaration.
A. True
B. False

Ans: B

14) The code public class B: A{}
A. Defines a class that inherits all the methods of A
B. Defines a class that inherits the public and protected methods of A only
C. Error
D. A and B

Ans: B

15) Assuming that public class B:A{public B(int i):base(i){}} compiles and runs correctly, what can we conclude about the constructor in the class A?
A. One constructor takes an argument of type i
B. There is only a default constructor
C. One constructor takes an arguments of the type int
D. A and B

16) Classes declared with the sealed keyword cannot be base class
A. True
B. False

Ans: A

17) An abstract class
A. May contains instance variables
B. May contain constructor
C. May extend another class
D. All of the above

Ans: D

18) Class String and the char structure found in the:
A. System.String namespace
B. System.Text namespace
C. System.Chars namespace
D. System namespace

Ans: D

19) The proper way to convert a string to all lowercase is:
A. String = string.ToLower(string)
B. ToLower(string)
C. string.ToLower()
D. string.ToLower(string)

Ans: C

20) If an indexof Any methods is passed an array of characters it:
A. Finds the first occurrence of each letter in the string
B. Searches for the first occurrence of any of the characters in the string
C. will search for the first occurrence of the sequence of characters
D. generates an error

Ans: B

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.

Saturday, February 5, 2011

ASP.NET state management

Que: What is a PostBack?
Ans: Send client side information/Data to server.

Que: HTTP protocol is stateless,so how do we maintain state between client/server on internet?
Ans: There are different ways to maintain states across Internet
Client: ViewState,Cookie,QueryString,Hidden fields,Control State
Server: Application, Session, Profile, DataBase

Que: What is ViewState?
Ans: ViewState the the way provided by ASP.NET to remember the state in postback.Because HTTP is stateless protocol, and every request to the server is a fresh request. So in order to maintain any data on the page(on client side), we have feature provided by ASP.NET,that is called as view state. It is stored in encrypted format. It is used by different ASP controls to store the state of the control and data to be preserved after postback.

Que: What are advantages and disadvantages of viewstate?
Ans: Advantages:
a) The view state is contained in a structure within the page code,so no server resources are required:
b) Enhanced security features: The values in view state are hashed, compressed, and encoded for Unicode implementations.
Disadvantages:
a) Performance considerations: Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
b) Security risks: The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with.

Que: How Cookie works?
Ans: Cookie is small amount of data maintain by client browser in text file(or client file system/in-memory). When the user visits any site first time,the server sends cookie along with the web page.This cookie get saved on client side.Next time any request goes to the same website(need not to be the same page) the cookie goes along with the request and server could authenticate the user based upon cookie.

Que: What are the type of Cookies?
Ans: There are 2 type of cookies:
1) Persistent: These cookies have expiration time set, and saved on hard disk. These will be available across browser instance also but only upto expiration time. The expired cookie gets deleted when user visit to the same site again who created this cookie.
2) Non-Persistent: Cookie that is not stored on user's hard disk, because they don't have any expiration time.These are part of browsers only.As soon as browser is closed, the cookie will be gone. It can not be shared across different browser instances.

Que: Where are cookies stored in your computer?
Ans: C:\Documents and Settings\[ your account name ]\Cookies

Que: What are advantage and disadvantage of cookie?
Ans: Advantages:
a) Configurable expiration rules
b) No server resources are required
c) Simplicity:Cookies are simple to write and handle.
Disadvantages:
a) Size limitations
b) User can disable their cookies by browser settings
c) Security risk: Cookies can easily be tampered.

Que: How to use Query Strings for state management?
Ans: We append information at the end of URL. Ex:
http://www.pankajsoni.com/abc.aspx?myKey1=myValue1&myKey2=myValue2

Que: Explain server side state management.
Ans:
Application state: Application state is stored in Application property of HttpContext. It is stored in an instance of HttpApplicationState class(a key-value dictionary). There are 2 ways to use application states.
1) Put the application state data in Application_start in Global.asax.
2) Add data in StaticObject collection by in Global.asax file. Advantages: 1) This is stored in server memory, so much faster than saving data to disk or database. 2) The data can be accessed by multiple threads at the same time. Disadvantages: 1) On application start up the data will be lost. 2) If the application is using multiple server for load balancing then this data won't be available to other servers.
Session State: Session variables are stored in SessionStateItemCollection object exposed through HttpContext.Session property.
Ex: Session["MyKey"] = "MyValue";
The sessions are available for limited time window.
Advantages:
1) Data preserved even if we restart iis or worker process. Because data stored in another process space.
2) It can be used for those browsers also which doesn't support HTTP cookies.
3) It can be accessed from multiple servers.
Disadvantages:
1) Session state remains in memory until removed/replaced so degrade the server performance.
Profile: Profile properties are used to store user specific data. It is similar to session state unlike session, the profile is not lost when user's session expires. To use this property we need to enable it through web.config file.
DataBase: Server save all the information in Database.
Advantages:
1) More secure, More storage, Robustness
2) Accessible for multiple resources.
Disadvantages:
1) Complex structure
2) Performance degradation