open source & dotnet platform - training division...

64
Architectural patterns Open Source & DOTNET platform Understanding architectural design patterns (like MVC, MVP, MVVM etc.) is essential for producing a maintainable, clean, extendable and testable source code.

Upload: lamhanh

Post on 29-Jul-2018

249 views

Category:

Documents


0 download

TRANSCRIPT

MVCMVC stands for Model-View-Controller. It is a software design pattern which was introducedin 1970s. Also, MVC pattern forces a separation of concerns, it means domain model andcontroller logic are decoupled from user interface (view). As a result maintenance andtesting of the application become simpler and easier.MVC design pattern splits an application into three main aspects: Model, View andController

MVCModelThe Model represents a set of classes that describe thebusiness logic i.e. business model as well as data accessoperations i.e. data model. It also defines business rulesfor data means how the data can be changed andmanipulated.

ViewThe View represents the UI components like CSS,jQuery, html etc. It is only responsible for displaying thedata that is received from the controller as the result.This also transforms the model(s) into UI.

ControllerThe Controller is responsible to process incomingrequests. It receives input from users via the View, thenprocess the user's data with the help of Model andpassing the results back to the View. Typically, it acts asthe coordinator between the View and the Model.

MVPThis pattern is similar to MVC pattern in which controller has been replaced by thepresenter. This design pattern splits an application into three main aspects: Model, View andPresenter.

This pattern is commonly used with ASP.NET Web Forms applications whichrequire to create automated unit tests for their code-behind pages. This is alsoused with windows forms.

MVPModelThe Model represents a set of classes that describes thebusiness logic and data. It also defines business rules fordata means how the data can be changed andmanipulated.ViewThe View represents the UI components like CSS,jQuery, html etc. It is only responsible for displaying thedata that is received from the presenter as the result.This also transforms the model(s) into UI.PresenterThe Presenter is responsible for handling all UI eventson behalf of the view. This receive input from users viathe View, then process the user's data with the help ofModel and passing the results back to the View. Unlikeview and controller, view and presenter are completelydecoupled from each other’s and communicate to eachother’s by an interface.Also, presenter does not manage the incoming requesttraffic as controller.

Key Points about MVP Pattern:User interacts with the View.There is one-to-one relationship between View and Presenter means oneView is mapped to only one Presenter.View has a reference to Presenter but View has not reference to Model.Provides two way communication between View and Presenter.

MVVMMVVM stands for Model-View-View Model. Thispattern supports two-waydata binding between viewand View model. Thisenables automaticpropagation of changes,within the state of viewmodel to the View.Typically, the view modeluses the observer patternto notify changes in theview model to model.

MVVMModelThe Model represents a set of classes that describes the business logic and data.It also defines business rules for data means how the data can be changed andmanipulated.ViewThe View represents the UI components like CSS, jQuery, html etc. It is onlyresponsible for displaying the data that is received from the controller as theresult. This also transforms the model(s) into UI..View ModelThe View Model is responsible for exposing methods, commands, and otherproperties that helps to maintain the state of the view, manipulate the model asthe result of actions on the view, and trigger events in the view itself.

This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.Key Points about MVVM Pattern:User interacts with the View.There is many-to-one relationship between View and ViewModel means many View can be mapped to one ViewModel.View has a reference to ViewModel but View Model has no information about the View.Supports two-way data binding between View and ViewModel.

Open Source Development Framework for developing web applications

Using Spring MVC

Java Web Development Framework

There are a majority of enterprises runningJava applications and working on Java webdevelopment framework. What remains tobe seen is that a number of companies aretied to the conventional web developmentframework and haven’t actually started toanticipate what could be the best Java webdevelopment framework.

10 best Java web development framework

1. Struts 2

2. JSF (Java Server Faces)

3. Spring MVC

4. Wicket

5. Stripes

6. Tapestry

7. RIFE

8. Seam

9. Google Web Toolkit (GWT)

10. OpenXava

Java Web Development Frameworks

“Full-stack” frameworks: SEAM, RIFE, Spring (?)

Address back-end soup-to-nuts web development

Typically include MVC component AND integration with enterprise systems

ADVANTAGES: complete stack, limited glue code

DISADVANTAGES: less plug-n-play; “heavyweight”

MVC frameworks: Struts, Spring MVC, etc.

Address “page flow” and reusability in web development

Focused on simplifying MVC-based web application

Limited out-of-the-box integration with “enterprise”

ADVANTAGES: pluggable architecture, “lightweight”

DISADVANTAGES: glue code

Choosing an MVC FrameworkTwo types of MVC frameworks:

• Action-based (aka Push-based MVC) Data is pushed from controller to view Focused more on request flow

Struts, Spring MVC, Stripes

• Component-based (aka Pull-based MVC) Data is pulled in view Focused more on view rendering

JSF, Wicket, Tapestry

Spring MVC & Struts1)Struts is a web framework while spring is an application framework in which spring MVC is one of the modules of spring framework.

2)Spring is a Layered Architecture while Struts is not.

3)Struts is heavy weight while Spring is light weight.

4)Struts supports tag Library while Spring does not.

5)Spring is loosely coupled while Struts is tightly coupled.

6)Spring provides easy integration with ORM technologies while in struts, we need to do coding manually.

7)Struts easily integrate with other client side technologies. It is not easy in case of spring.

Spring MVC Architecture

Front Controller design pattern

This design patternenforces a singlepoint of entry for allthe incomingrequests. All therequests arehandled by a singlepiece of code whichcan then furtherdelegate theresponsibility ofprocessing therequest to furtherapplication objects.

Spring MVC Architecture

MVC design pattern

This design patternhelps us developloosely coupledapplication bysegregating variousconcerns intodifferent layers.MVC design patternenforces theapplication to bedivided into threelayers, Model, Viewand Controller.

Spring MVC ArchitectureSpring’s MVC module

Spring’s MVC module is based on front controller design pattern followedby MVC design pattern. All the incoming requests are handled by thesingle servlet named DispatcherServlet which acts as the front controllerin Spring’s MVC module. The DispatcherServlet then refers tothe HandlerMapping to find a controller object which can handle therequest. DispatcherServlet then dispatches the request to the controllerobject so that it can actually perform the business logic to fulfil the userrequest. (Controller may delegate the responsibility to further applicationobjects known as service objects). The controller returns an encapsulatedobject containing the model object and the view object (or a logical nameof the view). In Spring’s MVC, this encapsulated object is represented byclass ModelAndView. In case ModelAndView contains the logical name ofthe view, the DispatcherServlet refers the ViewResolver to find the actualView object based on the logical name. DispatcherServlet then passes themodel object to the view object which is then rendered to the end user.

Spring MVC ArchitectureSpring’s MVC module

Open Source Project Development Framework

OSPDF 7 Layers:1. Controller

2. View (JSP pages)

3. DTO (Data Transfer Objects)

4. Service

5. Utilities

6. Entities

7. DAO (Data Access Object)

To build upon a basic project development framework for NIC, UttarPradesh so that any project development team can develop anapplication with less effort and in a structured and efficient manner. Theframework shall be used as a basic template for development of webapplications in open source framework. The framework is a directionand not binding for the development by different groups. It is open forupgradation and improvement based on the inputs received fromvarious divisions/groups of NIC and never shall be thought of as a frozenor proprietary thing.

(Document)

User Request (request URL)

Open Source Project Development Framework

Utility Classfor Authentications, validations, conversions etc.

HandlerMapping

PersonController[stores form entries to DTO]through PersonService(DTO)

PersonService[Converts DTO to Entity for WRITE and Entity to DTO for READ] calls PersonDAO(Entity)

PersonDAOCalls GenericDAO for CRUD operations using Hibernate.

Response back to User

DispatcherServlet(Front Controller)

IDEEclipse: Eclipse is an integrated development environment (IDE)for Java and other programming languages like C, C++, PHP, andRuby etc. Development environment provided by Eclipseincludes the Eclipse Java development tools (JDT) for Java,Eclipse CDT for C/C++, and Eclipse PDT for PHP, among others.

Application ServerJBoss AS 8.0: The JBoss applications server is a J2EE platformfor developing and deploying enterprise Java applications, Webapplications and services, and portals. J2EE allows the use ofstandardized modular components and enables the Javaplatform to handle many aspects of programmingautomatically.

OSPDF using Spring MVC

Development Environment

For project development using Spring MVC the following things are required:

DatabasePostgreSQL 9.4: PostgreSQL is a powerful, open source object-relational databasesystem. It has more than 15 years of active development and a proven architecturethat has earned it a strong reputation for reliability, data integrity, and correctness.PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD,HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows.

Development FrameworkSpring 4.0.3: Spring is a lightweight framework. The Spring framework comprisesseveral modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc

Entity FrameworkHibernate 4.0.1: Hibernate is a high-performance Object/Relational persistenceand query service which is licensed under the open source GNU Lesser GeneralPublic License (LGPL) and is free to download. Hibernate not only takes care of themapping from Java classes to database tables (and from Java data types to SQLdata types), but also provides data query and retrieval facilities.

