Monday, June 30, 2008

.NET Architecture

Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns
√ Mediator:-Defines simplified communication between classes.
√ Memento:-Capture and restore an object's internal state.
√ Interpreter:-A way to include language elements in a program.
√ Iterator:-Sequentially access the elements of a collection.
√ Chain of Resp:-A way of passing a request between a chain of objects.
√ Command:-Encapsulate a command request as an object.
√ State:-Alter an object's behavior when its state changes.
√ Strategy:-Encapsulates an algorithm inside a class.
√ Observer:-A way of notifying change to a number of classes.
√ Template Method:-Defer the exact steps of an algorithm to a subclass.
√ Visitor:-Defines a new operation to a class without change.
Note :- Just remember Music....... 2 MICS On TV (MMIICCSSOTV).
Note:- No source code is provided for architecture section. As much of the things can be
clear from good UML diagrams.
(A)What’s difference between Factory and Abstract Factory Pattern’s?
Note: - This is quiet a confusing architect question especially in design pattern section.
Interviewer can take you for a nice ride …. So get the difference’s in your heart.
First read the definition provided in the first question about both these patterns. The
common thing they have is that they belong to creational patterns. In short they hide the
complexity of creating objects.
The main difference between factory and Abstract factory is factory method uses
inheritance to decide which object has to be instantiated. While abstract factory uses
delegation to decide instantiation of object. We can say Abstract factory uses factory
method to complete the architecture. Abstract Factory is one level higher in abstraction
over Factory.
151
The below two class diagrams will provide overview of what the actual difference is.
First figure shows a sample implementation of Factory Patterns. In this figure there are
two basic sections:-
√ The actual product section i.e. Class “Product” it inherits from a abstract
class “AbstractProduct”.
√ The creational aspect section that’s “ConcreteCreator” class which inherits
from class “Creator”.
√ Now there are some rules the client who will need the “Product” object will
have to follow. He will never refer directly to the actual “Product” object he
will refer the “Product” object using “AbstractProduct”.
√ Second client will never use “New” keyword to create the “Product” object
but will use the “Creator” class which in turn will use the “ConcreteCreator”
class to create the actual “Product” object.
Figure: - 8.1 Class diagram of a factory Pattern
So what are benefits from this architecture? All creational and initializing aspects are
now detached from the actual client. As your creational aspect is now been handled in
“ConcreteCreator” and the client has reference to only “Creator”, so any implementation
change in “CreateProduct” will not affect the client code. In short now your creational
aspect of object is completely encapsulated from the client’s logic.
Now let’s look at the second class diagram which provides an overview of what actually
“Abstract factory” pattern is. It creates objects for families of classes. In short it describes
collection of factor methods from various different families. In short it groups related
152
factory methods. Example in this the class “Creator” is implemented using the “Abstract”
factory pattern. It now creates objects from multiple families rather one product.
Note :- Just stick up to this definition that Abstract factory classifies factory methods or
groups logically related factory method together..
Figure:- 8.2 Class Diagram of Abstract Factory
153
(I)What’s MVC pattern?
Twist: - How can you implement MVC pattern in ASP.NET?
The main purpose using MVC pattern is to decouple the GUI from the Data. It also gives
the ability to provide multiple views for the same Data. MVC pattern separates objects in
to three important sections:-
√ Model: - This section is specially for maintaining data. It is actually where your
business logic, querying database, database connection etc. is actually
implemented.
√ Views: - Displaying all or some portion of data, or probably different view of
data. View is responsible for look and feel, Sorting, formatting etc.
√ Controller: - They are event handling section which affects either the model or
the view. Controller responds to the mouse or keyboard input to command
model and view to change. Controllers are associated with views. User
interaction triggers the events to change the model, which in turn calls some
methods of model to update its state to notify other registered views to refresh
their display.
Ok now this was all in theory. Let’s look at how in actually ASP.NET can we implement
MVC pattern. During interview with theory they will be looking at more have you really
implemented MVC or its just talks. Following are the various sections of ASP.NET which
maps to MVC sections:-
√ Model: - This section is represented by Data view, Dataset, Typed Dataset,
Business components, business entity models etc. Now this section can then
be tied up to either windows application or web UI.
√ View: - ASPX, ASCX, or windows application UI like data grid etc. form the
view part of it.
√ Controller: - In ASP.NET the behind code is the controller. As the events are
handled by that part. Controller communicates both with Model as well as
view.
I hope I was able to map you imagination of ASP.NET with the diagram given below.
154
Figure: - 8. 3 Data flow between MVC architectures.
(A)How can we implement singleton pattern in .NET?
Singleton pattern mainly focuses on having one and only one instance of the object running.
Example a windows directory service which has multiple entries but you can only have
single instance of it through out the network.
Note:- May of developers would jump to a conclusion saying using the “STATIC” keyword
we can have a single instance of object. But that’s not the real case there is something more
that has to be done. But please note we can not define a class as STATIC, so this will not
serve our actual purpose of implementing singleton pattern.
Following are the three steps needed to implement singleton pattern in .NET:-
155
√ First create your class with static members.
Public class ClsStaticClass
Private shared objCustomer as clsCustomer
End class
This ensures that there is actually only one Customer object through out the project.
√ Second define a private constructor to your class.
Note: - defining a private constructor to class does not allow a client to create objects directly.
√ Finally provide a static method to get access to your singleton object.
(A)How do you implement prototype pattern in .NET?
Twist: - How to implement cloning in .NET ? , What is shallow copy and deep copy ?
Cloning is achieved by using ICloneable of the System namespace. It has a “Clone” method
which actually returns the reference of the same copy. Clone method allows a Shallow
copy and not a deep copy. In Shallow copy if you make changes to the cloned object it
actually does change on the main object itself. So how is deep copy achieved, by using
“ISerializable” interface? So what you do is first serialize the object then deserialize back
to a complete new copy. Now any changes to this new copy do not reflect on the original
copy of the object, this is called as Deep copy.
(I)What are the situations you will use a Web Service and Remoting in
projects?
Well “Web services” uses “remoting” concepts internally. But the major difference between
“web service” and “remoting” is that “web service” can be consumed by clients who are
not .NET platform. While remoting you need the client to be .NET compliant. Regarding
the speed issue “Remoting” is faster than “Web Services”. So I think when deciding the
architecture side of choosing between “Web services” and “Remoting” keep the cross
platform issue and the speed issue in mind.
(A)Can you give a practical implementation of FAÇADE patterns?
156
Façade pattern sits on the top of lot of subsystems and makes access easy to interfaces
of these subsystems. Basic purpose of Façade is to make interfacing between many
modules and classes manageable.
Figure: - 8.4 Façade in action
Above is a simple live application of a Façade class. In this we have four subsystems :-
√ Customer
√ Product
157
√ Payment
√ Invoicing
All the four modules when built at initial stage where built completely independent. The
main interaction between all these subsystems is customer placing order. This functionality
can be attained by using all these subsystems, which involves complex interaction between
them.
There’s where FAÇADE comes in to action. We have built a FAÇADE called as
“FACADEORDER” which sits on the top of all these subsystem and fulfills our
functionality.
(I) How can we implement observer pattern in .NET?
Observer patterns can be implemented using “Delegates” and “Events”. I leave this to
the readers to implement one sample code for observer patterns.
(B)What is three tier architecture?
The three tier software architecture emerged in the 1990s to overcome the limitations of
the two tier architecture.
There are three layers in when we talk about three tier architecture:-
User Interface (Client) :- This is mostly the windows user interface or the Web interface.
But this has only the UI part.
Mid layer: - Middle tier provides process management where business logic and rules are
executed and can accommodate hundreds of users (as compared to only 100 users with
the two tier architecture) by providing functions such as queuing, application execution,
and database staging.
Data Access Layer: - This is also called by the famous acronym "DAL" component. It has
mainly the SQL statement which do the database operation part of the job.
The three tier architecture is used when an effective distributed client/server design is
needed that provides (when compared to the two tier) increased performance, flexibility,
maintainability, reusability, and scalability, while hiding the complexity of distributed
processing from the user.
158
(I)Have you ever worked with Microsoft Application Blocks, if yes then
which?
Application Blocks are C# and VB.NET classes distributed as Visual Studio projects
that can be downloaded from Microsoft's Web site and used in any .NET application,
including ASP.NET Web applications. They are useful and powerful tools that can make
applications more maintainable, scalable and efficient
The second question which of the application blocks has been used depends on really
what you have implemented. But there are two famous MAB which is making buzz around
the industry:-
√ data access block
The Data Access Block provides static methods located in the SqlHelper class
that encapsulates the most common data access tasks performed with Microsoft
SQL server. If the term "static method" is new to you, it means that the class
methods can be called without instantiating an instance of the class. For
example, the method ExecuteReader () within the SqlHelper class can be called
by simply using the statement SqlHelper.ExecuteReader () -- no object
instantiation of the SqlHelper class is required.
√ Exception management block.
The Exception Management Application Block provides a simple yet extensible
framework for handling exceptions. With a single line of application code you
can easily log exception information to the Event Log or extend it by creating
your own components that log exception details to other data sources or notify
operators, without affecting your application code. The Exception Management
Application Block can easily be used as a building block in your own .NET
application
Note: - It’s beyond the scope the book to look in to details of application block. Best is go to
www.microsoft.com and search for these application block. Try to compile one or two
programs using there given classes and documentation.
(A)What is Service Oriented architecture?
“Services” are components which expose well defined interfaces and these interfaces
communicate through XML messages. Using SOA you can build workflow, which uses
159
interfaces of these components. SOA is typically useful when you are crossing
heterogeneous technical boundaries, organizations, domain etc.
In .NET SOA technically uses Web services to communicate with each service which is
crossing boundaries. You can look SOA which sits on TOP of web services and provides
a workflow.
SOA uses service components which operate in there own domain boundary. Let’s note
some points of service :-
√ They are independent components and operate in there own boundary and
own technology.
√ They have well defined interfaces which use XML and WSDL to describe
themselves.
√ Services have URL where any one can find them and clients can bind to these
URL to avail for the service.
√ Services have very loosely coupled architecture. In order to communicate to
service you only have to know the WSDL. Your client can then generate proxy
from the WSDL of the service.
160
Figure: - 8.5 SOA basic architecture
Above figure describes a broader picture of what service oriented architecture will look
like. The basic fundamental of SOA is a web service. In above diagram you can see there
are two services available. One is the “Credit Card” service and other is “Address Check”
161
web service. Both these services are provided by different company. Now we want to
build a functionality which needs to validate a credit card and also check that addresses
are proper. In short we will need functionalities of both the “CreditCard” and
“AddressCheck” service. Also note the “CreditCard” service has its own business layer
and DAL components, which can be in a proprietary language. It’s very much possible
that the whole Credit card service is made in .NET and the Address check is SAP
implementation or JAVA implementation. But because both the systems provide there
functionality using Web services which is nothing but basically XML message
communication. So we have made new service which sits like a FAÇADE on top of both
the web service and performs both functionalities in one common service. You will see I
have made a third service which sits on top of both the webservice and consumes them.
Also you can see that the UI part of the systems have access to Buisness layer and Web
service of there system. But the service which does both these check has only access to
the Web service.
Note:- It’s beyond the scope of this book to discuss about SOA. But just to keep you safe
during interview this book has tried to clear some basics of SOA.
(I)What are different ways you can pass data between tiers?
There are many ways you can pass data between tiers :-
√ Dataset the most preferred one as they maintain data in XML format.
√ Datareader
√ Custom classes.
√ XML
(A)What is Windows DNA architecture?
Note :- If you have worked with classic ASP this question can come to you.
The Windows Distributed interNet Applications Architecture (DNA) is a Microsoft
blueprint for robust, scalable, distributed business software. Windows DNA has evolved
over time and was not preplanned. It gives all combined advantages of Centralized
mainframe, application servers, internet technologies and Personal computers. Windows
DNA is a evolution which started from mainframes (Where all logic was centralized) ,
Fox pro ages ( Where we talked in terms of two tier systems) , VB6 / SQL SERVER
(Three tier where we talked in terms of having one more tier which was mainly COM
162
where business logic resided) , COM+ ( looking in terms of transactions and fulfilling
ACID rules) and finally the DNA.
Figure :- 8.6 Windows DNA sections
Above shown is a Windows DNA model which is a blue print which Microsoft has
proposed. So if interviewer is asking you have you worked with Windows DNA , then
answer is yes. You will see that you always use these sections in project. Do not get
confused with the terminology DNA.
163
(A)What is aspect oriented programming?
Note :- This is something which is catching up the market so interviewer can ask you to see
how you are in touch with the market.So probably this explanation can be quiet long but
bear with me it is worth of it
I will try to be as short as possible as this book is not a reference book. Just to save you
from interviewer I will give a short description of aspect oriented programming in .NET.
First let's try to define it which can probably save you during interview
Aspect-oriented software development is a new technology for separation of concerns (SOC)
in software development. The techniques of AOSD make it possible to modularize
crosscutting aspects of a system.
Ok that statement’s can save you for the first stage let’s get down actually what is it. Let’s
revisit back how software development cycle evolved.
When we look back at times of Cobol where we used to break the modules in small
functionalities and use reusability to its maximum.
Then came the time when we talked in terms of Objects where things where clearer as
software was modeled in terms of real life examples. It worked fine and till today is the
most accepted way of implementing and organizing project. So why AOP ?
Aspect oriented programming does not oppose OOP’s but rather supports it and make’s
it more maintainable. So remove the logic from head the AOP is replacement of OOP.
No its brother of OOP helping him to be better.
When we talk in terms of object’s it’s an entity which maps to real world domain. Object
has attributes which represent the state of object and also define its behavior. By rule of
object oriented programming object should be stand alone and communicate with other
object’s using messages or defined interface.
One object should not communicate with other object directly rather communicate through
defined interfaces. Every object satisfies some “Concern” in relation to the system.
Twist: - What is Concern in AOP?
“A concern is a particular goal, concept, or area of interest”
There are mainly two types of concern from an object perspective:-
√ Core / Main concerns which it should satisfy and is his work.
I hope in my second edition i will come out with a seperate chapter on AOP
164
√ System concerns which are not related to business functionalities but software
related concerns example audit trail, Error handling, Security etc.
Ok let’s try to understand this principle by some actual example.
Figure :- 8.7 Customer and Audit trail relationships
Above is a class diagram which shows relationshipbetween two classes “ClsCustomer”
and “ClsAuditTrail”. “ClsCustomer” class does inserting of new customer’s in to database
and “ClsAuditTrail” does the auditing of what is changed in the customer class.
Now there are two concerns in this project :-
√ Customer code should not exceed greater than 10 length (Business level
concern)
√ All customer data which is updated should be audited. (System level concern)
Here goes the class code. If you see the ClsCustomer implementation in the update method
I have called the Audit trail implementation. If you really look from object oriented point
of view we are doing something in customer class which is supposed to be not his
implementation: - Audit Trail logging. Thus we have also broken down the rule of
165
encapsulation. In short the class not only handles his work but also some other work
which is not his concern.
Ok now lets define crosscutting which is one of important aspect’s of AOP.
Twist :- What is cross cutting in AOP ?
When one or many concerns span across module its called as cross cutting.Example in
our audit trail example we will probably need to audit trail for customer as well as supplier.So
Audit trail can span across other objects also that is termed as cross cutting.
Below are both the classes actually implemented as per class diagram 8.7. If you see the
“Update” method of the customer class , its doing both of the concerns that is checking
for customer code length and also maintaining the audit trail using the audit trail class.
Public Class ClsCustomer
Private pstrCustcode As String
Private pstrCustName As String
Public Property Code() As String
Get
Return pstrCustcode
End Get
Set(ByVal Value As String)
pstrCustcode = Value
End Set
End Property
Public Property CustomerName() As String
Get
Return pstrCustName
End Get
Set(ByVal Value As String)
166
pstrCustName = Value
End Set
End Property
Public Function Update() As Boolean
‘ first / core concern
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
‘ second concern / system concern
Dim pobjClsAuditTrail As New ClsAuditTrail
With pobjClsAuditTrail
.NewValue = "1001"
.OldValue = "1003"
.UserName = "shiv"
.Update()
End With
' then inserting the customer in database
End Function
End Class
Public Class ClsAuditTrail
Private pstrUserName As String
Private pstrOldValue As String
Private pstrNewValue As String
Private pdblLogTime As Double
167
Public Property UserName() As String
Get
Return pstrUserName
End Get
Set(ByVal Value As String)
pstrUserName = Value
End Set
End Property
Public Property OldValue() As String
Get
Return pstrOldValue
End Get
Set(ByVal Value As String)
pstrOldValue = Value
End Set
End Property
Public Property NewValue() As String
Get
Return pstrNewValue
End Get
Set(ByVal Value As String)
pstrNewValue = Value
End Set
End Property
Public Property LogTime() As Double
168
Get
Return pdblLogTime
End Get
Set(ByVal Value As Double)
pdblLogTime = Value
End Set
End Property
Public Sub Update()
' do the logging activity here
End Sub
End Class
In short the customer class is doing lot of activity. There is lot of tangling of code. So
how do we overcome this problem… Simple separate the System level concern (Audit
Trail) from the core level concern ( Customer code check). This is achieved at this
moment in .NET using attribute programming.
Here is the change to the customer class
Imports System.Reflection
Public Class ClsCustomer
Private pstrCustcode As String
Private pstrCustName As String
Public Property Code() As String
Get
Return pstrCustcode
End Get
Set(ByVal Value As String)
169
pstrCustcode = Value
End Set
End Property
Public Property CustomerName() As String
Get
Return pstrCustName
End Get
Set(ByVal Value As String)
pstrCustName = Value
End Set
End Property
_
Public Function Update() As Boolean
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
' then inserting the customer in database
End Function
End Class
170
And here is the change to the audit trail class
Imports System.Reflection
_
Public Class ClsAuditTrail
Inherits Attribute
Private pstrUserName As String
Private pstrOldValue As String
Private pstrNewValue As String
Private pdblLogTime As Double
Public Property UserName() As String
Get
Return pstrUserName
End Get
Set(ByVal Value As String)
pstrUserName = Value
End Set
End Property
Public Property OldValue() As String
Get
Return pstrOldValue
End Get
Set(ByVal Value As String)
pstrOldValue = Value
End Set
171
End Property
Public Property NewValue() As String
Get
Return pstrNewValue
End Get
Set(ByVal Value As String)
pstrNewValue = Value
End Set
End Property
Public Property LogTime() As Double
Get
Return pdblLogTime
End Get
Set(ByVal Value As Double)
pdblLogTime = Value
End Set
End Property
Public Sub New(ByVal pstrUserName As String, _
ByVal pstrOldValue As String, _
ByVal pstrnewValue As String, _
ByVal plng As Long)
Update()
End Sub
Public Sub Update()
' do the logging activity here
172
End Sub
End Class
The fun part of the code is below , you can see that the code audit trail is now seperate
and the code check belongs to the customer code.
_
Public Function Update() As Boolean
If pstrCustcode.Length() > 10 Then
Throw New Exception("Value can not be greater than 10")
End If
' usingthe customer audit trail to do auditing
' then inserting the customer in database
End Function
Note:- Architecture is everybodys favorite and the wide combination is difficult to be covered
in this book. Many of the things can only come by live experience.

No comments: