This document discusses implementing a generic repository pattern and unit of work pattern in an MVC application using Entity Framework. It begins by introducing the concepts of a generic repository and unit of work. It then shows how to create a generic repository class that can be used for any entity. A unit of work class is created to manage transactions and repositories. Properties on the unit of work class provide access to repositories without having to create separate classes. CRUD operations on entities are demonstrated using the generic repository through the unit of work. This completes the tutorial on implementing these patterns to reduce redundant code and complexity in an MVC application.
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
The document discusses implementing a repository pattern in an MVC application using Entity Framework. It begins with an introduction and roadmap of previous articles. It then discusses the benefits of a repository pattern in abstracting the data access layer from business logic. Steps are provided to create a sample repository interface and class to implement basic CRUD operations on a User entity, abstracting the data access code from the controller. The repository class uses the Entity Framework context to perform operations while resolving tight coupling issues between layers. It concludes that while this implementation works for a single entity, a generic repository will be needed to cleanly support multiple entities without duplication.
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
This document discusses connecting an existing MVC application to a database using Entity Framework instead of LINQ to SQL. It provides steps to generate an Entity Data Model from an existing database, generate strongly typed entity classes, and modify the application's controllers to use the Entity Framework context instead of the LINQ to SQL context. The key steps are: 1) Adding an Entity Data Model file and generating entity classes; 2) Modifying controllers to use the Entity Framework context instead of LINQ to SQL; 3) Binding views to the generated entity classes. The document emphasizes that Entity Framework automates CRUD operations and allows focusing on business logic rather than data access code.
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
This document discusses connecting an MVC application to a database using Entity Framework's Code First approach. It explains that with Code First, domain models are designed first before the database is automatically generated. The steps shown create a DbContext class that inherits from DbContext and defines a DbSet for the User model. A connection string is added and the DbContext is used instead of the prior Entity Data Model classes. When run, the database is dynamically generated based on the model, allowing CRUD operations on the User table through the application and Entity Framework.
This paper’s aim is to point out the RAD ( Rapid application development) elements present in the Microsoft’s MVC 3 and WCF 4.0 using Microsoft Visual Studio 2010. It will describe why creating a new web application using MVC 3 and WCF 4.0 is a easy and fast and also present simple ways to develop such applications.
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
In my last two articles I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article I’ll explain how to create a loosely coupled system with Unity Container and MEF(Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).
This document discusses strategies for streamlining application architecture. It defines a large application as one requiring significant effort to maintain. Examples given include Gmail, Yahoo homepage, and MobileMe. Current architectures are described as having custom widgets, modules, MVC patterns and libraries coupled together. Problems identified include lack of reusability and tight coupling. The document proposes using a module pattern with loose coupling, a facade abstraction layer, and mediator pattern to improve maintainability. Modules would communicate through publishing events to the facade/mediator core rather than directly accessing each other.
This document discusses building rich web applications using ASP.NET MVC 2. It includes 4 exercises:
1. Adding metadata attributes to model entities to help render them in views. This includes attributes like DisplayName and DataType.
2. Modifying markup in a view to make use of new strongly-typed HTML helpers like LabelFor and DisplayFor.
3. Creating a metadata class to store attributes for rendering an activity entity, including using the MetadataType attribute.
4. Learning how to use templates in ASP.NET MVC 2 to help render model properties, including creating a template for the activity rating property.
This document discusses creating an MVC application from scratch using LINQ to SQL to perform CRUD operations on a database. It covers:
1. Creating an empty MVC project and adding controllers, views and models
2. Creating a sample database and using LINQ to SQL for communication between the MVC app and database
3. Performing CRUD operations in the MVC app by querying the database and passing data between controllers and views
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
The document discusses implementing a repository pattern in an MVC application using Entity Framework. It begins with an introduction and roadmap of previous articles. It then discusses the benefits of a repository pattern in abstracting the data access layer from business logic. Steps are provided to create a sample repository interface and class to implement basic CRUD operations on a User entity, abstracting the data access code from the controller. The repository class uses the Entity Framework context to perform operations while resolving tight coupling issues between layers. It concludes that while this implementation works for a single entity, a generic repository will be needed to cleanly support multiple entities without duplication.
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
This document discusses connecting an existing MVC application to a database using Entity Framework instead of LINQ to SQL. It provides steps to generate an Entity Data Model from an existing database, generate strongly typed entity classes, and modify the application's controllers to use the Entity Framework context instead of the LINQ to SQL context. The key steps are: 1) Adding an Entity Data Model file and generating entity classes; 2) Modifying controllers to use the Entity Framework context instead of LINQ to SQL; 3) Binding views to the generated entity classes. The document emphasizes that Entity Framework automates CRUD operations and allows focusing on business logic rather than data access code.
MVC Application using EntityFramework Code-First approach Part4Akhil Mittal
This document discusses connecting an MVC application to a database using Entity Framework's Code First approach. It explains that with Code First, domain models are designed first before the database is automatically generated. The steps shown create a DbContext class that inherits from DbContext and defines a DbSet for the User model. A connection string is added and the DbContext is used instead of the prior Entity Data Model classes. When run, the database is dynamically generated based on the model, allowing CRUD operations on the User table through the application and Entity Framework.
This paper’s aim is to point out the RAD ( Rapid application development) elements present in the Microsoft’s MVC 3 and WCF 4.0 using Microsoft Visual Studio 2010. It will describe why creating a new web application using MVC 3 and WCF 4.0 is a easy and fast and also present simple ways to develop such applications.
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
In my last two articles I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article I’ll explain how to create a loosely coupled system with Unity Container and MEF(Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).
This document discusses strategies for streamlining application architecture. It defines a large application as one requiring significant effort to maintain. Examples given include Gmail, Yahoo homepage, and MobileMe. Current architectures are described as having custom widgets, modules, MVC patterns and libraries coupled together. Problems identified include lack of reusability and tight coupling. The document proposes using a module pattern with loose coupling, a facade abstraction layer, and mediator pattern to improve maintainability. Modules would communicate through publishing events to the facade/mediator core rather than directly accessing each other.
This document discusses building rich web applications using ASP.NET MVC 2. It includes 4 exercises:
1. Adding metadata attributes to model entities to help render them in views. This includes attributes like DisplayName and DataType.
2. Modifying markup in a view to make use of new strongly-typed HTML helpers like LabelFor and DisplayFor.
3. Creating a metadata class to store attributes for rendering an activity entity, including using the MetadataType attribute.
4. Learning how to use templates in ASP.NET MVC 2 to help render model properties, including creating a template for the activity rating property.
This document discusses creating an MVC application from scratch using LINQ to SQL to perform CRUD operations on a database. It covers:
1. Creating an empty MVC project and adding controllers, views and models
2. Creating a sample database and using LINQ to SQL for communication between the MVC app and database
3. Performing CRUD operations in the MVC app by querying the database and passing data between controllers and views
An assembly in .NET is a collection of types and resources that form a logical unit. Assemblies can contain metadata about types using attributes. Attributes provide additional information that can be attached to classes, methods, and other members. There are built-in attributes in .NET and custom attributes can be created by deriving from the Attribute base class. Built-in attributes like Required and StringLength are used to validate model data in ASP.NET MVC. A custom MyLicenseAttribute was created to require a license key by applying the attribute to assemblies. Attributes help add metadata and customize behavior.
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
This document provides an overview of Maven, Subversion (SVN), and GIT. It discusses how to install and set up Maven, create Maven projects, and manage dependencies. It also explores version control systems, specifically SVN and GIT. With SVN, it demonstrates how to create repositories and check out projects. It discusses merging code and avoiding conflicts. The document is a presentation intended to teach these topics.
IRJET- Lightweight MVC Framework in PHPIRJET Journal
This document discusses a lightweight Model-View-Controller (MVC) framework for PHP programming. It begins by providing background on PHP and the traditional MVC pattern. It then introduces a lightweight MVC framework for PHP that aims to improve efficiency, reduce complexity, and enhance security, stability and robustness. The framework consists of components like the index page, libraries, business controller, MVC base class, and database/template layers. It allows developers to get the benefits of MVC while maintaining simplicity. Some advantages are fast development, low maintenance and high performance, while disadvantages include needing programming expertise and less built-in support.
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
This document provides an over view of spring IOC and it's advantages. It also gives basic idea on the spring core container. At the last it describes how develop a simple spring application
The 9 new features in Java 9 are: 1) the Java Platform module system, 2) linking, 3) JShell interactive shell, 4) improved Javadoc search, 5) collection factory methods, 6) Stream API improvements, 7) private interface methods, 8) support for HTTP/2, and 9) multi-release JARs that allow libraries to use new Java features while maintaining backward compatibility.
This document provides an overview of Asp.Net MVC and how it compares to traditional Asp.Net web forms. Some key points:
- Asp.Net MVC follows the MVC pattern, separating concerns into models, views, and controllers, allowing for cleaner code and easier testing compared to Asp.Net web forms.
- In Asp.Net MVC, controllers handle requests and return action results, views are responsible for the UI, and models represent application data. This separation of concerns is more aligned with HTTP concepts.
- Asp.Net MVC aims to be more flexible, maintainable, and testable than web forms. It allows for tighter control over HTML and adheres to conventions over configurations
The document discusses client-side JavaScript and DOM (Document Object Model) manipulation. It covers the window object, DOM programming interface, DOM element types like Node and HTML Element. Methods for accessing elements like getElementById(), getElementsByName(), and querySelector() are explained. Working with element attributes, innerHTML, and traversing the DOM using childNodes and parentNode properties are also summarized. The presentation aims to explain DOM and how JavaScript can be used to get, change, add or remove HTML elements.
Hibernate is an object-relational mapping tool that maps objects to database tables. It creates a "virtual object database" that can be used from within programming languages. Hibernate is a persistence framework that stores and retrieves data to and from a permanent medium like a database. Configuration files like hibernate.cfg.xml are used to map classes and their attributes to database tables and columns. The SessionFactory interface manages connections to the database using the configuration files.
The document discusses Struts framework and internationalization (I18N) applications. Some key points:
1. Struts is a MVC framework that simplifies development of web applications. It provides components like ActionServlet and tag libraries.
2. I18N applications display output based on the user's locale/language. This is achieved using properties files with language-specific translations and the ResourceBundle class.
3. In Struts, properties files are configured in struts-config.xml and accessed in JSPs using the <message> tag. Keys not found will result in errors unless null=false is specified.
This document discusses JavaScript design patterns. It begins by defining what a design pattern is, noting that patterns provide proven solutions to common software development problems. It then summarizes several categories of design patterns, including creational patterns (which deal with object creation), structural patterns (which concern relationships between entities), and behavioral patterns (which focus on communication between objects). Specific patterns like module, facade, and mediator are then explained in more detail with examples provided.
This presentation illustrates DocIndex, InternetMiner and VisioDecompositer - my 3 proprietary test tools - and walks the user through how they are used effectively.
The tools are presented in the context of a Test Strategy and the emphasis is on HOW the tools are used and the rationale behind the esign of the tools.
View this presentation with SPEAKERS NOTES ON.
Java servlets are small programs that run on a web server and dynamically generate web page content. They extend the functionality of web servers and allow for more complex interactions than CGI programs. Servlets support multithreading and sharing of resources, making them faster than CGI programs which require creating a new process for each request. Common ways to handle form data submitted to servlets include using the getParameter() method to retrieve parameter values by name. Sessions can be tracked across requests using cookies, which are small pieces of data stored in the user's browser by the web server. There are two main architectures for developing JSP applications - page-centric and servlet-centric, with servlet-centric following the MVC pattern and separating business
Introduction to Spring's Dependency InjectionRichard Paul
This document provides an overview of dependency injection in Spring. It defines dependency injection as a form of inversion of control where objects are provided to classes rather than having classes create their own dependencies. It discusses the benefits of dependency injection such as loose coupling, easy switching of implementations, and enhanced testability. It also compares constructor injection and setter injection and describes how to configure dependency injection using XML, annotations, and Java configuration in Spring.
The document discusses object-relational mapping (ORM) and Hibernate. It describes how Hibernate provides a layer between a database and application code to abstract away differences in database types. This allows changing the backend database without changing code. Hibernate also maps object-oriented domain models to relational database tables through configuration files or annotations. Examples show how to configure Hibernate and perform basic operations like inserting a record.
Struts is a web application framework that uses the MVC design pattern. It combines Java servlets, JavaServer Pages, custom tags and message resources. Struts acts as a controller in MVC that routes requests between the view (JSPs) and the model (business logic classes). Struts is open source software hosted by the Apache Software Foundation. It provides a standard way to build Java web applications by separating the application logic from the user interface.
The document provides an overview of the key components of Windows Azure, Microsoft's cloud computing platform. It describes the Compute service which allows running applications on virtual machines at scale, the Storage service which provides blobs, tables and queues to store and access data, and the Fabric which manages resources and monitors applications running on the platform. The goal of Windows Azure is to provide a foundation for building and running applications in the cloud similar to what an operating system provides for on-premises applications.
React.js is a JavaScript library developed by awesome engineers at Facebook. React is really fast, any app developed in React can handle complex updates and still feel quick and responsive. It uses reusable components, it’s modularity makes it really easy to maintain JavaScript (spaghetti code). React performs best with large programs that constantly require data changes, and this is a very famous language, understanding. React will definitely make you more employable.
Prerequisite to understanding React.js is JavaScript fundamentals,
This document describes how to rapidly develop a web application using ASP.NET MVC 3 in Microsoft Visual Studio 2010. It outlines how to create a new project, add models, contexts, controllers with CRUD functionality, and use HTML helpers and dynamic templates to simplify development. MVC 3 enables full control over HTML while separating concerns, and allows both basic and complex applications to be built quickly through its RAD elements integrated into Visual Studio.
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
Patterns (contd)
Software Development Process
Design patterns used to handle change
More time extending and changing code than developing it.
The Strategy design pattern handle change by selecting from a family of external algorithms rather than rewrite.
Design point: Make code closed for modification of code, but open for extension
Problem
Computer object created
Description Method returns
Getting a Computer
Problem
Program has to change every time
Customer changes options
Decorator Pattern
Wrapper code used to extend your core code
Extend a class dynamically at runtime
Decorator uses wrapper code to extend core functionality - decorating the code
Decorator Pattern
description() returns “You are getting a computer”
Wrapper description() returns
“You are getting a computer and a disk”
Wrapper description() returns
“You are getting a computer and a disk and a monitor”
Decorator Pattern
Core component: Computer
Variables holding computer objects should also be able to hold objects that wrap computer objects.
Extend the wrapper classes from the Computer class.
Abstract class cannot be instantiated
Ensures all wrappers are consistent
Developers have to provide their own description
Decorator Pattern
Method calls the core computer object’s
description method and adds “and a disk”
Decorator Pattern
Method calls the core computer object’s
description method and adds “and a disk”
Extend the core object by wrapping it in decorator wrappers. Avoids modification of the core code.
Each successive wrapper called the description method of the object it wrapped and added something to it.
Factory Pattern
Based on type, call the
Connection method
Factory Pattern
Create a method that returns the
correct connection type
Factory Pattern
New operator used to create OracleConnection objects.
New operator used to create SqlServerConnection objects, and MySqlConnection objects.
New operator to instantiate many different concrete classes
Code becomes larger and needs to be replicated in many places
Factor that code out into a method.
Code keeps changing
Encapsulate code into a factory object
Goal: Separate out the changeable code and leave the core code closed for modification
Building the Factory
Creating the Factory
FirstFactory class encapsulates the connection object creation
Pass to it the type of connection (“Oracle”, “SQL Server”,)
Use the factory object to create connection objects with a factory method named createConnection
Building the Factory
Create the FirstFactory class.
Save the type of the database, passed to the FirstFactory class’s constructor.
Object-creation code changes
Check which type of object to be created
(OracleConnection, SqlServerConnection,
and then create it.
Factory Class
Create the Abstract Connection Class
Core code should not be modified or has to be modified
as little as possible.
Using the connection object returned by the
new factory object
Use t.
The document discusses the Model-View-Controller (MVC) architectural pattern. MVC separates an application into three main components: the model, the view, and the controller. The model manages the behavior and data of the application, the view manages the display of the model, and the controller handles input and interaction with the model and view. The document provides examples of how MVC is implemented in different frameworks like ASP.NET, Windows Forms, and Java Server Pages.
An assembly in .NET is a collection of types and resources that form a logical unit. Assemblies can contain metadata about types using attributes. Attributes provide additional information that can be attached to classes, methods, and other members. There are built-in attributes in .NET and custom attributes can be created by deriving from the Attribute base class. Built-in attributes like Required and StringLength are used to validate model data in ASP.NET MVC. A custom MyLicenseAttribute was created to require a license key by applying the attribute to assemblies. Attributes help add metadata and customize behavior.
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
This document provides an overview of Maven, Subversion (SVN), and GIT. It discusses how to install and set up Maven, create Maven projects, and manage dependencies. It also explores version control systems, specifically SVN and GIT. With SVN, it demonstrates how to create repositories and check out projects. It discusses merging code and avoiding conflicts. The document is a presentation intended to teach these topics.
IRJET- Lightweight MVC Framework in PHPIRJET Journal
This document discusses a lightweight Model-View-Controller (MVC) framework for PHP programming. It begins by providing background on PHP and the traditional MVC pattern. It then introduces a lightweight MVC framework for PHP that aims to improve efficiency, reduce complexity, and enhance security, stability and robustness. The framework consists of components like the index page, libraries, business controller, MVC base class, and database/template layers. It allows developers to get the benefits of MVC while maintaining simplicity. Some advantages are fast development, low maintenance and high performance, while disadvantages include needing programming expertise and less built-in support.
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
This document provides an over view of spring IOC and it's advantages. It also gives basic idea on the spring core container. At the last it describes how develop a simple spring application
The 9 new features in Java 9 are: 1) the Java Platform module system, 2) linking, 3) JShell interactive shell, 4) improved Javadoc search, 5) collection factory methods, 6) Stream API improvements, 7) private interface methods, 8) support for HTTP/2, and 9) multi-release JARs that allow libraries to use new Java features while maintaining backward compatibility.
This document provides an overview of Asp.Net MVC and how it compares to traditional Asp.Net web forms. Some key points:
- Asp.Net MVC follows the MVC pattern, separating concerns into models, views, and controllers, allowing for cleaner code and easier testing compared to Asp.Net web forms.
- In Asp.Net MVC, controllers handle requests and return action results, views are responsible for the UI, and models represent application data. This separation of concerns is more aligned with HTTP concepts.
- Asp.Net MVC aims to be more flexible, maintainable, and testable than web forms. It allows for tighter control over HTML and adheres to conventions over configurations
The document discusses client-side JavaScript and DOM (Document Object Model) manipulation. It covers the window object, DOM programming interface, DOM element types like Node and HTML Element. Methods for accessing elements like getElementById(), getElementsByName(), and querySelector() are explained. Working with element attributes, innerHTML, and traversing the DOM using childNodes and parentNode properties are also summarized. The presentation aims to explain DOM and how JavaScript can be used to get, change, add or remove HTML elements.
Hibernate is an object-relational mapping tool that maps objects to database tables. It creates a "virtual object database" that can be used from within programming languages. Hibernate is a persistence framework that stores and retrieves data to and from a permanent medium like a database. Configuration files like hibernate.cfg.xml are used to map classes and their attributes to database tables and columns. The SessionFactory interface manages connections to the database using the configuration files.
The document discusses Struts framework and internationalization (I18N) applications. Some key points:
1. Struts is a MVC framework that simplifies development of web applications. It provides components like ActionServlet and tag libraries.
2. I18N applications display output based on the user's locale/language. This is achieved using properties files with language-specific translations and the ResourceBundle class.
3. In Struts, properties files are configured in struts-config.xml and accessed in JSPs using the <message> tag. Keys not found will result in errors unless null=false is specified.
This document discusses JavaScript design patterns. It begins by defining what a design pattern is, noting that patterns provide proven solutions to common software development problems. It then summarizes several categories of design patterns, including creational patterns (which deal with object creation), structural patterns (which concern relationships between entities), and behavioral patterns (which focus on communication between objects). Specific patterns like module, facade, and mediator are then explained in more detail with examples provided.
This presentation illustrates DocIndex, InternetMiner and VisioDecompositer - my 3 proprietary test tools - and walks the user through how they are used effectively.
The tools are presented in the context of a Test Strategy and the emphasis is on HOW the tools are used and the rationale behind the esign of the tools.
View this presentation with SPEAKERS NOTES ON.
Java servlets are small programs that run on a web server and dynamically generate web page content. They extend the functionality of web servers and allow for more complex interactions than CGI programs. Servlets support multithreading and sharing of resources, making them faster than CGI programs which require creating a new process for each request. Common ways to handle form data submitted to servlets include using the getParameter() method to retrieve parameter values by name. Sessions can be tracked across requests using cookies, which are small pieces of data stored in the user's browser by the web server. There are two main architectures for developing JSP applications - page-centric and servlet-centric, with servlet-centric following the MVC pattern and separating business
Introduction to Spring's Dependency InjectionRichard Paul
This document provides an overview of dependency injection in Spring. It defines dependency injection as a form of inversion of control where objects are provided to classes rather than having classes create their own dependencies. It discusses the benefits of dependency injection such as loose coupling, easy switching of implementations, and enhanced testability. It also compares constructor injection and setter injection and describes how to configure dependency injection using XML, annotations, and Java configuration in Spring.
The document discusses object-relational mapping (ORM) and Hibernate. It describes how Hibernate provides a layer between a database and application code to abstract away differences in database types. This allows changing the backend database without changing code. Hibernate also maps object-oriented domain models to relational database tables through configuration files or annotations. Examples show how to configure Hibernate and perform basic operations like inserting a record.
Struts is a web application framework that uses the MVC design pattern. It combines Java servlets, JavaServer Pages, custom tags and message resources. Struts acts as a controller in MVC that routes requests between the view (JSPs) and the model (business logic classes). Struts is open source software hosted by the Apache Software Foundation. It provides a standard way to build Java web applications by separating the application logic from the user interface.
The document provides an overview of the key components of Windows Azure, Microsoft's cloud computing platform. It describes the Compute service which allows running applications on virtual machines at scale, the Storage service which provides blobs, tables and queues to store and access data, and the Fabric which manages resources and monitors applications running on the platform. The goal of Windows Azure is to provide a foundation for building and running applications in the cloud similar to what an operating system provides for on-premises applications.
React.js is a JavaScript library developed by awesome engineers at Facebook. React is really fast, any app developed in React can handle complex updates and still feel quick and responsive. It uses reusable components, it’s modularity makes it really easy to maintain JavaScript (spaghetti code). React performs best with large programs that constantly require data changes, and this is a very famous language, understanding. React will definitely make you more employable.
Prerequisite to understanding React.js is JavaScript fundamentals,
This document describes how to rapidly develop a web application using ASP.NET MVC 3 in Microsoft Visual Studio 2010. It outlines how to create a new project, add models, contexts, controllers with CRUD functionality, and use HTML helpers and dynamic templates to simplify development. MVC 3 enables full control over HTML while separating concerns, and allows both basic and complex applications to be built quickly through its RAD elements integrated into Visual Studio.
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
Patterns (contd)
Software Development Process
Design patterns used to handle change
More time extending and changing code than developing it.
The Strategy design pattern handle change by selecting from a family of external algorithms rather than rewrite.
Design point: Make code closed for modification of code, but open for extension
Problem
Computer object created
Description Method returns
Getting a Computer
Problem
Program has to change every time
Customer changes options
Decorator Pattern
Wrapper code used to extend your core code
Extend a class dynamically at runtime
Decorator uses wrapper code to extend core functionality - decorating the code
Decorator Pattern
description() returns “You are getting a computer”
Wrapper description() returns
“You are getting a computer and a disk”
Wrapper description() returns
“You are getting a computer and a disk and a monitor”
Decorator Pattern
Core component: Computer
Variables holding computer objects should also be able to hold objects that wrap computer objects.
Extend the wrapper classes from the Computer class.
Abstract class cannot be instantiated
Ensures all wrappers are consistent
Developers have to provide their own description
Decorator Pattern
Method calls the core computer object’s
description method and adds “and a disk”
Decorator Pattern
Method calls the core computer object’s
description method and adds “and a disk”
Extend the core object by wrapping it in decorator wrappers. Avoids modification of the core code.
Each successive wrapper called the description method of the object it wrapped and added something to it.
Factory Pattern
Based on type, call the
Connection method
Factory Pattern
Create a method that returns the
correct connection type
Factory Pattern
New operator used to create OracleConnection objects.
New operator used to create SqlServerConnection objects, and MySqlConnection objects.
New operator to instantiate many different concrete classes
Code becomes larger and needs to be replicated in many places
Factor that code out into a method.
Code keeps changing
Encapsulate code into a factory object
Goal: Separate out the changeable code and leave the core code closed for modification
Building the Factory
Creating the Factory
FirstFactory class encapsulates the connection object creation
Pass to it the type of connection (“Oracle”, “SQL Server”,)
Use the factory object to create connection objects with a factory method named createConnection
Building the Factory
Create the FirstFactory class.
Save the type of the database, passed to the FirstFactory class’s constructor.
Object-creation code changes
Check which type of object to be created
(OracleConnection, SqlServerConnection,
and then create it.
Factory Class
Create the Abstract Connection Class
Core code should not be modified or has to be modified
as little as possible.
Using the connection object returned by the
new factory object
Use t.
The document discusses the Model-View-Controller (MVC) architectural pattern. MVC separates an application into three main components: the model, the view, and the controller. The model manages the behavior and data of the application, the view manages the display of the model, and the controller handles input and interaction with the model and view. The document provides examples of how MVC is implemented in different frameworks like ASP.NET, Windows Forms, and Java Server Pages.
The document introduces ASP.NET Identity, which is Microsoft's new platform for managing users in ASP.NET applications. It has replaced the older ASP.NET Membership platform. The document discusses setting up an ASP.NET Identity implementation in an example project, including installing NuGet packages, defining a database context class, and creating a basic user management interface. It also provides an overview of how ASP.NET Identity uses OWIN/Katana to provide services to web applications in a more modular way compared to the previous ASP.NET Membership system.
Workshop - The Little Pattern That Could.pdfTobiasGoeschel
The document discusses refactoring a monolithic application to follow Domain-Driven Design (DDD) and microservice principles. It provides exercises and hints to guide refactoring the codebase to use Hexagonal Architecture with separated domains, commands and queries using CQRS, and persistence-oriented repositories. Later exercises discuss improving test speed by isolating dependencies and refactoring for a serverless architecture by splitting the application into individual use cases and replacing the in-memory repository.
Two months ago I wrote about benefits of Community Frameworks compared with Home-Grown ones. In the article I mentioned some of the benefits of Cake, but it was “scratching the surface” rather than complete info
This document summarizes a presentation on leveraging object-oriented programming techniques in LotusScript. It introduces object-oriented concepts like classes, objects, and encapsulation. It then walks through building an application to monitor news sites for company mentions using a class to represent each site and a nested class to represent individual news items. The presentation demonstrates encapsulating the news item class within the site class and using inheritance by extending all classes from a base class. It shows how to make the application more robust by adding logging through the base class.
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Bill Buchan
Co-presented with Jens Augustini
Object Oriented Programming (OOP) may drastically reduce your coding time in projects that reach a higher degree of complexity, as it brings re-usable and consistent logic in the form of your own objects to your fingertips. This session will show how to create and use your own classes and how they can relate to the LotusScript Object Model. If you are familiar with LotusScript but don't know how to create your own classes, this session is for you!
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
SVR Technologies providing the course content of C Sharp.net. It was given by our expert Poornima to improve the knowledge of the readers. For more details about other IT courses please visit http://www.svrtechnologies.com
SVR Technologies
Contact: 91- 988 502 2027
info@svrtechnologies.com
http://svrtechnologies.com
Luis Valencia will give a presentation on applying Typescript design patterns to React/SPFx. He has 17 years of experience including 10 years in SharePoint. The session will focus on writing clean, maintainable code and not flashy user interfaces. It will cover common design patterns like singleton, abstract factory, builder, and factory method. It will also discuss SOLID principles and building shared code libraries. The presentation aims to teach developers how to write code that is easy for others to maintain.
The document discusses several design patterns including Inversion of Control (IoC), Dependency Injection (DI), Repository pattern, and Unit of Work pattern. IoC is a design principle that inverts control of object creation and dependencies to achieve loose coupling. Dependency Injection is a pattern that implements IoC by allowing dependent objects to be created outside of a class. The Repository pattern abstracts data access logic from business logic. The Unit of Work pattern groups multiple data transactions into a single transaction.
Here are some of the key purposes of the ApplicationContext in Spring:
- It extends and builds upon the basic functionality of the BeanFactory by adding support for internationalization, event publication, resource loading, etc.
- It allows configuration through XML files and automatic detection of configuration metadata.
- It manages the complete lifecycle of beans within the context, including instantiation, configuration, dependency injection, and destruction.
- It supports transparently loading bean definitions from a variety of external locations. This includes classpath, file system, URLs, etc.
- It provides a simplified and more object-oriented model for accessing configuration metadata and bean definitions during runtime compared to the BeanFactory.
- It allows for
ASP.NET MVC 5 Building Your First Web Application (A Beginner S GuideAlicia Buske
This document provides a beginner's guide to building a web application using ASP.NET MVC 5. It includes an overview of ASP.NET MVC and its core components - Models, Views, and Controllers. It then outlines steps to create an MVC project, setup a database using Entity Framework and SQL Server, and build pages for user registration, login, profile editing, and role-based authorization. It concludes with deploying the application to IIS.
This document discusses an automatic code generation tool called UJECTOR that can generate executable Java code from UML diagrams, including class diagrams, sequence diagrams, and activity diagrams. It notes the benefits of automatic code generation in reducing errors compared to manual coding. The paper also discusses some related work, including Enterprise Architect, Eclipse UML Generators, Rhapsody, and dCode - other tools that can generate code from UML models. Overall, the document examines challenges in ensuring consistency, accuracy, maintainability and efficiency when automatically generating code from UML models.
Ruby on Rails training certifies you with in demand Web Application Technologies to help you grab the top paying IT job title with Web Application skills and expertise in Full Stack. Rails is written in Ruby, which is a language explicitly designed with the goal of increasing programmer happiness. This unbiased and universal view makes Ruby on Rails unique in today's Job market as a leader in the Web Application platform.
The document discusses frameworks in web development and provides examples using ASP.NET MVC framework. It defines what a framework is, explains the benefits of using frameworks like organizing code and faster development. It also describes the MVC pattern with model, view and controller components. An example application is built using ASP.NET MVC and Entity Framework to demonstrate how to create, build and run an MVC application.
CodeIgniter is a lightweight and open source PHP web application framework that uses the model-view-controller (MVC) approach. It provides basic functionality for common tasks like database connections, form handling and validation out of the box. CodeIgniter is easy to learn and use for beginners due to its simplicity and conventional PHP coding. While lightweight and fast, it lacks some functionality found in other frameworks like integrated CRUD and authentication libraries that require third party libraries. Overall, CodeIgniter provides a simple and flexible way to build PHP web applications.
The document provides an introduction to the ASP.NET MVC framework. It discusses the MVC pattern and how ASP.NET MVC works, including controllers handling requests and rendering views. It then walks through creating a sample ASP.NET MVC project, examining the default code, and creating a basic controller and view.
Similar to Generic Repository Pattern in MVC3 Application with Entity Framework (20)
This document discusses content negotiation in ASP.NET Web API 2. It explains what content negotiation is, why it is important, and how to implement it in Web API. Content negotiation allows a client to specify the desired response format using request headers like Accept and Content-Type. Web API uses formatters to serialize the response into the requested format. The document provides examples of configuring formatters to support different media types and customize the JSON output. It also describes how the content negotiation pipeline in Web API works to select the appropriate formatter based on the request headers.
The document discusses new and improved debugging features in Visual Studio 2015, including easier breakpoint configuration with an inline toolbar, simplified context menus, and settings windows that appear as peek windows. It also covers breakpoint conditions that allow hitting a breakpoint based on the number of hits or a conditional expression. Breakpoint actions allow logging messages to the output window. Additionally, the improved Error List in VS 2015 displays all errors at once, allows filtering by severity and error code, and links error codes to documentation.
This document discusses code refactoring techniques in Visual Studio 2015, including inline temporary variables and introducing local variables. It provides an example C# class with a method to fetch products above a certain price, and shows how Visual Studio's code refactoring suggestions can optimize the method in multiple steps. These include removing temporary variables, converting the method to an expression-bodied member, and reducing the code to a single line. The document emphasizes that code refactoring requires an understanding of how the changes will affect the code.
The document discusses renaming features in Visual Studio 2015. It describes how VS2015 provides renaming assistance through suggestions from the light bulb icon and previews changes before renaming. The renaming window allows renaming variables, methods, properties, classes, parameters and strings. It can also rename code comments and detect conflicts if the new name already exists. Renaming occurs inline and on the fly. The examples demonstrate renaming a variable, method, and parameter across multiple files. VS2015 helps optimize code through intelligent and automated renaming.
The document discusses Visual Studio's live static code analysis feature. It explains that this feature analyzes code in real-time as it is written, without requiring compilation, to detect errors and potential issues based on installed code analyzers. The document demonstrates how to install and use code analyzers through examples, showing how analyzers detect issues and provide suggestions to fix problems directly in the code editor through light bulb notifications. It provides a case study walking through fixing various issues detected in sample code using suggestions from an analyzer to iteratively improve the code quality.
The document discusses the code assistance features of Visual Studio 2015. It provides examples of how the light bulb icon displays potential fixes for syntax errors and missing code. It also shows how refactoring suggestions are provided to optimize code, such as removing unused namespaces or changing a method to directly return a value rather than using a temporary variable. The light bulb icon assists with code completion, error fixing, and refactoring to improve code quality and developer productivity.
Release planning is a challenging but important part of the agile development process. There are two main approaches to release planning: fixed timeline and fixed scope of work. With a fixed timeline, the deadline cannot be extended and functionality may need to be cut, while a fixed scope defines what must be included regardless of timeline. The objective of release planning is to baseline the product roadmap and team commitments, while allowing flexibility based on which approach is chosen.
This document discusses extending OData support in ASP.NET Web APIs. It provides an introduction to OData and the roadmap for a RESTful Web API series. It describes setting up a solution to add OData support and modifying existing API endpoints to be OData enabled. This allows queries to support options like $top, $filter, $orderby and more to filter, sort, page and select data from the server.
The document describes setting up unit testing for a Web API project using NUnit and Moq frameworks. It includes:
1. Adding a test project and installing necessary packages like NUnit, Moq, EntityFramework, and Newtonsoft.Json.
2. Defining variables and setting up mocks for the repositories, services, and UnitOfWork classes needed for the tests.
3. Writing tests for the ProductController including getting all products, getting a product by ID, and testing exceptions.
4. Explaining how to mock the repositories to simulate database operations during the tests.
So in summary, it covers the steps to set up a Web API project for unit testing and then provides examples
This document discusses unit testing Web APIs using the NUnit and Moq frameworks. It provides an overview of unit testing and the NUnit and Moq frameworks. It then details setting up a test project and installing necessary packages. The document focuses on writing unit tests for the business logic layer and controllers, demonstrating how to test a ProductService class by mocking dependencies, writing test methods, and more.
The document discusses implementing request and exception logging in ASP.NET Web APIs using NLog, Action Filters, and Exception Filters. It describes setting up NLog configuration, creating an NLogger class to handle logging, and adding an Action Filter (LoggingFilterAttribute) to log requests. It also covers adding an Exception Filter (GlobalExceptionAttribute) to log exceptions, modifying classes to support exception logging, and throwing an exception to test the exception logging.
This document introduces the MVC architecture and separation of concerns. It outlines a 6 part roadmap to cover MVC fundamentals and implementing it with Entity Framework. Part 1 introduces MVC, defining the roles of models, views, and controllers. It explains how MVC separates the application into independent and reusable components for the model, views for presentation, and controllers for handling requests. This separation aims to improve maintainability and extensibility of applications.
This document discusses implementing security in a Web API using basic authentication and token-based authorization. It introduces basic authentication as a means of validating a user's credentials through a username and password sent in the request header. Token-based authorization is described as sending a token to authenticated users that allows them to access other resources. The document then outlines steps to create a user service, implement basic authentication using an authentication filter, and implement token-based authorization by setting up databases, services, and controllers and marking them with an authorization filter. Maintaining sessions with tokens is also briefly mentioned.
C sharp and asp.net interview questionsAkhil Mittal
The document provides summaries of common questions and answers related to ASP.NET, C#, and the .NET framework. It defines view state as storing the current property settings of an ASP.NET page and controls to detect form submissions. It explains that user controls allow reusing ASP.NET pages as controls, and validation controls perform input checking on server controls. The document also distinguishes between Response.Write and Response.Output.Write, and lists page life cycle methods like Init, Load, and Unload.
This document provides answers to common ASP.NET interview questions. It begins with questions about the differences between custom controls and user controls, ASP session state and ASP.NET session state, and datasets versus recordsets in ADO.NET. Subsequent questions cover topics like view state, authentication, caching, validation controls, and working with data controls.
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc., my priority always remains to cover the topic as a whole, so that a reader do not have to search for missing links anywhere else. My this article will cover almost every OOPS concept that a novice/beginner developer hunt for, and not only beginners, the article’s purpose is to be helpful to experience professionals also who need to sometimes brush-up their concepts or who prepare for interviews .
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Akhil Mittal
My article of the series “Diving in OOP” will explain enum datatype in C#. We’ll learn by doing hands on lab and not only by theory. We’ll explore the power of enum and will cover almost every scenario in which we can use enum. We’ll follow a practical approach of learning to understand this concept. We may come across complex examples to understand the concept more deeply.
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Akhil Mittal
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Akhil Mittal
The document discusses runtime polymorphism in C# using method overriding. It shows how to override methods in a derived class by marking the base class methods as virtual and using the override keyword in the derived class. An experiment is conducted where calling a method on an object initialized as the base class but actually referring to a derived class instance results in the overridden method from the derived class being called due to runtime binding.
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Generic Repository Pattern in MVC3 Application with Entity Framework
1. Learning MVC-Part 6
Generic Repository Pattern in MVC3 Application with Entity Framework
Introduction:
Creating a Generic Repository Pattern in MVC3 Application with Entity Framework is the last
topic that we are about to cover in our journey of Learning MVC.
The article will focus on Unit Of Work Pattern and Repository Pattern, and shows how to
performCRUD operations in an MVC application when there could be a possibility of creating
more than one repository class. To overcomethis possibility and overhead, we make a Generic
Repository class for all other repositories and implement a Unit of Work pattern to provide
abstraction.
Our roadmap towards Learning MVC:
Just to remind our full roadmap towards learning MVC,
Part1: Introduction to MVC architecture and Separation of Concerns.
Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to
SQL.
Part 3: Connecting the MVC Application with the help of EntityFramework DB-Firstapproach.
Part 4: Connecting the MVC Application with the help of EntityFramework Code-First
approach.
Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.
Part 6: Implementing a Generic Repository PatternandUnit Of Work patterninMVC
ApplicationwithEntityFramework.
Pre-requisites:
There are few pre-requisites beforewe start with the article,
1. We haverunning sample application that we created in fifth part of the article series.
2. We haveEntityFramework 4.1 packageor dll on our local file system.
3. We understand how MVCapplication is created(Follow second partof the series).
Why Generic Repository:
2. We have already discussed whatRepository Pattern is and why do we need Repository Pattern
in our last article. We created a User Repository for performing CRUD operations, but think of
the scenario wherewe need 10 such repositories.
Are we going to create these classes?, notgood, it results in a lot of redundantcode. So to
overcomethis situation we’ll create a Generic Repository class that will be called by a property
to create a new repository thus wedo not result in lot of classes and also escaperedundant
code too. Moreover we savea lot of time that could be wasted creating those classes.
Unit of Work Pattern:
According to Martin Fowler Unit of Work Pattern “Maintains a list of objects affected by a
business transaction and coordinates the writing out of changes and the resolution of
concurrency problems.”
FromMSDN, The Unit of Work pattern isn't necessarily something that you will explicitly build
yourself, butthe pattern shows up in almost every persistencetool. The ITransaction interface
in NHibernate, the DataContext class in LINQ to SQL, and the ObjectContext class in the Entity
Framework areall examples of a Unit of Work. For that matter, the venerableDataSet can be
used as a Unit of Work.
Other times, you may want to write your own application-specific Unit of Work interface or
class that wraps the inner Unit of Work fromyour persistencetool. You may do this for a
number of reasons. You might want to add application-specific logging, tracing, or error
handling to transaction management. Perhaps you want to encapsulate the specifics of your
persistencetooling fromthe rest of the application. You might wantthis extra encapsulation
3. to make it easier to swap out persistencetechnologies later. Or you might want to promote
testability in your system. Many of the built-in Unit of Work implementations fromcommon
persistencetools are difficult to deal with in automated unit testing scenarios.”
The Unit of Work class can have methods to mark entities as modified, newly created, or
deleted. The Unit of Work will also have methods to commit or roll back all of the changes as
well.
The important responsibilities of Unit of Work are,
To manage transactions.
To order the databaseinserts, deletes, and updates.
To prevent duplicate updates. Insidea single usage of a Unit of Work object, different
parts of the code may mark the sameInvoice object as changed, but the Unit of Work
class will only issuea single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code fromthese concerns
so that you can otherwiseconcentrate on business logic.
Why use Unit of Work?
Again Martin Fowler statements,”When you'repulling data in and out of a database, it's
important to keep track of what you'vechanged; otherwise, that data won't be written back
into the database. Similarly you have to insert new objects you create and remove any objects
you delete.
You can change the database with each change to your object model, but this can lead to lots
of very small databasecalls, which ends up being very slow. Furthermoreit requires you to
have a transaction open for the whole interaction, which is impractical if you havea business
transaction that spans multiple requests. The situation is even worseif you need to keep track
of the objects you've read so you can avoid inconsistentreads.
4. A Unit of Work keeps track and takes responsibility of everything you do during a business
transaction that can affect the database. When you'redone, it figures out everything that
needs to be done to alter the databaseas a result of your work.”
You see I don’t haveto concentrate much on theory, we already havegreat definitions
existing, all we needed is to stack them in a correct format.
Using the Unit of Work
One of the best ways to usethe Unit of Work pattern is to allow disparateclasses and services
to take partin a single logical transaction. The key point here is that you want the disparate
classes and services to remain ignorant of each other while being able to enlist in a single
transaction. Traditionally, you'vebeen able to do this by using transaction coordinators like
MTS/COM+ or the newer System.Transactions namespace. Personally, I prefer using the Unit
of Work pattern to allow unrelated classes and services to take part in a logical transaction
because I think it makes the code more explicit, easier to understand, and simpler to unit
test(FromMSDN).
Creating Generic Repository:
Cut the Redundancy…
Step1: Open up our existing MVC3 application created in Part5 in Visual Studio.
Step2: Right click Learning MVCproject folder and create a folder named GenericRepository
and add a class named GenericRepository.cs to that folder.
The code of the GenericRepository.cs class is as follows,
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
5. using System.Linq.Expressions;
namespaceLearningMVC.GenericRepository
{
public class GenericRepository<TEntity> whereTEntity : class
{
internal MVCEntities context;
internal DbSet<TEntity> dbSet;
public GenericRepository(MVCEntities context)
{
this.context = context;
this.dbSet= context.Set<TEntity>();
}
public virtual IEnumerable<TEntity>Get()
{
IQueryable<TEntity>query = dbSet;
return query.ToList();
}
public virtual TEntity GetByID(objectid)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
6. }
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State= EntityState.Modified;
}
}
}
We can see, we havecreated the generic methods and the class as well is generic, when
instantiating this class we can pass any model on which the class will work as a repository and
servethe purpose.
TEntity is any model/domain/entity class
MVCEntities is our DBContext as discussed in earlier parts.
Step3:Implementing UnitOfWork : Create a folder named UnitOfWork under LearningMVC
project, and add a class UnitOfWork.cs to thatfolder.
The code of the class is as follows,
using System;
using LearningMVC.GenericRepository;
namespaceLearningMVC.UnitOfWork
{
public class UnitOfWork : IDisposable
{
private MVCEntities context = new MVCEntities();
private GenericRepository<User>userRepository;
public GenericRepository<User>UserRepository
{
get
{
if (this.userRepository ==null)
this.userRepository =new GenericRepository<User>(context);
return userRepository;
}
7. }
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(booldisposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed =true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
We see the class implements IDisposableinterfacefor objects of this class to be disposed.
We create objectof DBContext in this class,notethat earlier it was used to be passed in
Repository class froma controller.
Now its time to create our User Repository.Wesee in the code itself that, simply a variable
named userRepository is declared as privateGenericRepository<User>userRepository; of
type GenericRepository serving User entity to TEntity template.
Then a property is created for the same userRepository variablein a very simplified manner,
public GenericRepository<User>UserRepository
{
get
{
if (this.userRepository ==null)
8. this.userRepository =new GenericRepository<User>(context);
return userRepository;
}
}
i.e. mere 6-7 lines of code.Guess what? Our UserRepository is created.
(taken fromgoogle)
You see it was as simple as that,you can create as many repositories you want by justcreating
simple properties,and no need to create separateclasses. And now you can complete the rest
of the story by yourself,Confused????,Yes its DBOperations , lets do it.
Step4:In MyController, declarea variableunitOfWork as,
private UnitOfWork.UnitOfWork unitOfWork =new UnitOfWork.UnitOfWork();
Now this unitOfWork instanceof UnitOfWork class holds all th repository properties,if we
press “.” After it, it will show the repositories.So wecan chooseany of the repositories created
and performCRUD operations on them.
e.g. our Indexaction,
public ActionResult Index()
{
var userList= from user in unitOfWork.UserRepository.Get() selectuser;
var users = new List<LearningMVC.Models.UserList>();
if (userList.Any())
{
foreach (var user in userList)
{
users.Add(new LearningMVC.Models.UserList() { UserId =user.UserId, Address =
user.Address, Company =user.Company, FirstName=user.FirstName, LastName=
user.LastName, Designation = user.Designation, EMail= user.EMail, PhoneNo = user.PhoneNo
});
}
}
ViewBag.FirstName= "My FirstName";
ViewData["FirstName"] ="My FirstName";
if(TempData.Any())
{
var tempData = TempData["TempData Name"];
9. }
return View(users);
}
Here,
unitOfWork.UserRepository Accessing UserRepository.
unitOfWork.UserRepository.Get() Accessing Generic Get() method to get all users.
Earlier we use to have MyController constructor like ,
public MyController()
{
this.userRepository =new UserRepository(new MVCEntities());
}
Now, no need to write that constructor, infactyou can Remove the UserRepository class and
Interfacewecreated in 5th
Part of Learning MVC.
I hope you can write the Actions for rest of the CRUD operations as well.
Details:
public ActionResult Details(int id)
{
var userDetails = unitOfWork.UserRepository.GetByID(id);
var user = new LearningMVC.Models.UserList();
if (userDetails != null)
{
user.UserId =userDetails.UserId;
user.FirstName=userDetails.FirstName;
user.LastName= userDetails.LastName;
user.Address=userDetails.Address;
user.PhoneNo =userDetails.PhoneNo;
user.EMail= userDetails.EMail;
user.Company =userDetails.Company;
user.Designation =userDetails.Designation;
}
return View(user);
}
Create:
[HttpPost]
public ActionResult Create(LearningMVC.Models.UserListuserDetails)
10. {
try
{
var user = new User();
if (userDetails != null)
{
user.UserId =userDetails.UserId;
user.FirstName= userDetails.FirstName;
user.LastName= userDetails.LastName;
user.Address =userDetails.Address;
user.PhoneNo = userDetails.PhoneNo;
user.EMail = userDetails.EMail;
user.Company = userDetails.Company;
user.Designation = userDetails.Designation;
}
unitOfWork.UserRepository.Insert(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Edit:
public ActionResult Edit(int id)
{
var userDetails = unitOfWork.UserRepository.GetByID(id);
var user = new LearningMVC.Models.UserList();
if (userDetails != null)
{
user.UserId =userDetails.UserId;
user.FirstName=userDetails.FirstName;
user.LastName= userDetails.LastName;
user.Address=userDetails.Address;
user.PhoneNo =userDetails.PhoneNo;
user.EMail= userDetails.EMail;
user.Company =userDetails.Company;
user.Designation =userDetails.Designation;
}
11. return View(user);
}
[HttpPost]
public ActionResult Edit(int id, User userDetails)
{
TempData["TempData Name"] = "Akhil";
try
{
var user = unitOfWork.UserRepository.GetByID(id);
user.FirstName=userDetails.FirstName;
user.LastName= userDetails.LastName;
user.Address=userDetails.Address;
user.PhoneNo =userDetails.PhoneNo;
user.EMail= userDetails.EMail;
user.Company =userDetails.Company;
user.Designation =userDetails.Designation;
unitOfWork.UserRepository.Update(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
Delete:
public ActionResult Delete(int id)
{
var user = new LearningMVC.Models.UserList();
var userDetails = unitOfWork.UserRepository.GetByID(id);
if (userDetails != null)
{
user.FirstName=userDetails.FirstName;
user.LastName= userDetails.LastName;
user.Address=userDetails.Address;
user.PhoneNo =userDetails.PhoneNo;
user.EMail= userDetails.EMail;
user.Company =userDetails.Company;
user.Designation =userDetails.Designation;
}
return View(user);
}
12. [HttpPost]
public ActionResult Delete(int id, LearningMVC.Models.UserListuserDetails)
{
try
{
var user = unitOfWork.UserRepository.GetByID(id);
if (user != null)
{
unitOfWork.UserRepository.Delete(id);
unitOfWork.Save();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Note: Images are taken from google images.
Conclusion
We now know how to make generic repositories too, and performCRUD operations using it.
We have also learnt UnitOfWork pattern in detail. Now you are qualified and confident
enough to apply these concepts in your enterprise applications.This was lastpart of this MVC
series, let me know if you feel to discuss any topic in particular or we can also start any other
series as well .
Happy Coding :-).