OSPDF using Spring MVCDevelopment Environment

HibernateHibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is apowerful, high performance object/relational persistence and query service.It allows us to develop persistent classes following object-oriented idiom –including association, inheritance and polymorphism.

1.Hibernate is database independent. You can work with any database you want like oracle,mysql,db2,sql server ,etc. Using hibernate you won't worry about writing database specific queries and syntax. It's provides HQL (Hibernate Query Language), which is compatible with any database server. You just need to write queries in HQL, at the end hibernate converts HQL to underlying database and executes it.

2. In ORM, you will map a database table with java object called "Entity". So once you map these, you will get advantages of OOP concepts like inheritance, encapsulation, etc.

3. Caching mechanism (1st level & 2nd level cache) provided hibernate means you don't need to hit database for similar queries, you can cache it and use it from buffered memory to improve performance.

4.Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of child class. So When you want information from only 1 child class,there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).

DIRECTORY

STRUCTURE

Spring MVC Login Page

Sample codes for development using Spring MVC

http://10.135.2.177:8080/loginIf you browse a URL

1. Layer-1: On seeing login, it will look for login controller (loginController.java)

@RequestMapping(value = "/login", method = RequestMethod.GET)public ModelAndView login(@ModelAttribute("log") LoginDTO dto,@RequestParam(value = "error", required = false) String error,@RequestParam(value = "logout", required = false) String logout){ ……………………………………………….model.setViewName("login");model.addObject("log", dto);return model;}

2 Layer-2: Controller has set the view name and the DTO (login.jsp)

<form:form name='loginForm' action="j_spring_security_check"method='POST' commandName="log">

<tr><td><em class="outputText">password:</em></td><td><form:password path="password" id="password"name="password" cssClass="inputText" onblur="encryption()" /></td></tr>

Sample codes for development using Spring MVC

3. Layer-3: Now we see LoginDTO.java file

public class LoginDTO {public LoginDTO(){private String loginname;private String username;public String getLoginname() {return loginname;}public void setLoginname(String loginname) {this.loginname = loginname;}

4. Layer-4 : Service implementation goes like this, (LoginSeviceImpl.java)

public class LoginServiceImpl implements LoginService {public String getLoginName(String username){return loginDao.getLoginName(username);} @Overridepublic String getLoginPassword(String username){return loginDao.getLoginName(username);}

Sample codes for development using Spring MVC

6. Layer-6: Login entity (LoginUser.java)

public class LoginUser implements UserDetails {private static final long serialVersionUID = 1L;private String username;private String password;

@Overridepublic String getUsername() {

return username;}

5. Layer-5 : Data access object (LoginDao.java)

public class LoginDaoImpl implements LoginDao {public String getLoginName(String username){String encPass="";Connection con=null;

7. Layer-7: General utilities (LoginUser.java)

public class ConvertDTO2Entity {

public static User getEntity(PersonDTO dto){User person=new User();BeanUtils.copyProperties(dto, person);

AJAX (Asynchronous JavaScript And XML)

It is a group of inter-related technologies like JavaScript, DOM, XML,HTML, CSS etc. AJAX allows you to send and receive dataasynchronously without reloading the web page.

The Document Object Model (DOM) is across-platform and language-independentapplication programming interface thattreats an HTML, XHTML, or XML documentas a free structure wherein each node is anobject representing a part of thedocument.

XMLHttpRequest (XHR) is an API that can be used by JavaScript,JScript, VBScript, and other web browser scripting languages totransfer and manipulate XML data to and from a webserverusing HTTP, establishing an independent connection channelbetween a webpage's Client-Side and Server-Side.

MVC with AngularJSAngularJS is a JavaScript framework to create SPA (Single PageApplication). It is a client side MV* (MVC+MVVM=MV*) framework.AngularJS extends HTML by providing Directives that add functionality toyour markup and that allow you to create powerful dynamic templatesfor application.

The following are some AngularJS directives which I have used in sample application.

ng-app: It is entry point of AngularJS to the page. It shows that the application is AngularJS app.ng-controller: It is directive to define the controller. It attaches a controller class to the view.ng-repeat: It creates loop in your page like foreach loop.angular.module: It is use to create, register and retrieve all angular module.$http: It is an XMLHttpRequest object for requesting external data.$http.get: It read the json data. It takes two parameter url and config but config is optional.

Example

(MVC 5 application development in DOTNET platform)

MVC application development using Visual studio 2013 is sosimple and configurable, this is shown in the example.

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

MVC 5 application development

The End