Upload
dsk-chakravarthy
View
102
Download
0
Tags:
Embed Size (px)
DESCRIPTION
This presentation will help you to understand the best design methodologies that are used in the industry
Citation preview
.NET Solutions.NET Solutions.NET Solutions.NET Solutions
DSK ChakravarthyDSK Chakravarthy
http://dskc.blogspot.comhttp://dskc.blogspot.com
Who am I?
Certified by MicrosoftHaving hands on all phases of
SDLCConducted sessions for major
players of the industry… like … Infosys, Accenture, Wipro, etc.,
Been a consultant for Project management
Agenda for the DayAgenda for the DayAgenda for the DayAgenda for the Day
• Application ArchitectureApplication Architecture– Design PatternDesign Pattern– Services and IntegrationServices and Integration
• Component TypesComponent Types• Recommendations for Recommendations for
Application designApplication design• LayersLayers
– BusinessBusiness– DataData
Pre Lunch Session• Over view of Distributed Application DesignOver view of Distributed Application Design• Services and Service Integration “?s”Services and Service Integration “?s”• General Design Recommendations for General Design Recommendations for
Applications and servicesApplications and services• Designing Presentation LayersDesigning Presentation Layers
– UI ComponentsUI Components– Process ComponentsProcess Components
PrerequisitesPrerequisites• Architect (s) / Tech Export (s)Architect (s) / Tech Export (s)• Team Leader (s)Team Leader (s)• Sr. Programmers with C# in depthSr. Programmers with C# in depth
Best architecture design
Users Users
PresentationPresentation
Business Business LogicLogic
Data TierData Tier
Design Patterns
• It describes all the necessary elements and characteristics of the solution in generic language and it forms the basis for any implementation
• We use the design patterns for– To minimize design flaws– Performance enhancement– Adaptability– Scalability
Design Patterns should not be confused as a ready made detail of a particular implementation, it’s a template
There are almost 26 patterns, which fall in 3 categories…
• Creational : Deals with the problems of the Object construction. Provides flexi approach for 4 Ws (Who, What, Where & When)
• Structural : Governs how the objects and classes work together
• Behavioral : Supervise messages sent between the objects
Design Patterns
Note: The PatternForm is invented by Mr. Christopher Alexander, and he calls them as just “Patterns”, but not as “Design Patterns”
In the current world you’ve around 62 kinds62 kinds of patterns in practice
Design PatternsFull List1.1. AbstractFactoryPattern aka KitPatternAbstractFactoryPattern aka KitPattern
2.2. AbstractClientPatternAbstractClientPattern3.3. ActionPattern aka CommandPattern, TransactionPatternActionPattern aka CommandPattern, TransactionPattern4.4. ActiveObjectPatternActiveObjectPattern5.5. AdapterPattern aka WrapperPatternAdapterPattern aka WrapperPattern6.6. AbstractServerPatternAbstractServerPattern7.7. ApplicationControllerPatternApplicationControllerPattern8.8. WrapperPattern aka AdapterPatternWrapperPattern aka AdapterPattern9.9. BalkingPatternBalkingPattern10.10. BindingPropertiesBindingProperties11.11. BridgePattern aka HandleBodyPatternBridgePattern aka HandleBodyPattern12.12. BuilderPatternBuilderPattern13.13. CaretakerPatternCaretakerPattern14.14. ChainOfResponsibilityPatternChainOfResponsibilityPattern15.15. CommandPattern aka ActionPattern, TransactionPatternCommandPattern aka ActionPattern, TransactionPattern16.16. CompositePatternCompositePattern17.17. CursorPattern aka IteratorPatternCursorPattern aka IteratorPattern18.18. DataBusPatternDataBusPattern19.19. DecoratorPattern aka WrapperPatternDecoratorPattern aka WrapperPattern20.20. Dependents Pattern aka ObserverPattern, PublishSubscribePattern, PubSubPatternDependents Pattern aka ObserverPattern, PublishSubscribePattern, PubSubPattern21.21. DisableJobRequestsWhileRunningJobDisableJobRequestsWhileRunningJob
Design PatternsFull List
22.22. DoubleCheckedLockingDoubleCheckedLocking23.23. DynamicUserInterfacePatternDynamicUserInterfacePattern24.24. FacadePatternFacadePattern25.25. FacetPatternFacetPattern26.26. FactoryMethodPattern aka VirtualConstructorPatternFactoryMethodPattern aka VirtualConstructorPattern27.27. FlyweightPatternFlyweightPattern28.28. FrontControllerPatternFrontControllerPattern29.29. GuardedSuspensionGuardedSuspension30.30. HandleBodyPattern aka BridgePatternHandleBodyPattern aka BridgePattern31.31. HierarchicalVisitorPatternHierarchicalVisitorPattern32.32. InterpreterPatternInterpreterPattern33.33. IteratorPattern aka CursorPatternIteratorPattern aka CursorPattern34.34. KitPattern aka AbstractFactoryPatternKitPattern aka AbstractFactoryPattern35.35. LazyInstantiationPatternLazyInstantiationPattern36.36. MediatorPatternMediatorPattern37.37. MementoPattern aka Token PatternMementoPattern aka Token Pattern38.38. MockObjectPattern aka Service Stub PatternMockObjectPattern aka Service Stub Pattern39.39. MonostatePatternMonostatePattern40.40. NullObjectPatternNullObjectPattern41.41. ObserverPattern aka DependentsPattern, PublishSubscribePattern, PubSubPatternObserverPattern aka DependentsPattern, PublishSubscribePattern, PubSubPattern42.42. PolicyPattern aka StrategyPatternPolicyPattern aka StrategyPattern43.43. PrototypePatternPrototypePattern44.44. ProxyPattern aka SurrogatePatternProxyPattern aka SurrogatePattern45.45. PublishSubscribePattern aka DependentsPattern, ObserverPattern, PubSubPatternPublishSubscribePattern aka DependentsPattern, ObserverPattern, PubSubPattern46.46. PubSubPattern aka DependentsPattern, ObserverPattern, PublishSubscribePatternPubSubPattern aka DependentsPattern, ObserverPattern, PublishSubscribePattern47.47. ReadWriteLockReadWriteLock
Design PatternsFull List
48.48. ScheduledTaskScheduledTask49.49. SchedulerPatternSchedulerPattern50.50. SeparatedInterface Pattern aka InterfaceSegregationPrincipleSeparatedInterface Pattern aka InterfaceSegregationPrinciple51.51. ServiceStubPattern aka MockObjectPatternServiceStubPattern aka MockObjectPattern52.52. SingletonPatternSingletonPattern53.53. StatePattern aka StatesPatternStatePattern aka StatesPattern54.54. StatesPattern aka StatePatternStatesPattern aka StatePattern55.55. StaticUserInterfacePatternStaticUserInterfacePattern56.56. StrategyPattern aka PolicyPatternStrategyPattern aka PolicyPattern57.57. SurrogatePattern aka ProxyPatternSurrogatePattern aka ProxyPattern58.58. TemplateMethodPatternTemplateMethodPattern59.59. TokenPattern aka MementoPatternTokenPattern aka MementoPattern60.60. TransactionPattern aka ActionPattern, CommandPatternTransactionPattern aka ActionPattern, CommandPattern61.61. VirtualConstructorPattern aka FactoryMethodPatternVirtualConstructorPattern aka FactoryMethodPattern62.62. VisitorPatternVisitorPattern
Design Patterns an Example
Problem:You are building a Quote Application, which contains a class that is responsible for managing all the quotes in the system. It is important that all quotes interact with one and only oneone and only one instance of this class. How do you structure your design so that only one instance of this class is accessible with in the application?
Solution:A simple solution to this problem is to create a QuoteManager class with a private constructor so that no other class can instantiate it. This class contains a static instance of QuoteManager that is returned with a static method named GetInstance().
Can you design the code for the same?
Design Patterns an Example
public class QuoteManger{
// NOTE: For single threaded application onlyprivate static QuoteManagaer _Instance = null;private QuoteManager() {}private static QuoteManager GetInstanceGetInstance(){
if (_Instance==null){
_Instance = new QuoteManager ();}return _Instance;
}}
NOTE: This kind of Pattern is said as “Singleton Pattern”
We are focusing on distributed applications We are focusing on distributed applications and WebServices that may need to provide and WebServices that may need to provide
integration capabilities for multiple data integration capabilities for multiple data sources & services, and they may require a sources & services, and they may require a user interface for one (or) multiple devicesuser interface for one (or) multiple devices
Our Focus – Distributed Application Design
Designing a distributed application involvesDesigning a distributed application involves1)1) Making decisions about it’s logical and physical architecture issuesMaking decisions about it’s logical and physical architecture issues2)2) Sound knowledge of the technologies and infrastructure used to implement the Sound knowledge of the technologies and infrastructure used to implement the
functionalityfunctionality3)3) Should be very much aware of the business process that the application will Should be very much aware of the business process that the application will
performperforma)a) Functional RequirementsFunctional Requirementsb)b) Levels of scalability, availability, securityLevels of scalability, availability, securityc)c) Maintainability required i.e., Non-Functional, operational, requirementsMaintainability required i.e., Non-Functional, operational, requirements
Services Services n n IntegrationIntegrationServices Services n n IntegrationIntegration
Specialisation means not doing the Specialisation means not doing the Extraordinary things, but doing Extraordinary things, but doing
Ordinary things Extraordinarily well...Ordinary things Extraordinarily well...
So, What are you doing?So, What are you doing?
As iNet and related technologies grow, and the large organizations seek to integrate their systems across the companies boundaries, a service-based approach to design solutions has evolved
Services n Integration ?s
What are services?# Conceptually, they are similar to the Traditional Components
How are they?# They encapsulate their own data and remember, they are
not a part of your application, rather they are used by your applicationWhat is the difficulty with services?
# They might have built on different platforms by different teams on different schedules and may be maintained & Updated
independently
Therefore, it’s critical to implement communication between them
How do I resolve?# You can implement communication between them by
using message-based technologies
# You can implement message communication byi) Explicitly – By writing code to send and receive
Message Queuing Messages.
Ex. MSMQ
ii) Implicitly – By using Infrastructure components that manage communication.
Ex. A Web service proxy by VS.NET
Services n Integration ?s
How are the services differ from Components?# Services exists in their own trust boundary and manage
their own data, out side your application
What is crucial between Services & Application integration?# Establishing a secure, authenticated connection
What should I be aware, while using a service?# The internal implementation is irrelevant to your design
# But need to know the business functionality that the service provides
# Also the details of the contract you must adhere to in order to communicate with it such as
i) Communication Formatii) Data Schemaiii) Authentication Mechanism etc.,
Services n Integration ?s
What a service contain?# The same kind of components that any traditional
application do
# You can categorise them as
i) Logic Components : That orchestrate the tasks they doii) Business Components : That implement the actual BLiii) Data Access Components : that access the service’s data
storeiv) Interfaces : That expose the functionality
What happens when I integrate a service?
# Your application will also call other services through “Service agents”, which communicate with service on behalf of the calling client application
Services n Integration ?s
A small scenario
A Retail applicationA Retail application
1. This application has an order UI to place orders, this could be either web or non-web
2. This application uses an external Credit Card authentication service to validate the customer’s credit card details and authorise the sale
3. A courier service is used to arrange the delivery of goods
Can you give me a Sequence diagram?????
A small scenario
A Retail applicationA Retail applicationSequence DiagramSequence Diagram
Components and Components and Tiers in ApplicationTiers in ApplicationComponents and Components and
Tiers in ApplicationTiers in Application
Imagination is more important Imagination is more important than knowledgethan knowledge
Distributed designDistributed design
Distributed Application Design means, “You should divide your application into
components providing PBD (Presentation, Business and Data) Services”. While doing the
same follow the below rules.
1.1. Form the Functional LayersForm the Functional Layers: Group the Components that perform similar types of functions into layer
2.2. Prepare the Communication ChannelPrepare the Communication Channel: Components in the same layer communicate via Agents, but the communication with “ABOVE “ or “ BELOW” a certain layer use the services
Points to NotePoints to Note
1.1. LayerLayer: Combination of similar component types
2.2. TierTier: Physical distribution pattern
# Conceptually, the services can be seen as components of overall solution.# Internally, each service is made up of software components, just like any other application and these components are logically grouped into Presentation / Business Logic /Data Services
# While designing the application, follow the below steps
1) (Can youCan you) Draw a block diagram for the (previousprevious) scenario ! % & $ # ?
2) Explain the bits & pieces of each block as internal elements
3) Finally, prepare a simplified view of any application and it’s layers
4) But remember that, each service encapsulates its own data and manages atomic transactions on it’s own
For now, sketch a component design for the previous scenario
Component design
A Retail applicationA Retail applicationComponent DiagramComponent Diagram
You might design the one like this . . .
Simplified View
Here comes the simplified view of any general application and it’s layers
A Detailed View
The previous scenario for the detailed design would look like . . . .
General Design General Design Recommendations for Recommendations for
Applications and ServicesApplications and Services
• Identify the components that are required and not required
• Design the components as consistent as possible
• Understand “How components communicate?”
• Maintain the “Data Format” consistent for Exchange
• Follow the code policies• Enforce strict Layering System
Tea BreakTea BreakTea BreakTea Break
Components - In detailComponents - In detailComponents - In detailComponents - In detail
Knowing the path to Knowing the path to failure is failure is
as important asas important as Knowing the path to Knowing the path to
successsuccess
Knowing the path to Knowing the path to failure is failure is
as important asas important as Knowing the path to Knowing the path to
successsuccess
Component Types
Note: The term component is used in the sense of a piece or part of the overall solution. This includes compiled software components such as Microsoft .NET assemblies, and other software artifacts such as Web
pages and Microsoft BizTalk Server schedules
Components In detail
1) User Interface (UI) Components: Use them to render and format data for users and to Acquire and Validate data coming in from them
2) User Process Components: To help the user interactions synchronize with the UI Components, it is a best practise to drive the process using separate User Process Components
3) Business Workflows:These components are used to perform the business process. During the transaction, these process could take an inderminate amount of time to complete, so the required tasks and the data required to perform them would have to be managed
4) Business Components: Regardless of whether a business process consists of a single step or an orchestrated workflow, your application will probably require components that implement business rules and perform business tasks
5) Service Agents: Any business component that needs to use functionality provided by an External service, they many need to provide some code to manage the semantics of communicating with that particular service
6) Service Interfaces: These expose business logic as service that support the communication contracts ( message-based communication, formats, protocols, security etc.,) These are sometimes referred to as Business facades
7) Data Access Logic Components: It makes sense to abstract the logic necessary to access data in a separate layer of DAL Components
8) Business Entity Components: These help Data to traverse between components, they are used internally in every application “Data structures such as DataSets, DataReaders, XML Streams..
9) Components for Security, Operational Management and Communication: The main purpose of these components to perform
i. Exception managementii. Authorize users to perform certain tasksiii. To communicate with other services and applications
Designing Presentation Designing Presentation LayersLayers
• Windows Desktop User InterfacesWindows Desktop User Interfaces• Internet Browser User InterfacesInternet Browser User Interfaces• Mobile Device User InterfacesMobile Device User Interfaces
– Web User InterfaceWeb User Interface– Smart Device User InterfaceSmart Device User Interface
• Document-based User InterfacesDocument-based User Interfaces– .NET to Office Developers.NET to Office Developers– Office ‘n’ .NET InteroperabilityOffice ‘n’ .NET Interoperability
UI Components & Types
Designing UI Components
ShowProducts(){ // Code to // get product // data
}
Controller
When a user interacts with a user interface element, an event is When a user interacts with a user interface element, an event is raised that calls code in a controller function, which inturn calls raised that calls code in a controller function, which inturn calls
business components, data access logic components (or) user process business components, data access logic components (or) user process components to implement the desired action and retrieve any components to implement the desired action and retrieve any
necessary data..necessary data..
A Small Scenario
You are designing a web-based quote application containing a You are designing a web-based quote application containing a great deal of business and presentation logic, which, in turn, great deal of business and presentation logic, which, in turn,
depends on numerous platform software components to provide depends on numerous platform software components to provide a suitable execution environment. How do you organise your a suitable execution environment. How do you organise your system at a high level to be flexible, loosely coupled, and yet system at a high level to be flexible, loosely coupled, and yet
highly cohesive?highly cohesive?
CustomerManagementInventory ManagementCustomerWebPages
UtilityQuote WebPages
Quote Management Price Engine ADO.NET
QuoteDataAccess
Can you rearrange wrf to Layers?Can you rearrange wrf to Layers?
Solution Scenario
CustomerManagement
Inventory Management CustomerWebPages
Utility
Quote WebPages
Quote Management Price Engine
ADO.NETQuoteDataAccess
Can you rearrange any?Can you rearrange any?
The solution could be as.. .. .. ..
Quote Presentation Layer
Quote Business Layer
Quote Data Access Layer
UI Components
UI Components by natureUI Components by nature1.1. Don’t initiate or participate in transactionDon’t initiate or participate in transaction2.2. Have ref to user process componentHave ref to user process component3.3. Encapsulate both view functionality and a controllerEncapsulate both view functionality and a controller
While accepting input from user UI Components shouldWhile accepting input from user UI Components should1.1. Acquire proper data from users and assist them via different Acquire proper data from users and assist them via different
techniquestechniques2.2. Capture the events and call controller functionsCapture the events and call controller functions3.3. Initiate an action on the current user process o changing data of Initiate an action on the current user process o changing data of
the current user processthe current user process4.4. Restrict the types of input a user can enterRestrict the types of input a user can enter5.5. Perform Data ValidationPerform Data Validation6.6. Perform simple mapping to values needed by the underlying Perform simple mapping to values needed by the underlying
components to do their work. Ex: You may capture “Product components to do their work. Ex: You may capture “Product Name”, convert to “ID”Name”, convert to “ID”
7.7. Internet user gestures to call a controller functions, such as Internet user gestures to call a controller functions, such as dragNdrop or button clicksdragNdrop or button clicks
8.8. Use a utility component for Caching and PagingUse a utility component for Caching and Paging
Windows Desktop – UIs
Recommendations
When creating a Windows Forms-based application, When creating a Windows Forms-based application, consider the following recommendationsconsider the following recommendations
1.1. Rely on data binding to keep data synchronized across multiple Rely on data binding to keep data synchronized across multiple
forms that are open simultaneouslyforms that are open simultaneously
2.2. Try avoiding hard-coding relationships between forms to make Try avoiding hard-coding relationships between forms to make
the elements more reusablethe elements more reusable
3.3. Implement error handlers (or) exception handlersImplement error handlers (or) exception handlers
4.4. Validate user input, this validation should occur at the stages of Validate user input, this validation should occur at the stages of
every process that allow point-in-time validationsevery process that allow point-in-time validations
5.5. For the custom controls, expose only the public properties and For the custom controls, expose only the public properties and
methods that are actually neededmethods that are actually needed
6.6. Implement controller functions as separate functions. Do not Implement controller functions as separate functions. Do not
implement controller functionality directly in control events implement controller functionality directly in control events
handlers (Look at the example from the book)handlers (Look at the example from the book)
iNET Browser UIs Recommendations
When you are implementing an application and publish a Web page-based When you are implementing an application and publish a Web page-based user interface for a browser, consider the following design user interface for a browser, consider the following design recommendations for ASP.NET user interfacesrecommendations for ASP.NET user interfaces
1.1. Implement a custom error page, and a global exception handler in Implement a custom error page, and a global exception handler in Global.asaxGlobal.asax
2.2. Use ASP.NET rich validation controls (or) if the user process has a Use ASP.NET rich validation controls (or) if the user process has a Validate control function, call it before transitioning to other pages Validate control function, call it before transitioning to other pages to perform point-in-time validationto perform point-in-time validation
3.3. If you are using WebUserControls, expose only the public If you are using WebUserControls, expose only the public properties and methods that are actually neededproperties and methods that are actually needed
4.4. Use ViewState to store page specific stateUse ViewState to store page specific state5.5. Controller functions should invoke the actions on a user process Controller functions should invoke the actions on a user process
components to guide the user through the current task rather than components to guide the user through the current task rather than redirecting the user to the page directlyredirecting the user to the page directly
6.6. Implement controller functions as separate functions. Do not Implement controller functions as separate functions. Do not implement controller functionality directly in control events implement controller functionality directly in control events handlers (Look at the example from the book)handlers (Look at the example from the book)
Process ComponentsProcess ComponentsProcess ComponentsProcess Components
A standardized specification that A standardized specification that improves the integrity, improves the integrity,
confidentiality and security of confidentiality and security of Services Services
-Bill GatesBill GatesLasVegas, Niveda, Jan 5th 2005
These help the user interactions synchronize with the UI Components, it is a best practise to drive the process using separate User Process Components
User process components are typically implemented as .NET classes that expose methods that can be called by user interfaces. Each method encapsulates the logic necessary to perform a specific action in the UP
The user interfaces creates instances of the user process component and uses it to transition through the steps of process
You should design them with globalization in mind to allow for localization to be implemented in the User Interface
Note: User process components co-ordinate the display of user interface elements
Task for You: Can you design common ProcessComponent for the previous Retail application ?
UP Components
UP Components Examplenamespace PurchaseUserProcess{
public class PurchaseUserProcess{public PurchaseUserProcess(){
userActivityID= System.Guid.NewGuid();}private int intCustomerID; private DataSet dsOrderData; private DataSet dsPaymentData; private Guid userActivityID; public bool webUI;public void ShowOrder() {
if(webUI){System.Web.HttpContext.Current.Response.Redirect("http://www.myserver.com/orderDetails.aspx");
}else{
OrderDetails = new OrderDetailsForm();OrderDetails.Show(); }
}public void EnterPaymentDetails() {
// code to display the Payment details page or window goes here}public void ShowConfirmation() {
// code to place the order goes here}public void Finish() {
// code to go back to the main page or window goes here}public void SaveToDataBase() {
// code to save order and payment info in the private variables to a database}public void ResumeCheckOut(System.Guid ProcessID) {
// code to reload the process state from the Database}public void Validate() {
// code to make sure the process instance variables have the right information for the current step}
}}
UP Components Advantages
Separating the user interaction functionality into user Separating the user interaction functionality into user interface and user process components provides the interface and user process components provides the following advantagesfollowing advantages
1.1. Long-running user interactions state is more easily Long-running user interactions state is more easily persisted, allowing a user interaction to be abandoned persisted, allowing a user interaction to be abandoned and resumed, possibly even using a different user and resumed, possibly even using a different user interfaceinterface
2.2. The same user process can be reused by multiple user The same user process can be reused by multiple user interfacesinterfaces
UP Components
Guidelines for separating a UserProcess from UserInterfaceGuidelines for separating a UserProcess from UserInterface
1.1. Draw Sequence Diagrams – helps you to identify the business Draw Sequence Diagrams – helps you to identify the business process that the UserInterface process will help to accomplishprocess that the UserInterface process will help to accomplish
2.2. Identify the data needed by the business processIdentify the data needed by the business process3.3. Identify additional state you will need to maintainIdentify additional state you will need to maintain4.4. Design the visual flow of the UserProcessDesign the visual flow of the UserProcess
UserProcess Component Interface DesignUserProcess Component Interface Design
UP Design
1) UP “Actions”(1): these typically trigger a change in the state of UserProcess. One should try to encapsulate calls to business components to these action methods(6)
2) State Access Methods(2): to acess the business-specific state by using GET & SET properties to expose one value to the business process deals with(5)
3) State Change Events(3): Fired during the business-related state of the UserProcess changes4) Control functions that let you start, pause, restart, and
cancel a particular user Process(4): Control methods could load required reference data for the UI from data access logic components(7) or delegate this work to the UI Component that needs the data