Friday, May 9, 2008

ASP.NET FAQS-9

(B) What’ is the sequence in which ASP.NET events are
processed ?
Following is the sequence in which the events occur :-
√ Page_Init.
√ Page_Load.
√ Control events
√ Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in
subsequent request of the page.
(B) In which event are the controls fully loaded ?
Page_load event guarantees that all controls are fully loaded. Controls are also accessed
in Page_Init events but you will see that viewstate is not fully loaded during this event.
(B) How can we identify that the Page is PostBack ?
Page object has a “IsPostBack” property which can be checked to know that is the page
posted back.
(B) How does ASP.NET maintain state in between
subsequent request ?
Refer caching chapter.
(A) What is event bubbling ?
Server controls like Datagrid, DataList, Repeater can have other child controls inside
them. Example DataGrid can have combo box inside datagrid. These child control do not
raise there events by themselves, rather they pass the event to the container parent (which
can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event.
As the child control send there events to parent this is termed as event bubbling.
223
(B) How do we assign page specific attributes ?
Page attributes are specified using the @Page directive.
(A) Administrator wants to make a security check that no
one has tampered with ViewState, how can he ensure this ?
Using the @Page directive EnableViewStateMac to True.
(B) What is the use of @ Register directives ?
@Register directive informs the compiler of any custom server control added to the
page.
(B) What’s the use of SmartNavigation property ?
It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is
posted back.
Note:- This is only supported for IE browser. Project’s who have browser compatibility as
requirements have to think some other ways of avoiding flickering.
(B) What is AppSetting Section in “Web.Config” file ?
Web.config file defines configuration for a webproject. Using “AppSetting” section we
can define user defined values. Example below defined is “ConnectionString” section
which will be used through out the project for database connection.




(B) Where is ViewState information stored ?
In HTML Hidden Fields.
224
(I) What is the use of @ OutputCache directive in ASP.NET?
It is basically used for caching. See more for Caching chapter.
(B) How can we create custom controls in ASP.NET ?
User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need
to two things in order that the ASCX can be used in project:.
√ Register the ASCX control in page using the
√ Now to use the above accounting footer in page you can use the below directive.

(B) How many types of validation controls are provided by
ASP.NET ?
There are six main types of validation controls :-
RequiredFieldValidator
It checks whether the control have any value. It's used when you want the control should
not be empty.
RangeValidator
It checks if the value in validated control is in that specific range. Example
TxtCustomerCode should not be more than eight length.
CompareValidator
It checks that the value in controls should match the value in other control. Example
Textbox TxtPie should be equal to 3.14.
RegularExpressionValidator
When we want the control value should match with a specific regular expression.
225
CustomValidator
It is used to define UserDefined validation.
ValidationSummary
It displays summary of all current validation errors.
Note:- It's rare that some one will ask step by step all the validation controls. Rather they
will ask for what type of validation which validator will be used. Example in one of the
interviews i was asked how you display summary of all errors in the validation control...So
there goes the last one Validation summary.
(B) Can you explain what is “AutoPostBack” feature in
ASP.NET ?
If we want the control to automatically postback in case of any event, we will need to
check this attribute as true. Example on a ComboBox change we need to send the event
immediately to the server side then set the “AutoPostBack” attribute to true.
(B) How can you enable automatic paging in DataGrid ?
Following are the points to be done in order to enable paging in Datagrid :-
√ Set the “AllowPaging” to true.
√ In PageIndexChanged event set the current pageindex clicked.
Note:- The answers are very short, if you have implemented practically its just a revision.
If you are fresher just make sample code using Datagrid and try to implement this
functionality.
(B) What’s the use of “GLOBAL.ASAX” file ?
It allows to executing ASP.NET application level events and setting application-level
variables.
(B) What is the difference between “Web.config” and
“Machine.Config” ?
226
“Web.config” files apply settings to each web application, while “Machine.config” file
apply settings to all ASP.NET applications.
(B) What is a SESSION and APPLICATION object ?
Session object store information between HTTP requests for a particular user, while
application object are global across users.
(A) What is the difference between Server.Transfer and
response.Redirect ?
Following are the major differences between them:-
√ Response.Redirect sends message to the browser saying it to move to some
different page, while server.transfer does not send any message to the browser
but rather redirects the user directly from the server itself. So in server.transfer
there is no round trip while response.redirect has a round trip and hence puts
a load on server.
√ Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is www.yahoo.com you can use server.transfer to move
to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e.
within websites. This cross server redirect is possible only using
Response.redirect.
√ With server.transfer you can preserve your information. It has a parameter
called as “preserveForm”. So the existing query string etc. will be able in the
calling page. In response.redirect you can maintain the state, but has
lot of drawbacks.
If you are navigating within the same website use “Server.transfer” or else go for
“response.redirect()”
(A)What is the difference between Authentication and
authorization?
This can be a tricky question. These two concepts seem altogether similar but there is
wide range of difference. Authentication is verifying the identity of a user and authorization
is process where we check does this identity have access rights to the system. In short we
227
can say the following authentication is the process of obtaining some sort of credentials
from the users and using those credentials to verify the user’s identity. Authorization is
the process of allowing an authenticated user access to resources. Authentication always
proceed to Authorization; even if your application lets anonymous users connect and use
the application, it still authenticates them as being anonymous.
(I) What is impersonation in ASP.NET ?
By default, ASP.NET executes in the security context of a restricted user account on the
local machine. Sometimes you need to access network resources such as a file on a shared
drive, which requires additional permissions. One way to overcome this restriction is to
use impersonation. With impersonation, ASP.NET can execute the request using the
identity of the client who is making the request, or ASP.NET can impersonate a specific
account you specify in web.config.
(B) Can you explain in brief how the ASP.NET authentication
process works?
ASP.NET does not run by itself, it runs inside the process of IIS. So there are two
authentication layers which exist in ASP.NET system. First authentication happens at
the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.
Below is how the whole process works:-
√ IIS first checks to make sure the incoming request comes from an IP address
that is allowed access to the domain. If not it denies the request.
√ Next IIS performs its own user authentication if it is configured to do so. By
default IIS allows anonymous access, so requests are automatically
authenticated, but you can change this default on a per – application basis
with in IIS.
√ If the request is passed to ASP.net with an authenticated user, ASP.net checks
to see whether impersonation is enabled. If impersonation is enabled, ASP.net
acts as though it were the authenticated user. If not ASP.net acts with its own
configured account.
√ Finally the identity from step 3 is used to request resources from the operating
system. If ASP.net authentication can obtain all the necessary resources it
grants the users request otherwise it is denied. Resources can include much
228
more than just the ASP.net page itself you can also use .Net’s code access
security features to extend this authorization step to disk files, Registry keys
and other resources.

Monday, May 5, 2008

DOTNET FAQS-8

oops concepts-2



(A) What are similarities between Class and structure ?
Following are the similarities between classes and structures :-
√ Both can have constructors, methods, properties, fields, constants,
enumerations, events, and event handlers.
√ Structures and classes can implement interface.
√ Both of them can have constructors with and without parameter.
√ Both can have delegates and events.
(A) What is the difference between Class and structure’s ?
Following are the key differences between them :-
√ Structure are value types and classes are reference types. So structures use
stack and classes use heap.
√ Structures members can not be declared as protected, but class members can
be. You can not do inheritance in structures.
√ Structures do not require constructors while classes require.
√ Objects created from classes are terminated using Garbage collector. Structures
are not destroyed using GC.
(B) What does virtual keyword mean ?
They are that method and property can be overridden.
(B) What are shared (VB.NET)/Static(C#) variables?
214
Static/Shared classes are used when a class provides functionality which is not specific to
any instance. In short if you want an object to be shared between multiple instances you
will use a static/Shared class.
Following are features of Static/Shared classes :-
√ They can not be instantiated. By default a object is created on the first method
call to that object.
√ Static/Shared classes can not be inherited.
√ Static/Shared classes can have only static members.
√ Static/Shared classes can have only static constructor.
Note :- In CD there is a folder “WindowsShared” which has a sample code for shared
variables.Below is a snippet. It has a “AddCount” function which increments a static
“intCount” variable. In form there are two buttons which creates a new object and displays
the count of the static variable. Even though the object is created and destroyed, the variable
values does not change. It retains its old value.
Public Class ClsShared
Shared intCount As Integer
Public Function AddCount() As Integer
intCount = intCount + 1
Return intCount
End Function
End Class
Public Class FrmSharedClasses
Inherits System.Windows.Forms.Form
Private Sub CmdInstance1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance1.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
End Sub
Private Sub CmdInstance2_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles CmdInstance2.Click
Dim pobjClsShared As New ClsShared()
MessageBox.Show(“The count at this moment is” &
pobjClsShared.AddCount.ToString())
215
End Sub
End Class
Figure :- 6.7 Shared/Static In Action
(B) What is Dispose method in .NET ?
.NET provides “Finalize” method in which we can clean up our resources. But relying on
this is not always good so the best is to implement “Idisposable” interface and implement
the “Dispose” method where you can put your clean up routines.
(B) What is the use of “OverRides” and “Overridable”
keywords ?
Overridable is used in parent class to indicate that a method can be overridden. Overrides
is used in the child class to indicate that you are overriding a method
(A) Where are all .NET Collection classes located ?
216
System.Collection namespace has all the collection classes available in .NET.
(A) What is ArrayList ?
Array is whose size can increase and decrease dynamically. Array list can hold item of
different types. As Array list can increase and decrease size dynamically you do not have
to use the REDIM keyword. You can access any item in array using the INDEX value of
the array position.
(A) What’s a HashTable ?
Twist :- What’s difference between HashTable and ArrayList ?
You can access array using INDEX value of array, but how many times you know the
real value of index. Hashtable provides way of accessing the index using a user identified
KEY value, thus removing the INDEX problem.
(A) What are queues and stacks ?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO)
structures.
(B) What is ENUM ?
It’s used to define constants.
(A) What is nested Classes ?
Nested classes are classes within classes. In sample below “ClsNested” class has a
“ChildNested” class nested inside it.
Public Class ClsNested
Public Class ChildNested
Public Sub ShowMessage()
MessageBox.Show(“Hi this is nested class”)
End Sub
End Class
End Class
This is the way we can instantiate the nested class and make the method call.
Dim pobjChildNested As New ClsNested.ChildNested()
pobjChildNested.ShowMessage()
217
Note:-In CD the above sample is provided in “WindowsNestedClasses”.
(B)What is Operator Overloading in .NET?
It provides a way to define and use operators such as +, -, and / for user-defined classes
or structs. It allows us to define/redefine the way operators work with our classes and
structs. This allows programmers to make their custom types look and feel like simple
types such as int and string.
VB.NET till now does not support operator overloading. Operator overloading is done
by using the “Operator” keyword.
Note:- Operator overloading is supported in VB.NET 2005
(I) In below sample code if we create a object of class2
which constructor will fire first ?
Public Class Class1
Sub New()
End Sub
End Class
Public Class class2
Inherits Class1
Sub New()
End Sub
End Class
* I leave this to the readers......
(B)What is the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged
resources (ex: - Windows API created objects, File, Database connection objects, COM
objects etc) is outside the scope of .NET framework we have to explicitly clean our
resources. For these types of objects .NET framework provides Object. Finalize method
218
which can be overridden and clean up code for unmanaged resources can be put in this
section.
(A)Why is it preferred to not use finalize for clean up?
Problem with finalize is that garbage collection has to make two rounds in order to remove
objects which have finalize methods.
Below figure will make things clear regarding the two rounds of garbage collection rounds
performed for the objects having finalized methods.
In this scenario there are three objects Object1, Object2 and Object3. Object2 has the
finalize method overridden and remaining objects do not have the finalize method
overridden.
Now when garbage collector runs for the first time it searches for objects whose memory
has to free. He can see three objects but only cleans the memory for Object1 and Object3.
Object2 it pushes to the finalization queue.
Now garbage collector runs for the second time. He see’s there are no objects to be
released and then checks for the finalization queue and at this moment it clears object2
from the memory.
So if you notice that object2 was released from memory in the second round and not first.
That’s why the best practice is not to write clean up Non.NET resources in Finalize
method rather use the DISPOSE.
219
Figure :- 6.8 Garbage collection in actions
(I)How can we suppress a finalize method?
GC.SuppressFinalize ()
(B)What is the use of DISPOSE method?
Dispose method belongs to IDisposable interface. We had seen in the previous section
how bad it can be to override the finalize method for writing the cleaning of unmanaged
resources. So if any object wants to release its unmanaged code best is to implement
220
IDisposable and override the Dispose method of IDisposable interface. Now once your
class has exposed the Dispose method it’s the responsibility of the client to call the
Dispose method to do the cleanup.
(A)How do I force the Dispose method to be called
automatically, as clients can forget to call Dispose method?
Note :- I admire this question.
Call the Dispose method in Finalize method and in Dispose method suppress the finalize
method using GC.SuppressFinalize. Below is the sample code of the pattern. This is the
best way we do clean our unallocated resources and yes not to forget we do not get the hit
of running the Garbage collector twice.
Note:- It will suppress the finalize method thus avoiding the two trip.
Public Class ClsTesting
Implements IDisposable
Public Overloads Sub Dispose()Implements IDisposable.Dispose
' write ytour clean up code here
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
Dispose()
End Sub
End Class
(I)In what instances you will declare a constructor to be
private?
When we create a private constructor, we can not create object of the class directly from
a client. So you will use private constructors when you do not want instances of the class
to be created by any external client. Example UTILITY functions in project will have no
221
instance and be used with out creating instance, as creating instances of the class would
be waste of memory.
(I)Can we have different access modifiers on get/set
methods of a property ?
No we can not have different modifiers same property. The access modifier on a property
applies to both its get and set accessors.
(I)If we write a goto or a return statement in try and catch
block will the finally block execute ?
The code in then finally always run even if there are statements like goto or a return
statements.
(A)What is Indexer ?
An indexer is a member that enables an object to be indexed in the same way as an array.
(A)Can we have static indexer in C# ?
No.
(A)In a program there are multiple catch blocks so can it
happen that two catch blocks are executed ?
No, once the proper catch section is executed the control goes finally to block. So there
will not be any scenarios in which multiple catch blocks will be executed.
(A) What is the difference between System.String and
System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety
of operations can be performed.

Friday, May 2, 2008

DOTNET FAQS-7

OOPS FAQS PART1::

(B) What is Object Oriented Programming ?
It is a problem solving technique to develop software systems. It is a technique to think
real world in terms of objects. Object maps the software model to real world concept.
These objects have responsibilities and provide services to application or other objects.
(B) What’s a Class ?
A class describes all the attributes of objects, as well as the methods that implement the
behavior of member objects. It’s a comprehensive data type which represents a blue print
of objects. It’s a template of object.
(B) What’s an Object ?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and
identity. Objects are members of a class. Attributes and behavior of an object are defined
by the class definition.
(A) What is the relation between Classes and Objects ?
They look very much same but are not same. Class is a definition, while object is a
instance of the class created. Class is a blue print while objects are actual objects existing
in real world. Example we have class CAR which has attributes and methods like Speed,
Brakes, Type of Car etc. Class CAR is just a prototype, now we can create real time
objects which can be used to provide functionality. Example we can create a Maruti car
object with 100 km speed and urgent brakes.
(B) What are different properties provided by Objectoriented
systems ?
Twist :- Can you explain different properties of Object Oriented Systems?
Note:- Difference between abstraction and encapsulation is one of the favorite interview
question and quiet confusing as both the terminology look alike. Best is if you can
brainstorm with your friends or do a little reading.
Following are characteristic’s of Object Oriented System’s :-
6. OOPS
201
Abstraction
It allows complex real world to be represented in simplified manner. Example color is
abstracted to RGB. By just making the combination of these three colors we can achieve
any color in world.It’s a model of real world or concept.
Encapsulation
It is a process of hiding all the internal details of an object from the outside world.
Communication using messages
When application wants to achieve certain task it can only be done using combination of
objects. A single object can not do all the task. Example if we want to make order processing
form.We will use Customer object, Order object, Product object and Payment object to
achieve this functionality. In short these objects should communicate with each other.
This is achieved when objects send messages to each other.
Object lifetime
All objects have life time.Objects are created ,and initialized, necessary functionalities
are done and later the object is destroyed. Every object have there own state and identity
which differ from instance to instance.
Class hierarchies (Inheritance and aggregation)
Twist :- What is difference between Association, Aggregation and Inheritance relationships?
In object oriented world objects have relation and hierarchies in between them. There are
basically three kind of relationship in Object Oriented world :-
Association
This is the simplest relationship between objects. Example every customer has sales. So
Customer object and sales object have an association relation between them.
Aggregation
This is also called as composition model. Example in order to make a “Accounts” class it
has use other objects example “Voucher”, “Journal” and “Cash” objects. So accounts
class is aggregation of these three objects.
202
Inheritance
Hierarchy is used to define more specialized classes based on a preexisting generalized
class. Example we have VEHICLE class and we can inherit this class make more
specialized class like CAR, which will add new attributes and use some existing qualities
of the parent class. Its shows more of a parent-child relationship. This kind of hierarchy
is called inheritance.
Polymorphism
When inheritance is used to extend a generalized class to a more specialized class, it
includes behavior of the top class(Generalized class). The inheriting class often implement
a behavior that can be somewhat different than the generalized class, but the name of the
behavior can be same. It is important that a given instance of an object use the correct
behavior, and the property of polymorphism allows this to happen automatically.
(B) How can we acheive inheritance in VB.NET ?
Note:- The following explanation is for VB.NET
Inheritance is achieved by using “Inherits” keyword in VB.NET (For C# it is “:”). Simple
Sample is provided in CD for understanding inheritance in folder
“WindowsApplicationInheritance”. There are two classes one is the parent “ClsParent”
and second is the child “ClsChild”. Parent class has a string which has to parsed for junk
data “@” and “/”.ClsParent has the functionality which parses only cleans up
“@”.”ClsChild” then inherits from parent and adds extra functionality by parsing “/”.
Public Class ClsParent
Protected strData As String = “jksdhkj@dadad///ajkdhsjakd”
Public Function Parse() As String
Dim PstrData As String
PstrData = strData
PstrData = Replace(PstrData, “@”, “”)
Return PstrData
End Function
Public Function GetActualString() As String
Return strData
End Function
End Class
Above is the source which parses only “@” of strData variable.
203
Public Class ClsChild
Inherits ClsParent
‘ this is child and a special parse function is added which will
also parse “/”
Public Function ParseBackSlash()
Dim PstrData As String
PstrData = Me.Parse()
PstrData = Replace(PstrData, “/”, “”)
Return PstrData
End Function
End Class
Above is the source code for “ClsChild” which does the remaining work. It adds extra
functionality by parsing “/” junk character’s of the data.
Note:- Strdata was accessible only because it was defined as protected in the parent class.
Figure :- 6.1 Inheritance in action
(I) What are abstract classes ?
Following are features of a abstract class :-
√ You can not create a object of abstract class
204
√ Abstract class is designed to act as a base class (to be inherited by other classes).
Abstract class is a design concept in program development and provides a
base upon which other classes are built.
√ Abstract classes are similar to interfaces. After declaring an abstract class, it
cannot be instantiated on its own, it must be inherited.
√ In VB.NET abstract classes are created using “MustInherit” keyword.In C#
we have “Abstract” keyword.
√ Abstract classes can have implementation or pure abstract methods which
should be implemented in the child class.
Note:- In order to understand the concept simple sample of add and multiply functionality
is implemented in “WindowsAbstract” folder in CD.
From interview point of view just saying using “MustInherit” keyword is more than enough
to convince that you have used abstract classes. But to clear simple fundamental let’s try
to understand the sample code. There are two classes one is “ClsAbstract” class and
other is “ClsChild” class. “ClsAbstract” class is a abstract class as you can see the
mustinherit keyword. It has one implemented method “Add” and other is abstract method
which has to be implemented by child class “MultiplyNumber”. In the child class we
inherit the abstract class and implement the multiplynumber function.
Definitely this sample does not take out actually how things are implemented in live
projects. Basically you put all your common functionalities or half implemented
functionality in parent abstract class and later let child class define the full functionality
of the abstract class. Example i always use abstract class with all my SET GET properties
of object in abstract class and later make specialize classes for insert, update, delete for
the corresponding entity object.
Public MustInherit Class ClsAbstract
‘ use the mustinherit class to declare the class as abstract
Public Function Add(ByVal intnum1 As Integer, ByVal intnum2 As
Integer) As Integer
Return intnum1 + intnum2
End Function
‘ left this seconf function to be completed by the inheriting
class
Public MustOverride Function MultiplyNumber(ByVal intnum1 As
Integer, ByVal intnum2 As Integer) As Integer
End Class
205
Public Class ClsChild
Inherits ClsAbstract
‘ class child overrides the Multiplynumber function
Public Overrides Function MultiplyNumber(ByVal intnum1 As
Integer, ByVal intnum2 As Integer) As Integer
Return intnum1 * intnum2
End Function
End Class
Figure :- 6.2 Abstract classes in action
My attitude towards abstract class has been that i put all my common functionality in
abstract class.
(B) What is a Interface ?
Interface is a contract that defines the signature of the functionality. So if a class is
implementing a interface it says to the outer world, that it provides specific behavior.
Example if a class is implementing Idisposable interface that means it has a functionality
to release unmanaged resources. Now external objects using this class know that it has
contract by which it can dispose unused unmanaged objects.
√ Single Class can implement multiple interfaces.
√ If a class implements a interface then it has to provide implementation to all
its methods.
206
Note:- In CD sample “WindowsInterFace” is provided, which has a simple interface
implemented.
In sample there are two files.One has the interface definition and other class implements
the interface. Below is the source code “IInterface” is the interface and “ClsDosomething”
implements the “IInterface”. This sample just displays a simple message box.
Public Interface IInterFace
Sub DoSomething()
End Interface
Public Class ClsDoSomething
Implements IInterFace
Public Sub DoSomething() Implements
WindowsInterFace.IInterFace.DoSomething
MsgBox(“Interface implemented”)
End Sub
End Class
Figure:- 6.3 Interface in action
207
(A) What is difference between abstract classes and
interfaces?
Following are the differences between abstract and interfaces :-
√ Abstract classes can have concrete methods while interfaces have no methods
implemented.
√ Interfaces do not come in inheriting chain, while abstract classes come in
inheritance.
(B) What is a delegate ?
Delegate is a class that can hold a reference to a method or a function. Delegate class has
a signature and it can only reference those methods whose signature is compliant with the
class. Delegates are type-safe functions pointers or callbacks.
Below is a sample code which shows a example of how to implement delegates.
Public Class FrmDelegates
Inherits System.Windows.Forms.Form
Public Delegate Sub DelegateAddString()
Private Sub FrmDelegates_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub AddString()
lstDelegates.Items.Add(“Running AddString() method”)
End Sub
Private Sub cmdDelegates_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdDelegates. Click
Dim objDelegateAddString As DelegateAddString
objDelegateAddString = AddressOf AddString
objDelegateAddString.Invoke()
End Sub
End Class
In the above there is a method called “AddString()” which adds a string to a listbox.You
can also see a delegate declared as :-
Public Delegate Sub DelegateAddString()
This delegate signature is compatible with the “AddString” method. When I mean
compatibility that means that there return types and passing parameter types are same.
208
Later in command click of the button object of the Delegate is created and the method
pointer is received from “AddressOf ” keyword. Then by using the “Invoke” method the
method is invoked.
Figure :- 6.4 Delegate in Action
(B) What are events ?
As compared to delegates events works with source and listener methodology. So listeners
who are interested in receiving some events they subscribe to the source. Once this
subscription is done the source raises events to its entire listener when needed. One
source can have multiple listeners.
In sample given below class “ClsWithEvents” is a event source class, which has a event
“EventAddString()”. Now the listeners who are interested in receiving this events they
can subscribe to this event. In class “FrmWithEvents” you can see they handle clause
which is associated with the “mobjClsWithEvents” objects.
Public Class ClsWithEvents
Event EventAddString(ByVal Value As String)
Public Sub AddString()
RaiseEvent EventAddString(“String added by Event”)
End Sub
End Class
209
Public Class FrmWithEvents
Inherits System.Windows.Forms.Form
Private WithEvents mobjClsWithEvents As New ClsWithEvents()
Private Sub FrmWithEvents_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub mobjClsWithEvents_EventAddString(ByVal Value As
String) Handles mobjClsWithEvents.EventAddString
LstData.Items.Add(Value)
End Sub
Private Sub CmdRunEvents_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CmdRunEvents.Click
mobjClsWithEvents.AddString()
End Sub
End Class
Figure :- 6.5 Events in action
Nore:- Above source code is provided in “WindowsEvent”
210
(I) Do events have return type ?
No, events do not have return type.
(A) Can event’s have access modifiers ?
Event’s are always public as they are meant to serve every one register ing to it. But you
can access modifiers in events.You can have events with protected keyword which will
be accessible only to inherited classes.You can have private events only for object in that
class.
(A) Can we have shared events ?
Yes, you can have shared event’s note only shared methods can raise shared events.
(I) What is shadowing ?
When two elements in a program have same name, one of them can hide and shadow the
other one. So in such cases the element which shadowed the main element is referenced.
Below is a sample code, there are two classes “ClsParent” and “ClsShadowedParent”. In
“ClsParent” there is a variable “x” which is a integer. “ClsShadowedParent” overrides
“ClsParent” and shadows the “x” variable to a string.
Note:- In Sample CD “WindowsShadowing” is folder which has the sample code. If you
run the program you can have two output’s one which shows a integer and other which shows
a string.
Public Class ClsParent
Public x As Integer
End Class
Public Class ClsShadowedParent
Inherits ClsParent
Public Shadows x As String
End Class
211
Figure :- 6.6 Shadowing in Action
(A) What is the difference between Shadowing and
Overriding ?
Following are the differences between shadowing and overriding :-
√ Overriding redefines only the implementation while shadowing redefines the
whole element.
√ In overriding derived classes can refer the parent class element by using “ME”
keyword, but in shadowing you can access it by “MYBASE”.
(I) What is the difference between delegate and events?
√ Actually events use delegates in bottom. But they add an extra layer on the
delegates, thus forming the publisher and subscriber model.
√ As delegates are function to pointers they can move across any clients. So any
of the clients can add or remove events, which can be pretty confusing. But
events give the extra protection by adding the layer and making it a publisher
and subscriber model.
212
Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the
error is.
(B) If we inherit a class do the private variables also get
inherited ?
Yes, the variables are inherited but can not be accessed directly by the class interface.
(B) What are the different accessibility levels defined in .NET
?
Following are the five levels of access modifiers :-
√ Private : Only members of class have access.
√ Protected :-All members in current class and in derived classes can access the
variables.
√ Friend (internal in C#) :- Only members in current project have access to the
elements.
√ Protected friend (protected internal in C#) :- All members in current project
and all members in derived class can access the variables.
√ Public :- All members have access in all classes and projects.
(I) Can you prevent a class from overriding ?
If you define a class as “Sealed” in C# and “NotInheritable” in VB.NET you can not
inherit the class any further.
(I) What is the use of “MustInherit” keyword in VB.NET ?
If you want to create a abstract class in VB.NET it’s done by using “MustInherit”
keyword.You can not create an object of a class which is marked as “MustInherit”. When
you define “MustInherit” keyword for class you can only use the class by inheriting.
213
Note :- There was huge typo in my previous versions for the above two questions. I hope
some one has not lost good oppurtunity because of the same. Thanks to all my readers for
pointing it out.
(I) Do interface have accessibility modifier?
All elements in Interface should be public. So by default all interface elements are public
by default.


NEXT>>>

Thursday, May 1, 2008

DOTNET FAQ-6

5. Caching Concepts

(B) What is an application object ?
Application object ca be n used in situation where we want data to be shared across users
globally.
(I)What’s the difference between Cache object and application object ?
The main difference between the Cache and Application objects is that the Cache object
provides cache-specific features, such as dependencies and expiration policies.
(I)How can get access to cache object ?
The Cache object is defined in the System.Web.Caching namespace. You can get a reference
to the Cache object by using the Cache property of the HttpContext class in the
System.Web namespace or by using the Cache property of the Page object.
(A)What are dependencies in cache and types of dependencies ?
When you add an item to the cache, you can define dependency relationships that can
force that item to be removed from the cache under specific activities of dependenci
es.Example if the cache object is dependent on file and when the file data changes you
want the cache object to be update. Following are the supported dependency :-
√ File dependency :- Allows you to invalidate a specific cache item when a disk
based file or files change.
√ Time-based expiration :- Allows you to invalidate a specific cache item
depending on predefined time.
√ Key dependency :-Allows you to invalidate a specific cache item depending
when another cached item changes.
5. Caching Concepts
179
(P)Can you show a simple code showing file dependency in cache ?
Partial Class Default_aspx
Public Sub displayAnnouncement()
Dim announcement As String
If Cache(“announcement”) Is Nothing Then
Dim file As New _
System.IO.StreamReader _
(Server.MapPath(“announcement.txt”))
announcement = file.ReadToEnd
file.Close()
Dim depends As New _
System.Web.Caching.CacheDependency _
(Server.MapPath(“announcement.txt”))
Cache.Insert(“announcement”, announcement, depends)
End If
Response.Write(CType(Cache(“announcement”), String))
End Sub
Private Sub Page_Init(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Init
displayAnnouncement()
End Sub
End Class
Note :- Above source code can be obtained from CD in “CacheSample”
folder.”Announcement.txt” is in the same folder which you can play around to see the
results.
Above given method displayAnnouncement() displays banner text from Announcement.txt
file which is lying in application path of the web directory. Above method first checks
whether the Cache object is nothing, if the cache object is nothing then it moves further
to load the cache data from the file. Whenever the file data changes the cache object is
removed and set to nothing.
(A) What is Cache Callback in Cache ?
Cache object is dependent on its dependencies example file based, time based etc...Cache
items remove the object when cache dependencies change.ASP.NET provides capability
to execute a callback method when that item is removed from cache.
180
(A) What is scavenging ?
When server running your ASP.NET application runs low on memory resources, items
are removed from cache depending on cache item priority. Cache item priority is set when
you add item to cache. By setting the cache item priority controls the items scavenging
are removed first.
(B) What are different types of caching using cache object of ASP.NET?
You can use two types of output caching to cache information that is to be transmitted to
and displayed in a Web browser:
√ Page Output Caching
Page output caching adds the response of page to cache object. Later
when page is requested page is displayed from cache rather than
creating the page object and displaying it. Page output caching
is good if the site is fairly static.
√ Page Fragment Caching
If parts of the page are changing, you can wrap the static sections as user
controls and cache the user controls using page fragment caching.
(B) How can you cache different version of same page using ASP.NET
cache object ?
Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET
page header. Below is the syntax
<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"
VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>
√ VaryByParam :- Caches different version depending on input parameters send
through HTTP POST/GET.
√ VaryByHeader:- Caches different version depending on the contents of the
page header.
181
√ VaryByCustom:-Lets you customize the way the cache handles page variations
by declaring the attribute and overriding the GetVaryByCustomString handler.
√ VaryByControl:-Caches different versions of a user control based on
the value of properties of ASP objects in the control.
(A) How will implement Page Fragment Caching ?
Page fragment caching involves the caching of a fragment of the page, rather than the
entire page. When portions of the page are need to be dynamically created for each user
request this is best method as compared to page caching. You can wrap Web Forms user
control and cache the control so that these portions of the page don’t need to be recreated
each time.
(B) What are ASP.NET session and compare ASP.NET session with
classic ASP session variables?
ASP.NET session caches per user session state. It basically uses “HttpSessionState” class.
Following are the limitations in classic ASP sessions :-
√ ASP session state is dependent on IIS process very heavily. So if IIS restarts
ASP session variables are also recycled.ASP.NET session can be independent
of the hosting environment thus ASP.NET session can maintained even if IIS
reboots.
√ ASP session state has no inherent solution to work with Web Farms.ASP.NET
session can be stored in state server and SQL SERVER which can support
multiple server.
√ ASP session only functions when browser supports cookies.ASP.NET session
can be used with browser side cookies or independent of it.
(B) Which various modes of storing ASP.NET session ?
√ InProc:- In this mode Session state is stored in the memory space of the
Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web
application restarts then session state is lost.
182
√ StateServer:-In this mode Session state is serialized and stored in a separate
process (Aspnet_state.exe); therefore, the state can be stored on a separate
computer(a state server).
√ SQL SERVER:- In this mode Session state is serialized and stored in a SQL
Server database.
Session state can be specified in element of application configuration
file. Using State Server and SQL SERVER session state can be shared across web farms
but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over
network again and again.
(A) Is Session_End event supported in all session modes ?
Session_End event occurs only in “Inproc mode”.”State Server” and “SQL SERVER”
do not have Session_End event.
(A) What are the precautions you will take in order that StateServer Mode
work properly ?
Following are the things to remember so that StateServer Mode works properly :-
√ StateServer mode session data is stored in a different process so you must
ensure that your objects are serializable.
elements in Web.config should be identical across all
servers.So this ensures that encryption format is same across all computers.
√ IIS metabase (\LM\W3SVC\2) must be identical across all servers in that
farm.
(A) What are the precautions you will take in order that SQLSERVER
Mode work properly ?
Following are the things to remember so that SQLSERVER Mode works properly :-
√ SQLSERVER mode session data is stored in a different process so you must
ensure that your objects are serializable.
√ IIS metabase (\LM\W3SVC\2) must be identical across all servers in that
farm.
183
√ By default Session objects are stored in “Tempdb”, you can configure it store
outside “TempDB” by running Microsoft provided SQL script.
Note :- “TempDB” database is re-created after SQL SERVER computer reboot.If you
want to maintain session state with every reboot best is to run SQL Script and store session
objects outside “TempDB” database.
(A) Where do you specify session state mode in ASP.NET ?
stateConnectionString=”tcpip=192.168.1.1:42424"
sqlConnectionString=”data source=192.168.1.1; Integrated
Security=SSPI”
cookieless=”false”
timeout=”20"
/>
Above is sample session state mode specified for SQL SERVER.
(B) What are the other ways you can maintain state ?
Other than session variables you can use the following technique to store state :
√ Hidden fields
√ View state
√ Hidden frames
√ Cookies
√ Query strings
(B) What are benefits and Limitation of using Hidden fields ?
Following are the benefits of using Hidden fields :-
√ They are simple to implement.
√ As data is cached on client side they work with Web Farms.
√ All browsers support hidden field.
√ No server resources are required.
Following are limitations of Hidden field :-
184
√ They can be tampered creating a security hole.
√ Page performance decreases if you store large data, as the data are stored in
pages itself.
√ Hidden fields do not support rich structures as HTML hidden fields are only
single valued. Then you have to work around with delimiters etc to handle
complex structures.
Below is how you will actually implement hidden field in a project
runat="server"NAME="HiddenValue">
(B) What is ViewState ?
Viewstate is a built-in structure for automatically retaining values amongst the multiple
requests for the same page. The viewstate is internally maintained as a hidden field on the
page but is hashed, providing greater security than developer-implemented hidden fields
do.
(A) Does the performance for viewstate vary according to User controls
?
Performance of viewstate varies depending on the type of server control to which it is
applied. Label, TextBox, CheckBox, RadioButton, and HyperLink are server controls
that perform well with ViewState. DropDownList, ListBox, DataGrid, and DataList suffer
from poor performance because of their size and the large amounts of data making
roundtrips to the server.
(B) What are benefits and Limitation of using Viewstate for state
management?
Following are the benefits of using Viewstate :-
√ No server resources are required because state is in a structure in
the page code.
√ Simplicity.
√ States are retained automatically.
185
√ The values in view state are hashed, compressed, and encoded, thus representing
a higher state of security than hidden fields.
√ View state is good for caching data in Web frame configurations because the
data is cached on the client.
Following are limitation of using Viewstate:-
√ Page loading and posting performance decreases when large values are
stored because view state is stored in the page.
√ Although view state stores data in a hashed format, it can still be tampered
because it is stored in a hidden field on the page. The information in the
hidden field can also be seen if the page output source is viewed directly,
creating a potential security risk.
Below is sample of storing values in view state.
this.ViewState["EnterTime"] = DateTime.Now.ToString();
(B) How can you use Hidden frames to cache client data ?
This technique is implemented by creating a Hidden frame in page which will contain
your data to be cached.

Above is a sample of hidden frames where the first frame “data_of_frame1.html” is visible
and the remaining frames are hidden by giving whole col section to first frame. See allocation
where 100 % is allocated to first frame and remaining frames thus remain hidden.
(I) What are benefits and limitations of using Hidden frames?
Following are the benefits of using hidden frames:
√ You can cache more than one data field.
√ The ability to cache and access data items stored in different hidden forms.
√ The ability to access JScript® variable values stored in different frames if they
come from the same site.
The limitations of using hidden frames are:
√ Hidden frames are not supported on all browsers.
√ Hidden frames data and be tampered thus creating security hole.
(I) What are benefits and limitations of using Cookies?
Following are benefits of using cookies for state management :-
√ No server resources are required as they are stored in client.
√ They are light weight and simple to use
Following are limitation of using cookies :-
√ Most browsers place a 4096-byte limit on the size of a cookie, although support
for 8192-byte cookies is becoming more common in the new browser and
client-device versions available today.
√ Some users disable their browser or client device’s ability to receive cookies,
thereby limiting the use of cookies.
√ Cookies can be tampered and thus creating a security hole.
√ Cookies can expire thus leading to inconsistency.
Below is sample code of implementing cookies
Request.Cookies.Add(New HttpCookie(“name”, “user1”))
(I) What is Query String and What are benefits and limitations of using
Query Strings?
A query string is information sent to the server appended to the end of a page URL.
Following are the benefits of using query string for state management:-
√ No server resources are required. The query string containing in the HTTP
requests for a specific URL.
√ All browsers support query strings.
Following are limitations of query string :-
√ Query string data is directly visible to user thus leading to security problems.-
√ Most browsers and client devices impose a 255-character limit on URL length.
Below is a sample “Login” query string passed in URL http://www.querystring.com/
login.asp?login=testing. This query string data can then be requested later by using
Request.QueryString(“login”).
(I) What is Absolute and Sliding expiration?
Absolute Expiration allows you to specify the duration of the cache, starting from the
time the cache is activated. The following example shows that the cache has a cache
dependency specified, as well as an expiration time of one minute.
Cache.Insert("announcement", announcement, depends, _
DateTime.Now.AddMinutes(1), Nothing)
Sliding Expiration specifies that the cache will expire if a request is not made within a
specified duration. Sliding expiration policy is useful whenever you have a large number
of items that need to be cached, because this policy enables you to keep only the most
frequently accessed items in memory. For example, the following code specifies that the
cache will have a sliding duration of one minute. If a request is made 59 seconds after the
cache is accessed, the validity of the cache would be reset to another minute:
Cache.Insert("announcement", announcement, depends, _
DateTime.MaxValue, _
TimeSpan.FromMinutes(1))
(I)What is cross page posting?
188
Note :- This is a new feature in ASP.NET 2.0
By default, button controls in ASP.NET pages post back to the same page that contains
the button, where you can write an event handler for the post. In most cases this is the
desired behavior, but occasionaly you will also want to be able to post to another page in
your application. The Server.Transfer method can be used to move between pages, however
the URL doesn't change. Instead, the cross page posting feature in ASP.NET 2.0 allows
you to fire a normal post back to a different page in the application. In the target page,
you can then access the values of server controls in the source page that initiated the post
back.
To use cross page posting, you can set the PostBackUrl property of a Button, LinkButton
or ImageButton control, which specifies the target page. In the target page, you can then
access the PreviousPage property to retrieve values from the source page. By default, the
PreviousPage property is of type Page, so you must access controls using the FindControl
method. You can also enable strongly-typed access to the source page by setting the
@PreviousPageType directive in the target page to the virtual path or Type name of the
source page.
Here is a step-by-step guide for implementing the cross-page post back using controls
that implement the IButtonControl interface.
√ Create a Web Form and insert a Button control on it using the VS .NET designer.
√ Set the button's PostBackUrl property to the Web Form you want to post back. For
instance in this case it is "nextpage.aspx"
PostBackUrl="~/nextpage.aspx" Text="Post to nextpage" />
When the PostBackUrl property of the IButtonControl is set, the ASP.NET framework
binds the corresponding HTML element to new JavaScript function named
WebForm_DoPostBackWithOptions. The corresponding HTML rendered by the ASP.NET
2.0 will look like this:

189
How do we access viewstate value of this page in the next page ?
View state is page specific; it contains information about controls embedded on the
particular page. ASP.NET 2.0 resolves this by embedding a hidden input field name,
__POSTBACK . This field is embedded only when there is an IButtonControl on the
page and its PostBackUrl property is set to a non-null value. This field contains the view
state information of the poster page. To access the view state of the poster page, you can
use the new PreviousPage property of the page:
Page poster = this.PreviousPage;
Then you can find any control from the previous page and read its state:
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;
This cross-page post back feature also solves the problem of posting a Form to multiple
pages, because each control, in theory, can point to different post back URL.
Can we post and access view state in another application?
You can post back to any page and pages in another application, too. But if you are
posting pages to another application, the PreviousPage property will return null. This is a
significant restriction, as it means that if you want to use the view state, you are confined,
for example, to posting to pages in the same virtual directory. Even so, this is a highly
acceptable addition to the functionality of ASP.NET.
What is SQL Cache Dependency in ASP.NET 2.0?
SQL cache dependencies is a new feature in ASP.NET 2.0 which can automatically
invalidate a cached data object (such as a Dataset) when the related data is modified in
the database. So for instance if you have a dataset which is tied up to a database tables
any changes in the database table will invalidate the cached data object which can be a
dataset or a data source.
How do we enable SQL Cache Dependency in ASP.NET 2.0?
Below are the broader steps to enable a SQL Cache Dependency:-
190
• Enable notifications for the database.
• Enable notifications for individual tables.
• Enable ASP.NET polling using “web.config” file
• Finally use the Cache dependency object in your ASP.NET code
Enable notifications for the database.
Before you can use SQL Server cache invalidation, you need to enable notifications for
the database. This task is performed with the aspnet_regsql.exe command-line utility,
which is located in the c:\[WinDir]\Microsoft.NET\Framework\[Version] directory.
aspnet_regsql -ed -E -d Northwind
-ed :- command-line switch
-E: - Use trusted connection
-S: - Specify server name it other than the current computer you are working on
-d: - Database Name
So now let’s try to understand what happens in the database because of
“aspnet_regsql.exe”. After we execute the “aspnet_regsql -ed -E -d Northwind” command
you will see one new table and four new stored procedures created.
Figure 5.1 : - SQL Cache table created for notification
Essentially, when a change takes place, a record is written in this table. The SQL Server
polling queries this table for changes.
191
Figure 5.2 : - New stored procedures created
Just to make brief run of what the stored procedures do.
“AspNet_SqlCacheRegisterTableStoredProcedure” :- This stored procedure sets a table
to support notifications. This process works by adding a notification trigger to the table,
which will fire when any row is inserted, deleted, or updated.
“AspNet_SqlCacheUnRegisterTableStoredProcedure”:- This stored procedure takes a
registered table and removes the notification trigger so that notifications won't be generated.
“AspNet_SqlCacheUpdateChangeIdStoredProcedure”:- The notification trigger calls this
stored procedure to update the AspNet_SqlCacheTablesForChangeNotification table,
thereby indicating that the table has changed.
AspNet_SqlCacheQueryRegisteredTablesStoredProcedure :- This extracts just the table
names from the AspNet_SqlCacheTablesForChangeNotification table. It’s used to get a
quick look at all the registered tables.
192
AspNet_SqlCachePollingStoredProcedure :- This will get the list of changes from the
AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling.
Enabling notification for individual tables
Once the necessary stored procedure and tables are created then we have to notify saying
which table needs to be enabled for notifications.
That can be achieved by two ways:-
√ aspnet_regsql -et -E -d Northwind -t Products
√ Exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName'
Registering tables for notification internally creates triggerfor the tables. For instance for
a “products” table the following trigger is created. So any modifications done to the
“Products” table will update the “AspNet_SqlCacheNotification’ table.
CREATE TRIGGER
dbo.[Products_AspNet_SqlCacheNotification_Trigger] ON
[Products]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
EXEC dbo.AspNet_SqlCacheUpdateChangeIdStoredProcedure
N'Products‘
END
“AspNet_SqlCacheTablesForChangeNotification” contains a single record for every table
you're monitoring. When you make a change in the table (such as inserting, deleting or
updating a record), the change Id column is incremented by 1.ASP.NET queries this table
repeatedly keeps track of the most recent changed values for every table. When this
value changes in a subsequent read, ASP.NET knows that the table has changed.
193
Figure 5.3 : - Entries in the Cache notification table
Enable ASP.NET polling using “web.config” file
Now that all our database side is configured in order to get the SQL Cache working in the
ASP.NET side we need to do some configuration in the web.config file.
We need to set two attributes in the “web.config” file:-
√ Set “Enabled” attribute to true to set the caching on.
√ Set the poll time attribute to the number of milliseconds between each poll
Below is the snapshot of the web.config file.
Figure 5.4 :- Web.config file modifications for SQL cache
194
Finally use the Cache dependency object in your ASP.NET code
Now comes the final step to use our cache dependency with programmatic data caching,
a data source control, and output caching.
For programmatic data caching, we need to create a new SqlCacheDependency and supply
that to the Cache.Insert() method. In the SqlCacheDependency constructor, you supply
two strings. The first is the name of the database you defined in the element in the section
of the web.config file e.g: Northwind. The second is the name of the linked table e.g:
Products.
private static void CacheProductsList(List products)
{SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind",
"Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency,
DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);}
private static List GetCachedProductList()
{return HttpContext.Current.Cache["ProductsList"] as List;}
ClsProductItem is business class, and here we are trying to cache a list of ClsProductItem
instead of DataSet or DataTable.
The following method is used by an ObjectDataSource Control to retrieve List of Products
public static List GetProductsList(int catId, string sortBy)
{
//Try to Get Products List from the Cache
List products = GetCachedProductList();
if (products == null)
{
//Products List not in the cache, so query the Database layer
ClsProductsDB db = new ClsProductsDB(_connectionString);
DbDataReader reader = null;
products = new List(80);
195
if (catId > 0)
{
//Return Product List from the Data Layer
reader = db.GetProductsList(catId);
}
else
{
//Return Product List from the Data Layer
reader = db.GetProductsList();
}
//Create List of Products -List if ClsProductItemproducts
= BuildProductsList(reader);
reader.Close();
//Add entry to products list in the Cache
CacheProductsList(products);
}
products.Sort(new ClsProductItemComparer(sortBy));
if (sortBy.Contains("DESC")) products.Reverse();
return products;
}
196
To perform the same trick with output caching, you simply need to set the SqlDependency
property with the database dependency name and the table name, separated by a colon:
<%@ OutputCache Duration="600" SqlDependency="Northwind:Products"
VaryByParam="none" %>
The same technique works with the SqlDataSource and ObjectDataSource controls:
SqlCacheDependency="Northwind:Products" ... />
Note :- ObjectDataSource doesn't support built in caching for Custom types such as the one
in our example. It only supports this feature for DataSets and DataTables.
Just to make a sample check run the SQL Server profiler and see that does the SQL
actually hit the database after the first run.
What is Post Cache substitution?
Post cache substitution is used when we want to cache the whole page but also need
some dynamic region inside that cached page. Some examples like QuoteoftheDay,
RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache
Substitution.
Post-cache substitution can be achieved by two means:
√ Call the new Response.WriteSubstitution method, passing it a reference to the desired
substitution method callback.
√ Add a control to the page at the desired location, and set its
methodName attribute to the name of the callback method.
197
Figure 5.5 : - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response
substitution callback to the “WriteSubstitution” method. So now when ASP.NET page
framework retrieves the cached page, it automatically triggers your callback method to
get the dynamic content. It then inserts your content into the cached HTML of the page.
Even if your page hasn't been cached yet (for example, it's being rendered for the first
time), ASP.NET still calls your callback in the same way to get the dynamic content. So
you create a method that generates some dynamic content, and by doing so you guarantee
that your method is always called, and it’s content is never cached.
Ok the above example was by using “WriteSubstitution” now lets try to see how we can
do by using “” control. You can get the “” control
from the editor toolbox.
198
Figure 5.6 : - Substitution Control
Figure 5.7 : - Substitution in Action.
199
Above is a sample code which shows how substitution control works. We have ASPX
code at the right hand side and class code at the behind code at the left hand side. We
need to provide the method name in the “methodname” attribute of the substitution
control.
Why do we need methods to be static for Post Cache substitution?
ASP.NET should be able to call this method even when there isn't an instance of your
page class available. When your page is served from the cache, the page object isn't
created. So ASP.NET skips the page life cycle when the page is coming from cache,
which means it won't create any control objects or raise any control events. If your dynamic
content depends on the values of other controls, you'll need to use a different technique,
because these control objects won't be available to your callback

Wednesday, April 30, 2008

DOTNET FAQ-5

4. Remoting and Webservices


(B)What is an application domain?
Previously “PROCESS” where used as security boundaries. One process has its own
virtual memory and does not over lap the other process virtual memory; due to this one
process can not crash the other process. So any problem or error in one process does not
affect the other process. In .NET they went one step ahead introducing application domains.
In application domains multiple applications can run in same process with out influencing
each other. If one of the application domains throws error it does not affect the other
application domains. To invoke method in a object running in different application domain
.NET remoting is used.
Figure :- 4.1 One process can have multiple Application domains
(B) What is .NET Remoting ?
.NET remoting is replacement of DCOM. Using .NET remoting you can make remote
object calls which lie in different Application Domains. As the remote objects run in
different process client calling the remote object can not call it directly. So the client uses
a proxy which looks like a real object.
When client wants to make method call on the remote object it uses proxy for it. These
method calls are called as “Messages”. Messages are serialized using “formatter” class
and sent to client “channel”. Client Channel communicates with Server Channel. Server
Channel uses as formatter to deserialize the message and sends to the remote object.
4. Remoting and Webservices
151
Figure :- 4.2 Channels, Formatters and Proxy in action.
(B) Which class does the remote object has to inherit ?
All remote objects should inherit from System.MarshalbyRefObject.
(I) What are two different types of remote object creation mode in .NET ?
There are two different ways in which object can be created using Remoting :-
√ SAO (Server Activated Objects) also called as Well-Known call mode.
√ CAO (Client Activated Objects)
SAO has two modes “Single Call” and “Singleton”. With Single Call object the object is
created with every method call thus making the object stateless. With Singleton the object
is created only once and the object is shared with all clients.
CAO are stateful as compared to SAO. In CAO the creation request is sent from client
side. Client holds a proxy to the server object created on server.
(A) Describe in detail Basic of SAO architecture of Remoting?
For these types of questions interviewer expects small and sweet answers. He is basically
looking at what you know about the specific subject. For these type of question this book
will provide detail code which is not necessary to be said during interview. Only the basic
steps and overall brief are enough to convince that you have knowledge about the subject.
Even though this question has detail code and answer say only what is needed in interview.
152
Remoting has at least three sections :-
√ Common Interface which will be shared between them.
√ Server.
√ Client.
Figure :- 4.3 Solution Explorer of Remoting Project
In CD “RemotingSample(SAO)” project is provided which gives a insight of remoting.
Above is the figure which shows the three important project sections needed to implement
remoting.
First important section is the common interface between Server and
Client.”InterFaceRemoting” project has the interface code. For sample project interface
is very simple with only two methods :- SetValue and GetValue.
Public Interface InterFaceRemoting
Sub SetValue(ByVal value As String)
Function GetValue() As String
End Interface
Second important section is the server.In this sample server is using HTTP channel and
the server object is singleton.
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Channels
Imports InterFaceRemoting
Public Class RemotingServer
Inherits MarshalByRefObject
153
Implements InterFaceRemoting.InterFaceRemoting
Private strData As String
Public Function GetValue() As String Implements
InterFaceRemoting.InterFaceRemoting.GetValue
Return strData
End Function
Sub New()
strData = “testing..”
End Sub
Public Sub SetValue(ByVal value As String) Implements
InterFaceRemoting.InterFaceRemoting.SetValue
strData = value
End Sub
End Class
Module ModuleRemotingStartUp
Sub Main()
Dim objHttpChannel As HttpChannel
Console.WriteLine(“Server Started....”)
objHttpChannel = New HttpChannel(1234)
ChannelServices.RegisterChannel(objHttpChannel)
RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
“RemoteObject”, WellKnownObjectMode.Singleton)
Console.WriteLine(“Server registered and listening waiting
for clients...”)
Console.ReadLine()
End Sub
End Module
Following is detail explanation :-
√ Channel object is created and registered.
Following is the code.
Dim objHttpChannel As HttpChannel
Console.WriteLine(“Server Started....”)
objHttpChannel = New HttpChannel(1234)
ChannelServices.RegisterChannel(objHttpChannel)
√ Server then hosts the object so that client can connect to it. This is the time
when we specify what mode the server object will be created i.e. Singleton or
SingleCall. This is done by the following below given code. Note in sample we
154
are hosting the server object in singleton mode that means that the same object
will be shared between all clients. Also note the server object is implementing
“InterFaceRemoting” and inheriting from “MarshalByRefObject”.
RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
“RemoteObject”, WellKnownObjectMode.Singleton)
Now comes the final section that is third section the client which will connect to this
hosted remoting object.
Following is a detail explanation of client code :-
√ First we create the channel i.e. HTTP. Note whatever channel the server is
using same will be used by the client.
ChannelServices.RegisterChannel(objHttpChannel)
√ As said before the common interface i.e.“InterFaceRemoting” will be used
to communicate with client.
√ After that we can get the server object reference using following code
objRemoting = CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),
“http://localhost:1234/RemoteObject”), InterFaceRemoting.InterFaceRemoting)
√ Then the client can make method call as if the object is local. But actually the
object is a proxy.
Console.WriteLine(“Value on server :- “ & objRemoting.GetValue.ToString())
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Channels
Imports InterFaceRemoting
Module ModuleStartClient
Sub Main()
Dim objHttpChannel As New HttpChannel
Dim objRemoting As InterFaceRemoting.InterFaceRemoting
ChannelServices.RegisterChannel(objHttpChannel)
objRemoting =
CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),
“http://localhost:1234/RemoteObject”),
155
InterFaceRemoting.InterFaceRemoting)
Console.WriteLine(“Referenced the main object.... Now
displaying Data”)
Console.WriteLine(“Value on server :- “ &
objRemoting.GetValue.ToString())
Console.WriteLine(“Press enter to Terminate”)
Console.ReadLine()
End Sub
End Module
You an run the program and see the output. For running the program run the server
program which is in server directory. Run “Server.exe” from BIN directory. If the EXE
runs properly following will be the screen as shown below.
Figure :- 4.4 Running Server Program of Remoting
Now run “Client.exe” from client folder in BIN directory.Following will be the output
seen.This means that the client connected to the server program and displayed the data in
the server object. In the server object we have initialized value “testing......”. In constructor
of class “RemotingServer” same value is displayed at the client side as shown in figure
below.
156
Figure :- 4.5 Client Program output of Remoting
(A) What are the situations you will use singleton architecture in
remoting ?
If all remoting clients have to share the same data singleton architecture will be used.
(A) What is fundamental of published or precreated objects in Remoting
?
In scenarios of singleton or single call the objects are created dynamically. But in situations
where you want to precreate object and publish it you will use published object scenarios.
Dim obj as new objRemote
obj.Initvalue = 100
RemotingServices.Marshal(obj,”RemoteObject”)
As shown in above sample following changes will be needed on server side.
RemotingConfiguration.RegisterWellKnownServiceType is replaced by
RemotingServices.Marshal(obj,”RemoteObject”) where “obj” is the precreated objected
on the server whose value is initialized to 100.
(A) What are the ways in which client can create object on server in CAO
model ?
There are two ways by which you can create Client objects on remoting server :-
157
√ Activator.CreateInstance().
√ By Keyword “New”.
(A) Are CAO stateful in nature ?
Yes. In CAO remoting model client creates a instance on server and instance variable set
by client on server can be retrieved again with correct value.
(A) In CAO model when we want client objects to be created by “NEW”
keyword is there any precautions to be taken ?
Remoting Clients and Remoting Server can communicate because they share a common
contract by implementing Shared Interface or Base Class (As seen in previous examples).
But according to OOP’s concept we can not create a object of interface or Base Classes
(Abstract Class). Shipping the server object to client is not a good design practice. In
CAO model we can use SOAPSUDS utility to generate Metadata DLL from server which
can be shipped to client, clients can then use this DLL for creating object on server. Run
the SOAPSUDS utility from visual studio command prompt for syntax see below :-
soapsuds -ia:RemotingServer -nowp -oa:ClientMetaData.dll
Where RemotingServer is your server class name.
ClientMetaData.dll is the DLL name by which you will want to create the metadll.
Server code will change as follows :-
ChannelServices.RegisterChannel(objHttpChannel)
RemotingConfiguration.ApplicationName = “RemoteObject”
RemotingConfiguration.RegisterActivatedServiceType(GetType(InterFaceRemoting.InterFaceRemoting))
Note :- We have to provide applicationname and register the object as ActivatedServiceType.
On client side we have to reference the generated ClientMetaData.dll from SOAPSUDS
utility. Below are changes which are needed to be incorporated at the Remoting Client :-
RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObject),“http://
localhost:1234/MyServer”)
Dim objRemoteObject as new RemoteObject().
158
RemoteObject is class which is obtained from ClientMetaData.dll which we created using
SOAPSUDS utility. Now you can reference the object as normal object.
(I) Is it a good design practice to distribute the implementation to
Remoting Client ?
It’s never advisable to distribute complete implementation at client, due to following
reasons:-
√ Any one can use ILDASM and decrypt your logic.
√ It’s a bad architecture move to have full implementation as client side as any
changes in implementation on server side you have to redistribute it again.
So the best way is to have a interface or SOAPSUDS generated meta-data DLL at client
side rather than having full implementation.
(A) What are LeaseTime, SponsorshipTime, RenewonCallTime and
LeaseManagerPollTime?
This is a very important question from practical implementation point of view. Companies
who have specific requirement for Remoting projects will expect this question to be answered.
In normal .NET environment objects lifetime is managed by garbage collector. But in
remoting environment remote clients can access objects which are out of control of
garbage collector. Garbage collector boundary is limited to a single PC on which framework
is running; any remote client across physical PC is out of control of GC (Garbage
Collector).
This constraint of garbage collector leads to a new way of handling lifetime for remoting
objects, by using concept called as “LeaseTime”. Every server side object is assigned by
default a “LeaseTime” of five minutes. This leasetime is decreased at certain intervals.
Again for every method call a default of two minutes is assigned. When i say method call
means every call made from client. This is called as “RenewalOnCallTime”.
Let’s put the whole thing in equation to make the concept more clear.
Total Remoting object life time = LeaseTime + (Number of method calls) X
(RenewalTime).
If we take NumberOfMethodCalls as one.
159
Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in
minutes)
When total object lifetime is reduced to zero, it queries the sponsor that should the object
be destroyed. Sponsor is an object which decides should object Lifetime be renewed. So
it queries any registered sponsors with the object, if does not find any then the object is
marked for garbage collection. After this garbage collection has whole control on the
object lifetime. If we do not foresee how long a object will be needed specify the
“SponsorShipTimeOut” value. SponsorShipTimeOut is time unit a call to a sponsor is
timed out.
“LeaseManagerPollTime” defines the time the sponsor has to return a lease time extension.
(A) Which config file has all the supported channels/protocol ?
Machine.config file has all the supported channels and formatter supported by .NET
remoting.Machine.config file can be found at
“C:\WINDOWS\Microsoft.NET\Framework\vXXXXX\CONFIG” path. Find
element in the Machine.config file which has the channels
and the formatters. Below is a figure shown which can give a clear idea of how the file
looks like.
Note :- Interviewer will not ask you to name all channels and formatters in machine.config
but will definitely like to know in which file are all the formatter and channels specified, one
sweet answer “Machine.config” can fetch you handsome job.
160
Figure :- 4.6 Channels and Formatter in machine.config file
(A) How can you specify remoting parameters using Config files ?
Both remoting server and remoting client parameters can be provided through config
files. Below is a sample of server config file which provides all remoting parameter values
which we where providing through code.




161
mode=”SingleCall”
type=”Server.ClsServer, Server”
objectUri=”RemoteObject” />







Later this config file can be loaded using the following code.
RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase
& “Server.config”)
Same way we also have client.config file for loading the client remoting parameters.




type=”CommonInterface.Icommon, Icommon”
url = “tcp://localhost:9000/Server/RemoteObject”/>







client remoting can then load the configuration file by using :-
Dim IobjCommon As CommonInterFace.Icommon
Dim StrData As String
Dim objServiceEntries As WellKnownClientTypeEntry()
RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase
& “Client.config”)
objServiceEntries =
RemotingConfiguration.GetRegisteredWellKnownClientTypes()
IobjCommon = Activator.GetObject(GetType(Icommon),
objServiceEntries(0).ObjectUrl.ToString())
StrData = IobjCommon.GetValue()
162
Console.WriteLine(“ Serve side Data is “ & StrData)
Console.ReadLine()
Note :- Complete source is provided in CD in folder “RemotingObjectLifeTime”.If you run
Server and Client following output can be seen. All source is compiled using VS2005
BETA1
Figure : - 4.7 Output of Server and Client for RemotingObjectLifeTime project
(A) Can Non-Default constructors be used with Single Call SAO?
Twist :- What are the limitation of constructors for Single call SAO ?
163
Non-Default constructors can not be used with single call objects as object is created
with every method call, there is no way to define Non-default constructors in method
calls.
It’s possible to use Non-Default constructor with Client activated objects as both methods
:-
“NEW” keyword and “Activator.CreateInstance” provide a way to specify Non-Default
constructors.
(I) How can we call methods in remoting Asynchronously ?
All previous examples are a synchronous method calls that means client has to wait until
the method completes the process. By using Delegates we can make Asynchronous method
calls.
(A) What is Asynchronous One-Way Calls ?
One-way calls are a different from asynchronous calls from execution angle that the .NET
Framework does not guarantee their execution. In addition, the methods used in this kind
of call cannot have return values or out parameters. One-way calls are defined by using
[OneWay()] attribute in class.
(B) What is marshalling and what are different kinds of marshalling ?
Marshaling is used when an object is converted so that it can be sent across the network
or across application domains. Unmarshaling creates an object from the marshaled data.
There are two ways to do marshalling :-
√ Marshal-by-value (MBV) :- In this the object is serialized into the channel, and
a copy of the object is created on the other side of the network. The object to
marshal is stored into a stream, and the stream is used to build a copy of the
object on the other side with the unmarshalling sequence.
√ Marshaling-by-reference (MBR):- Here it creates a proxy on the client that is
used to communicate with the remote object. The marshaling sequence of a
remote object creates an ObjRef instance that itself can be serialized across
the network.
Objects that are derived from “MarshalByRefObject” are always marshaled by reference.
All our previous samples have classes inherited from “MarshalByRefObject”
164
To marshal a remote object the static method RemotingServices.Marshal() is
used.RemotingServices.Marshal() has following overloaded versions:-
public static ObjRef Marshal(MarshalByRefObject obj)
public static ObjRef Marshal(MarshalByRefObject obj, string objUri)
public static ObjRef Marshal(MarshalByRefObject obj, string objUri,Type
requestedType)
The first argument obj specifies the object to marshal. The objUri is the path that is
stored within the marshaled object reference; it can be used to access the remote object.
The requestedType can be used to pass a different type of the object to the object reference.
This is useful if the client using the remote object shouldn't use the object class but an
interface that the remote object class implements instead. In this scenario the interface is
the requestedType that should be used for marshaling.
(A) What is ObjRef object in remoting ?
All Marshal() methods return ObjRef object.The ObjRef is serializable because it
implements the interface ISerializable, and can be marshaled by value. The ObjRef knows
about :-
√ location of the remote object
√ host name
√ port number
√ object name.
(B) What is a Web Service ?
Web Services are business logic components which provide functionality via the Internet
using standard protocols such as HTTP.
Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business
functionality.SOAP defines a standardized format in XML which can be exchanged
between two entities over standard protocols such as HTTP. SOAP is platform independent
so the consumer of a Web Service is therefore completely shielded from any
implementation details about the platform exposing the Web Service. For the consumer it
is simply a black box of send and receive XML over HTTP. So any web service hosted on
windows can also be consumed by UNIX and LINUX platform.
165
(B) What is UDDI ?
Full form of UDDI is Universal Description, Discovery and Integration. It is a directory
that can be used to publish and discover public Web Services. If you want to see more
details you can visit the http://www.UDDI.org .
(B) What is DISCO ?
DISCO is the abbreviated form of Discovery. It is basically used to club or group common
services together on a server and provides links to the schema documents of the services
it describes may require.
(B) What is WSDL?
Web Service Description Language (WSDL)is a W3C specification which defines XML
grammar for describing Web Services.XML grammar describes details such as:-
√ Where we can find the Web Service (its URI)?
√ What are the methods and properties that service supports?
√ Data type support.
√ Supported protocols
In short its a bible of what the webservice can do.Clients can consume this WSDL and
build proxy objects that clients use to communicate with the Web Services. Full WSDL
specification is available at http://www.w3.org/TR/wsdl.
(A) What the different phase/steps of acquiring a proxy object in
Webservice ?
Following are the different steps needed to get a proxy object of a webservice at
the client side :-
√ Client communicates to UDI node for WebService either through browser or
UDDI's public web service.
√ UDII responds with a list of webservice.
166
√ Every service listed by webservice has a URI pointing to DISCO or WSDL
document.
√ After parsing the DISCO document, we follow the URI for the WSDL document
related to the webservice which we need.
√ Client then parses the WSDL document and builds a proxy object which can
communicate with Webservice.
(B) What is file extension of Webservices ?
.ASMX is extension for Webservices.
Note :- After this we are going to deal with a sample of webservice. In VS2005 webproject
is created from the menu itself as compared to 2003 where it was present in the explorer.
167
Figure :- 4.8 Create Web project menu in VS2005
(B)Which attribute is used in order that the method can be used as
WebService ?
WebMethod attribute has to be specified in order that the method and property can be
treated as WebService.
(A) What are the steps to create a webservice and consume it ?
Note :- For this question this book will make a attempt by creating a simple webservice and
explaining steps to acheive it. A simple webservice will be created which takes two number
and gives addition result of the two number. In CD sample webservice project with folder
name “MathsWebService” is provided and same will be explained below. Definitely the
168
interviewer will not expect such a detail answer but this book will explain you in detail so
that you are on right track during interview.
This webservice will add two numbers and give to the calling client.All the below steps
are according to VS2005 beta editor :-
√ First create a website by clicking on File -- New WebSite.
√ From “Visual Studio Installed Templates” click on “Asp.NET Web Service”.
See figure below. Name the figure as “Maths Web Service”.
169
Figure :- 4.9 Create WebService Project
√ By default the .NET editor has made a default webservice method called as
"HelloWord" which returns a string datatype. Let's rename "Service.vb" to
"Maths.vb" and "Service.asmx" to "Maths.asmx". Let’s replace the
“HelloWorld” with following code below :-
_
Public Function AddTwoNumbers(ByVal Number1 As Integer, ByVal
Number2 As Integer) As Integer
Return Number1 + Number2
170
End Function
Figure :- 4.10 Rename all your default “Service” to “Maths”
√ After the webservice is done click on add Webreference. Normally for
components we do a “Add Reference” and for Webservices we do “Add Web
Reference”.
171
Figure :- 4.11 Click on Add Web Reference
√ You will be shown with a list of webservices which are known to the
solutions. As we are looking for our “Maths” webservice which exist in the
172
same solution, we click “Webservices in this solution”.
Figure :- 4.12 List of webservices for browsing
√ Your editor has located the “Maths” webservice.Select the webservice.
173
Figure :- 4.13 Solution showing the availability of Maths Webservice.
174
√ After you have clicked on “Maths” webservice you will see a search progress
bar as shown in figure below. This process will start the webservice, reference it
and create a proxy for the client, so that using it client can absorb the
webservice.
Figure :- 4.14 Starting the webservice and creating the proxy for your solution.
175
√ Finally you are able to see your webservice which is ready for use. Click on
Add Reference and you will see a “Localhost” reference in your .NET solution.
Figure :- 4.15 Starting the webservice and creating the proxy for your solution.
√ We need to make a client who will absorb this “Maths Webservice”. Add
“WebserviceClient.aspx” and create a UI as shown below. In the button click
put in the following code. “LocalHost.ClsMaths” is the proxy object by which
you can make calls to the webservice.
Sub cmdCalculate_Click(ByVal sender As Object, ByVal e As
176
System.EventArgs)
Dim pobjMaths As New localhost.ClsMaths
lblResultDisplay.Text =
Convert.ToString(pobjMaths.AddTwoNumbers(Convert.ToInt16(txtNumber1.Text),
Convert.ToInt16(txtNumber2.Text)))
End Sub
Figure :- 4.16 Complete Webservice in action.
Note :- The whole point of creating this “Maths Webservice” step by step was to have a
understanding of practical angle of how webservices are created. It’s very rare that you will
be asked to explain every step of how to write a webservice. But in case your interviewer is
too bend down to also know what are the actual steps in creating a Webservice.
(A) Do webservice have state ?
Twist :- How can we maintain State in Webservices ?
177
Webservices as such do not have any mechanism by which they can maintain state.
Webservices can access ASP.NET intrinsic objects like Session, application and so on if
they inherit from “WebService” base class.
<%@ Webservice class="TestWebServiceClass" %>
Imports System.Web.Services
Public class TestWebServiceClass
Inherits WebService
Public Sub SetSession(value As String)
session("Val") = Value
End Sub
end class
Above is a sample code which sets as session object called as “val”. TestWebserviceClass
is inheriting from WebService to access the session and application objects.

Monday, April 28, 2008

DOTNET FAQ-4

3. Threading

(B)What is Multi-tasking ?
It’s a feature of modern operating systems with which we can run multiple programs at
same time example Word, Excel etc.
(B)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking. Instead of having to switch between
programs this feature switches between different parts of the same program. Example
you are writing in word and at the same time word is doing a spell check in background.
(B)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(B)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a freethreading
model, which allows multiple threads to run against the same set of data.
(B)Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation
of a logical process within a physical process. Each AppDomain is started with a single
thread, but can create additional threads from any of its threads.
Note :- All threading classes are defined in System.Threading namespace.
(B)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading. Any .NET application
who wants to implement threading has to import this namespace.
Note :- .NET program always has at least two threads running one is the main program
and second is the garbage collector.
(I)Can you explain in brief how can we implement threading ?
3. Threading
143
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread(AddressOf Thread1)
Dim pthread2 As New Thread(AddressOf Thread2)
pthread1.Start()
pthread2.Start()
End Sub
Public Sub Thread1()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is first thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Public Sub Thread2()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is second thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Above is a sample code which shows simple sample code for threading. Above sample
code can be found in “Threading” folder in CD provided. Above sample has two methods
“Thread1()” and “Thread2()” which are started in multi-threaded mode in Form load
event of the sample.
Note :- If you run the sample you will see that sometimes the first thread runs first and
then the second thread.This happens because of thread priorities . The first thread is run
with highest priority.
(A)How can we change priority and what the levels of priority are
provided by .NET ?
144
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.
In the sample provided look out for code where the second thread is ran with a high
priority.
Following are different levels of Priority provided by .NET :-
√ ThreadPriority.Highest
√ ThreadPriority.AboveNormal
√ ThreadPriority.Normal
√ ThreadPriority.BelowNormal
√ ThreadPriority.Lowest
(A)What does AddressOf operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A
delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread
has been instantiated, you begin the execution of the code by calling the Start() method
of the thread
(A)How can you reference current thread of the method ?
"Thread.CurrentThread" refers to the current thread running in the
method."CurrentThread" is a public static property.
(I) What's Thread.Sleep() in threading ?
Thread's execution can be paused by calling the Thread.Sleep method. This method takes
an integer value that determines how long the thread should sleep. Example
Thread.CurrentThread.Sleep(2000).
(A)How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by
calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can
call the Thread.Interrupt method.
(A) What is Suspend and Resume in Threading ?
145
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another
thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter
does not immediately place a thread in the wait state. The thread does not suspend until
the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately
place a thread in a wait state.
Note :- In threading interviews most people get confused with Sleep and Suspend. They look
very similar.
(A)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
(A) How do I debug thread ?
Figure :- 3.1 Debug thread window
This window is only seen when the program is running in debug mode. In windows one of
the window is “Threads”.
146
(A)What is Thread.Join() in threading ?
There are two versions of Thread.Join :-
√ Thread.join().
√ Thread.join(Integer) this returns a Boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting
another task. The Join method waits a specified amount of time for a thread to end. If the
thread ends before the time-out, Join returns true; otherwise it returns False. Once you
call Join, the calling procedure stops and waits for the thread to signal that it is done.
Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call
"Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution
and the again invoke "Thread1".
Thread.Join(Integer) ensures that threads do not wait for a long time. If it exceeds a
specific time which is provided in integer the waiting thread will start.
(A)What are Daemon threads and how can a thread be created as
Daemon?
Daemon thread's run in background and stop automatically when nothing is running
program. Example of a Daemon thread is "Garbage collector". Garbage collector runs
until some .NET code is running or else its idle.
You can make a thread Daemon by
Thread.Isbackground=true
(A) When working with shared data in threading how do you implement
synchronization ?
There are certain somethings that you need to be careful with when using threads. If two
threads (e.g. the main and any worker threads) try to access the same variable at the same
time, you'll have a problem. This can be very difficult to debug because they may not
always do it at exactly the same time. To avoid the problem, you can lock a variable
147
before accessing it. However, if the two threads lock the same variable at the same time,
you'll have a deadlock problem.
SyncLock x
'Do something with x
End SyncLock
(I)Can we use events with threading ?
Yes, you can use events with thread; this is one of the techniques to synchronize one
thread with other.
(A)How can we know a state of a thread?
"ThreadState" property can be used to get detail of a thread. Thread can have one or a
combination of status.System.Threading. Threadstate enumeration has all the values to
detect a state of thread. Some sample states are Isrunning, IsAlive, suspended etc.
(A) What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :-
√ Increment Values.
√ Decrement values.
√ Exchange values between variables.
√ Compare values from any thread.
in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)
(A) What is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by
code running on other threads. In other words, code in other threads cannot run until
code in the synchronized code block has finished.
SyncLock and End SyncLock statements are provided in order to simplify access to monitor
object.
148
(A) What are wait handles ?
Twist :- What is a mutex object ?
Wait handles sends signals of a thread status from one thread to other thread. There are
three kind of wait modes :-
√ WaitOne.
√ WaitAny.
√ WaitAll.
When a thread wants to release a Wait handle it can call Set method. You can use Mutex
(mutually exclusive) objects to avail for the following modes. Mutex objects are
synchronization objects that can only be owned by a single thread at a time. Threads
request ownership of the mutex object when they require exclusive access to a resource.
Because only one thread can own a mutex object at any time, other threads must wait for
ownership of a mutex object before using the resource.
The WaitOne method causes a calling thread to wait for ownership of a mutex object. If
a thread terminates normally while owning a mutex object, the state of the mutex object
is set to be signaled and the next waiting thread gets ownership
(A) What is ManualResetEvent and AutoResetEvent ?
Threads that call one of the wait methods of a synchronization event must wait until
another thread signals the event by calling the Set method. There are two synchronization
event classes. Threads set the status of ManualResetEvent instances to signaled using
the Set method. Threads set the status of ManualResetEvent instances to no signaled
using the Reset method or when control returns to a waiting WaitOne call. Instances of
the AutoResetEvent class can also be set to signaled using Set, but they automatically
return to nonsignaled as soon as a waiting thread is notified that the event became signaled.
(A) What is ReaderWriter Locks ?
You may want to lock a resource only when data is being written and permit multiple
clients to simultaneously read data when data is not being updated. The ReaderWriterLock
class enforces exclusive access to a resource while a thread is modifying the resource, but
it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful
alternative to exclusive locks that cause other threads to wait, even when those threads
do not need to update data.
(I) How can you avoid deadlock in threading?
A good and careful planning can avoid deadlocks.There are so many ways Microsoft has
provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait
handles, Event raising from one thread to other thread, ThreadState property which you
can poll and act accordingly etc.
(B) What is the difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that
share the same virtual memory. A process has at least one thread of execution, and a
thread always run in a process context.
Note:- Its difficult to cover threading interview question in this small chapter. These
questions can take only to a basic level. If you are attending interviews where people are
looking for threading specialist, try to get deeper in to synchronization issues as that's the
important point they will stress.