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 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 .
1) Single page applications (SPAs) use JavaScript to dynamically update the content of a single web page rather than loading entire new pages. This reduces page refreshes.
2) React is a popular JavaScript library for building user interfaces, especially for SPAs. It uses a virtual DOM for faster rendering.
3) Create-React-App is a command line interface that sets up a React project with common dependencies like Babel and Webpack preconfigured.
Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.
8 Reasons to Use React Query" is likely a presentation discussing the benefits of using the React Query library for managing and caching data in a React application. The slides may cover topics such as efficient data fetching, automatic caching and stale-while-revalidate, real-time updates, and easy-to-use hooks for handling queries and mutations. Additionally, the slides may also highlight how React Query helps improve the performance, developer experience, and user experience of the application.
Spring Security is a powerful and highly customizable authentication and authorization framework for Spring-based applications. It provides authentication via mechanisms like username/password, LDAP, and SSO. Authorization can be implemented through voting-based access control or expression-based access control at the web (URL) level and method level. It includes filters, providers, and services to handle authentication, authorization, logout, and remember-me functionality. Configuration can be done through XML or Java configuration with support for common annotations.
The document discusses Swagger, an open source API documentation framework. It describes how Swagger is used to document REST APIs and provides an interactive UI. It then outlines how to add Swagger documentation to a Spring Boot project using Springfox, including adding dependencies, configuring Swagger, and annotating controllers. The document demonstrates how Swagger UI allows developers to easily view and test documented APIs in the browser.
Swagger UI enables generating documentation for RESTful APIs that is updated as the server code changes. It works with Spring Boot by adding dependencies, a configuration file, and annotations. This exposes API endpoints in the browser for testing and provides descriptive documentation of each service's title, function, inputs, and outputs.
The document discusses the Spring Framework, an open source application framework for Java. It provides inversion of control and dependency injection to manage application objects. The core package provides dependency injection while other packages provide additional features like transaction management, ORM integration, AOP, and MVC web development. The framework uses an IoC container to manage application objects called beans through configuration metadata.
Annotations provide metadata that can be applied to Java code elements. They do not directly affect program semantics but can be read and used by tools and libraries. The key points are:
1. Annotations were introduced in Java 5 to allow programmers to add metadata directly in code.
2. Common uses of annotations include providing compiler instructions, documentation, code generation, and runtime processing.
3. Annotation types define the structure of annotations and can be further configured using meta-annotations like @Target and @Retention.
The document introduces the basics of Java, including its keywords, syntax, and comparison to traditional programming. It explains that in Java, source code is compiled to bytecode, which is then interpreted by the Java Runtime Environment (JRE) using the Java Virtual Machine (JVM) to run on any platform. The JRE contains both the JVM and Java Application Programming Interface (JAPI). The Java Development Kit (JDK) contains the JRE as well as development tools like compilers and debuggers. Java programs can use default and third party libraries that are part of the JAPI.
OCA Java SE 8 Exam Chapter 5 Class Designİbrahim Kürce
Inheritance is the process by which the new child subclass automatically includes any public or protected primitives, objects, or methods defined in the parent class.
We refer to any class that inherits from another class as a child class, or a descendent of that class.
We refer to the class that the child inherits from as the parent class, or an ancestor of the class.
This document provides an overview of Hibernate, an object-relational mapping tool for Java. It begins with a list of topics covered and then defines what Hibernate and JDBC are. It describes the Hibernate architecture including configuration, sessions, and mapping. It also discusses annotations, HQL, caching and batch processing. The document provides details on configuring Hibernate with different databases as well as mapping files and object-relational mappings. It explains the use of annotations, HQL, criteria queries, and native SQL with Hibernate.
MVC stands for Model-View-Controller. The MVC pattern separates an application into three parts: the model, the view, and the controller. The model handles the application's data logic, the view handles presentation logic, and the controller handles business logic and communication between the model and view. MVC is commonly used in PHP frameworks like CodeIgniter to separate an application's logical components.
Spring Boot is a framework that makes it easy to create stand-alone, production-grade Spring based applications that you can "just run". It allows you to create stand-alone applications, embed Tomcat/Jetty directly with no need to deploy WAR files, and provides starter POMs to simplify configuration. Spring Boot applications are run by adding a spring-boot-gradle-plugin and can then be run as an executable JAR. Features include REST endpoints, security, external configuration, and production monitoring via Actuators.
This document provides examples of Java programming concepts and code snippets to demonstrate how to implement various Java features. It includes examples for Java basics like strings, arrays, files and directories as well as more advanced topics like collections, networking, threading and GUI programming. Each section breaks down a specific concept like string manipulation or environment settings into discrete code examples that show how to perform common tasks like comparing strings, setting the classpath, or splitting a string.
The document discusses RESTful APIs and some of their key concepts and design principles. It defines REST as an architectural style for building web APIs and describes six constraints of REST including a uniform interface, statelessness, cacheability, being client-server, having a layered system, and using hypermedia as the engine of application state. It then provides more details on concepts like resources, endpoints, verbs, versioning, authentication, and filtering.
In this session you will learn:
1. Principles of Object-Oriented Programming
2. Writing your first Java Application
3. Elements of Java programming language
4. Built in Data Types
5. Conditional Statements
6. Loops
Java Bean is a reusable software component that can be visually assembled into applications using visual development tools. It follows specific conventions like having public no-arg constructors, allowing properties to be read and written with get/set methods, and firing events. Beans are customizable, portable, and can persist their state. Introspection allows determining a bean's properties, methods, and events at runtime.
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns
It is often defined as a programming technique that promotes separation of crosscutting concerns with in a software system
concerns :
A concern is a particular issue, concept, or area of interest for an application: typically, a goal the application must meet
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
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.
- REST (Representational State Transfer) uses HTTP requests to transfer representations of resources between clients and servers. The format of the representation is determined by the content-type header and the interaction with the resource is determined by the HTTP verb used.
- The four main HTTP verbs are GET, PUT, DELETE, and POST. GET retrieves a representation of the resource and is safe, while PUT, DELETE, and POST can modify the resource's state in atomic operations.
- Resources are abstract concepts acted upon by HTTP requests, while representations are the actual data transmitted in responses. The representation may or may not accurately reflect the resource's current state.
Java handles two types of exceptions - unchecked exceptions and checked exceptions. Unchecked exceptions do not need to be handled by programmers, while checked exceptions must be handled. Checked exceptions are environment or server-related issues outside a programmer's control. There are three ways to handle checked exceptions: try-catch blocks, throwing exceptions with the throw keyword, or specifying exceptions with the throws keyword in method signatures. Finally blocks are used to ensure cleanup code executes after try or catch blocks complete.
This document discusses using interfaces and dependency injection to create a clean repository pattern with Entity Framework. It presents a typical dependency structure and issues with directly referencing data access layers. The solution shown uses interfaces to abstract data access and dependency injection to decouple layers. Code examples demonstrate implementing repositories, domain logic with constructor injection, and controllers without data dependencies. Benefits include flexibility to change data layers and performance.
Swagger UI enables generating documentation for RESTful APIs that is updated as the server code changes. It works with Spring Boot by adding dependencies, a configuration file, and annotations. This exposes API endpoints in the browser for testing and provides descriptive documentation of each service's title, function, inputs, and outputs.
The document discusses the Spring Framework, an open source application framework for Java. It provides inversion of control and dependency injection to manage application objects. The core package provides dependency injection while other packages provide additional features like transaction management, ORM integration, AOP, and MVC web development. The framework uses an IoC container to manage application objects called beans through configuration metadata.
Annotations provide metadata that can be applied to Java code elements. They do not directly affect program semantics but can be read and used by tools and libraries. The key points are:
1. Annotations were introduced in Java 5 to allow programmers to add metadata directly in code.
2. Common uses of annotations include providing compiler instructions, documentation, code generation, and runtime processing.
3. Annotation types define the structure of annotations and can be further configured using meta-annotations like @Target and @Retention.
The document introduces the basics of Java, including its keywords, syntax, and comparison to traditional programming. It explains that in Java, source code is compiled to bytecode, which is then interpreted by the Java Runtime Environment (JRE) using the Java Virtual Machine (JVM) to run on any platform. The JRE contains both the JVM and Java Application Programming Interface (JAPI). The Java Development Kit (JDK) contains the JRE as well as development tools like compilers and debuggers. Java programs can use default and third party libraries that are part of the JAPI.
OCA Java SE 8 Exam Chapter 5 Class Designİbrahim Kürce
Inheritance is the process by which the new child subclass automatically includes any public or protected primitives, objects, or methods defined in the parent class.
We refer to any class that inherits from another class as a child class, or a descendent of that class.
We refer to the class that the child inherits from as the parent class, or an ancestor of the class.
This document provides an overview of Hibernate, an object-relational mapping tool for Java. It begins with a list of topics covered and then defines what Hibernate and JDBC are. It describes the Hibernate architecture including configuration, sessions, and mapping. It also discusses annotations, HQL, caching and batch processing. The document provides details on configuring Hibernate with different databases as well as mapping files and object-relational mappings. It explains the use of annotations, HQL, criteria queries, and native SQL with Hibernate.
MVC stands for Model-View-Controller. The MVC pattern separates an application into three parts: the model, the view, and the controller. The model handles the application's data logic, the view handles presentation logic, and the controller handles business logic and communication between the model and view. MVC is commonly used in PHP frameworks like CodeIgniter to separate an application's logical components.
Spring Boot is a framework that makes it easy to create stand-alone, production-grade Spring based applications that you can "just run". It allows you to create stand-alone applications, embed Tomcat/Jetty directly with no need to deploy WAR files, and provides starter POMs to simplify configuration. Spring Boot applications are run by adding a spring-boot-gradle-plugin and can then be run as an executable JAR. Features include REST endpoints, security, external configuration, and production monitoring via Actuators.
This document provides examples of Java programming concepts and code snippets to demonstrate how to implement various Java features. It includes examples for Java basics like strings, arrays, files and directories as well as more advanced topics like collections, networking, threading and GUI programming. Each section breaks down a specific concept like string manipulation or environment settings into discrete code examples that show how to perform common tasks like comparing strings, setting the classpath, or splitting a string.
The document discusses RESTful APIs and some of their key concepts and design principles. It defines REST as an architectural style for building web APIs and describes six constraints of REST including a uniform interface, statelessness, cacheability, being client-server, having a layered system, and using hypermedia as the engine of application state. It then provides more details on concepts like resources, endpoints, verbs, versioning, authentication, and filtering.
In this session you will learn:
1. Principles of Object-Oriented Programming
2. Writing your first Java Application
3. Elements of Java programming language
4. Built in Data Types
5. Conditional Statements
6. Loops
Java Bean is a reusable software component that can be visually assembled into applications using visual development tools. It follows specific conventions like having public no-arg constructors, allowing properties to be read and written with get/set methods, and firing events. Beans are customizable, portable, and can persist their state. Introspection allows determining a bean's properties, methods, and events at runtime.
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns
It is often defined as a programming technique that promotes separation of crosscutting concerns with in a software system
concerns :
A concern is a particular issue, concept, or area of interest for an application: typically, a goal the application must meet
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
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.
- REST (Representational State Transfer) uses HTTP requests to transfer representations of resources between clients and servers. The format of the representation is determined by the content-type header and the interaction with the resource is determined by the HTTP verb used.
- The four main HTTP verbs are GET, PUT, DELETE, and POST. GET retrieves a representation of the resource and is safe, while PUT, DELETE, and POST can modify the resource's state in atomic operations.
- Resources are abstract concepts acted upon by HTTP requests, while representations are the actual data transmitted in responses. The representation may or may not accurately reflect the resource's current state.
Java handles two types of exceptions - unchecked exceptions and checked exceptions. Unchecked exceptions do not need to be handled by programmers, while checked exceptions must be handled. Checked exceptions are environment or server-related issues outside a programmer's control. There are three ways to handle checked exceptions: try-catch blocks, throwing exceptions with the throw keyword, or specifying exceptions with the throws keyword in method signatures. Finally blocks are used to ensure cleanup code executes after try or catch blocks complete.
This document discusses using interfaces and dependency injection to create a clean repository pattern with Entity Framework. It presents a typical dependency structure and issues with directly referencing data access layers. The solution shown uses interfaces to abstract data access and dependency injection to decouple layers. Code examples demonstrate implementing repositories, domain logic with constructor injection, and controllers without data dependencies. Benefits include flexibility to change data layers and performance.
Software re-engineering is a process of examining and altering a software system to restructure it and improve maintainability. It involves sub-processes like reverse engineering, redocumentation, and data re-engineering. Software re-engineering is applicable when some subsystems require frequent maintenance and can be a cost-effective way to evolve legacy software systems. The key advantages are reduced risk compared to new development and lower costs than replacing the system entirely.
Basics, Components, Design and Development of Web Application and Websites. Especially made for seminars and guest sessions for newbies in Web Development field.
STAENZ Academy
https://staenz.com/academy
Hi- tech Architecture and its pioneering architects, Norman Foster , Richard ...Rohit Arora
Norman Foster is considered a pioneer of hi-tech architecture. Some key aspects of hi-tech architecture include the display of the building's structural components on the exterior, use of prefabricated materials like glass panels, and steel frames. Hi-tech buildings aim to be energy efficient through the use of high technology. Norman Foster and other architects like Richard Rogers and Renzo Piano have designed several landmark hi-tech buildings around the world.
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).
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.
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.
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.
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.
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.
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.
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 provides an overview of ASP.NET MVC frameworks and how to get started with ASP.NET MVC 4. It discusses how ASP.NET MVC supports the MVC pattern and test-driven development. It also describes how to install ASP.NET MVC 4, create a basic MVC 4 project with different templates, add controllers and views, and connect to a database using Entity Framework.
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
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.
The document discusses the Model-View-Controller (MVC) pattern and ASP.NET MVC framework. It describes the key components of MVC - the Model, View and Controller. The Controller handles communication from the user, application flow and logic. The Model represents application data and business rules. The View displays the user interface. ASP.NET MVC is an MVC web application framework for ASP.NET that was open sourced by Microsoft. New versions of ASP.NET MVC added features like Razor view engine, model validation, and Web API for building HTTP services.
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.
This document discusses moving existing websites with security issues to the ASP.NET MVC framework using Entity Framework. It provides an overview of MVC and EF, how to set them up in Visual Studio, and examples of using them to improve security by removing direct SQL queries and moving more logic to the server. Key benefits highlighted include built-in features for validation and preventing cross-site request forgery attacks. Examples demonstrate querying databases and validating models without writing direct SQL or adding additional code.
This document discusses the benefits of using the .NET framework for web development. It begins by explaining that .NET compiles code to intermediate language (IL) rather than machine code. This allows the common language runtime (CLR) to manage aspects like garbage collection and exception handling. ASP.NET uses dynamic compilation for improved performance. The .NET framework also includes a large set of reusable classes. Additional benefits discussed include object-oriented architecture, caching, XML configuration, code separation, mobile support, powerful data access, language preference, and easy creation of web services.
This document provides an overview of Entity Framework 4 and how to use it in different scenarios. It discusses Code First, Model First, and Database First approaches. For Code First, it demonstrates how to create data classes and contexts and add a connection string. For Model First, it shows how to create an entity data model, generate a database from the model, and use the model in an MVC project. It also discusses how to generate models from an existing database. Finally, it demonstrates integrating Entity Framework with an MVC 3 and Razor project, including adding controllers and views to display and edit data.
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.
Generic Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
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.
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 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 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 in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Class...Akhil Mittal
This document provides an overview of abstract classes in C# object-oriented programming. It defines abstract classes as classes that cannot be instantiated and must be implemented in derived classes. The document demonstrates several key features of abstract classes through code examples, including: defining abstract and non-abstract methods in abstract classes; inheriting from abstract classes to instantiate derived classes; and requiring derived classes to implement abstract methods from the base abstract class.
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)Akhil Mittal
ClassA inherits from ClassB, allowing ClassA to access methods and properties defined in ClassB like Display1(). Defining a method in ClassA with the same name as one in ClassB will override and hide the base method, unless base is used to explicitly call the base method. Inheritance does not work backwards - a base class does not have access to methods defined in a derived class.
Artificial Intelligence is providing benefits in many areas of work within the heritage sector, from image analysis, to ideas generation, and new research tools. However, it is more critical than ever for people, with analogue intelligence, to ensure the integrity and ethical use of AI. Including real people can improve the use of AI by identifying potential biases, cross-checking results, refining workflows, and providing contextual relevance to AI-driven results.
News about the impact of AI often paints a rosy picture. In practice, there are many potential pitfalls. This presentation discusses these issues and looks at the role of analogue intelligence and analogue interfaces in providing the best results to our audiences. How do we deal with factually incorrect results? How do we get content generated that better reflects the diversity of our communities? What roles are there for physical, in-person experiences in the digital world?
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfAbi john
Analyze the growth of meme coins from mere online jokes to potential assets in the digital economy. Explore the community, culture, and utility as they elevate themselves to a new era in cryptocurrency.
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell
With expertise in data architecture, performance tracking, and revenue forecasting, Andrew Marnell plays a vital role in aligning business strategies with data insights. Andrew Marnell’s ability to lead cross-functional teams ensures businesses achieve sustainable growth and operational excellence.
Procurement Insights Cost To Value Guide.pptxJon Hansen
Procurement Insights integrated Historic Procurement Industry Archives, serves as a powerful complement — not a competitor — to other procurement industry firms. It fills critical gaps in depth, agility, and contextual insight that most traditional analyst and association models overlook.
Learn more about this value- driven proprietary service offering here.
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxJustin Reock
Building 10x Organizations with Modern Productivity Metrics
10x developers may be a myth, but 10x organizations are very real, as proven by the influential study performed in the 1980s, ‘The Coding War Games.’
Right now, here in early 2025, we seem to be experiencing YAPP (Yet Another Productivity Philosophy), and that philosophy is converging on developer experience. It seems that with every new method we invent for the delivery of products, whether physical or virtual, we reinvent productivity philosophies to go alongside them.
But which of these approaches actually work? DORA? SPACE? DevEx? What should we invest in and create urgency behind today, so that we don’t find ourselves having the same discussion again in a decade?
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc
Most consumers believe they’re making informed decisions about their personal data—adjusting privacy settings, blocking trackers, and opting out where they can. However, our new research reveals that while awareness is high, taking meaningful action is still lacking. On the corporate side, many organizations report strong policies for managing third-party data and consumer consent yet fall short when it comes to consistency, accountability and transparency.
This session will explore the research findings from TrustArc’s Privacy Pulse Survey, examining consumer attitudes toward personal data collection and practical suggestions for corporate practices around purchasing third-party data.
Attendees will learn:
- Consumer awareness around data brokers and what consumers are doing to limit data collection
- How businesses assess third-party vendors and their consent management operations
- Where business preparedness needs improvement
- What these trends mean for the future of privacy governance and public trust
This discussion is essential for privacy, risk, and compliance professionals who want to ground their strategies in current data and prepare for what’s next in the privacy landscape.
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxAnoop Ashok
In today's fast-paced retail environment, efficiency is key. Every minute counts, and every penny matters. One tool that can significantly boost your store's efficiency is a well-executed planogram. These visual merchandising blueprints not only enhance store layouts but also save time and money in the process.
How Can I use the AI Hype in my Business Context?Daniel Lehner
𝙄𝙨 𝘼𝙄 𝙟𝙪𝙨𝙩 𝙝𝙮𝙥𝙚? 𝙊𝙧 𝙞𝙨 𝙞𝙩 𝙩𝙝𝙚 𝙜𝙖𝙢𝙚 𝙘𝙝𝙖𝙣𝙜𝙚𝙧 𝙮𝙤𝙪𝙧 𝙗𝙪𝙨𝙞𝙣𝙚𝙨𝙨 𝙣𝙚𝙚𝙙𝙨?
Everyone’s talking about AI but is anyone really using it to create real value?
Most companies want to leverage AI. Few know 𝗵𝗼𝘄.
✅ What exactly should you ask to find real AI opportunities?
✅ Which AI techniques actually fit your business?
✅ Is your data even ready for AI?
If you’re not sure, you’re not alone. This is a condensed version of the slides I presented at a Linkedin webinar for Tecnovy on 28.04.2025.
Semantic Cultivators : The Critical Future Role to Enable AIartmondano
By 2026, AI agents will consume 10x more enterprise data than humans, but with none of the contextual understanding that prevents catastrophic misinterpretations.
Mobile App Development Company in Saudi ArabiaSteve Jonas
EmizenTech is a globally recognized software development company, proudly serving businesses since 2013. With over 11+ years of industry experience and a team of 200+ skilled professionals, we have successfully delivered 1200+ projects across various sectors. As a leading Mobile App Development Company In Saudi Arabia we offer end-to-end solutions for iOS, Android, and cross-platform applications. Our apps are known for their user-friendly interfaces, scalability, high performance, and strong security features. We tailor each mobile application to meet the unique needs of different industries, ensuring a seamless user experience. EmizenTech is committed to turning your vision into a powerful digital product that drives growth, innovation, and long-term success in the competitive mobile landscape of Saudi Arabia.
Big Data Analytics Quick Research Guide by Arthur MorganArthur Morgan
This is a Quick Research Guide (QRG).
QRGs include the following:
- A brief, high-level overview of the QRG topic.
- A milestone timeline for the QRG topic.
- Links to various free online resource materials to provide a deeper dive into the QRG topic.
- Conclusion and a recommendation for at least two books available in the SJPL system on the QRG topic.
QRGs planned for the series:
- Artificial Intelligence QRG
- Quantum Computing QRG
- Big Data Analytics QRG
- Spacecraft Guidance, Navigation & Control QRG (coming 2026)
- UK Home Computing & The Birth of ARM QRG (coming 2027)
Any questions or comments?
- Please contact Arthur Morgan at [email protected].
100% human made.
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...SOFTTECHHUB
I started my online journey with several hosting services before stumbling upon Ai EngineHost. At first, the idea of paying one fee and getting lifetime access seemed too good to pass up. The platform is built on reliable US-based servers, ensuring your projects run at high speeds and remain safe. Let me take you step by step through its benefits and features as I explain why this hosting solution is a perfect fit for digital entrepreneurs.
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfSoftware Company
Explore the benefits and features of advanced logistics management software for businesses in Riyadh. This guide delves into the latest technologies, from real-time tracking and route optimization to warehouse management and inventory control, helping businesses streamline their logistics operations and reduce costs. Learn how implementing the right software solution can enhance efficiency, improve customer satisfaction, and provide a competitive edge in the growing logistics sector of Riyadh.
Generative Artificial Intelligence (GenAI) in BusinessDr. Tathagat Varma
My talk for the Indian School of Business (ISB) Emerging Leaders Program Cohort 9. In this talk, I discussed key issues around adoption of GenAI in business - benefits, opportunities and limitations. I also discussed how my research on Theory of Cognitive Chasms helps address some of these issues
What is Model Context Protocol(MCP) - The new technology for communication bw...Vishnu Singh Chundawat
The MCP (Model Context Protocol) is a framework designed to manage context and interaction within complex systems. This SlideShare presentation will provide a detailed overview of the MCP Model, its applications, and how it plays a crucial role in improving communication and decision-making in distributed systems. We will explore the key concepts behind the protocol, including the importance of context, data management, and how this model enhances system adaptability and responsiveness. Ideal for software developers, system architects, and IT professionals, this presentation will offer valuable insights into how the MCP Model can streamline workflows, improve efficiency, and create more intuitive systems for a wide range of use cases.
What is Model Context Protocol(MCP) - The new technology for communication bw...Vishnu Singh Chundawat
Enterprise Level Application Architecture with Web APIs using Entity Framework, Generic Repository Pattern and Unit of Work
1. RESTful Day #1: Enterprise level application
architecture with Web API’s using Entity
Framework, Generic Repository pattern and
Unit of Work. –by Akhil Mittal
Table of Contents
Introduction:_____________________________________________________________________________ 1
Roadmap: _______________________________________________________________________________ 3
REST: ___________________________________________________________________________________ 4
Setup database: __________________________________________________________________________ 4
Web API project:__________________________________________________________________________ 5
Setup Data Access Layer: ___________________________________________________________________ 8
Generic Repository and Unit of Work:________________________________________________________ 18
Unit of Work : ___________________________________________________________________________ 22
Setup Business Entities :___________________________________________________________________ 26
Product entity : ________________________________________________________________________________27
Token entity :__________________________________________________________________________________27
User entity : ___________________________________________________________________________________27
Setup Business Services Project: ____________________________________________________________ 28
Setup WebAPI project: ____________________________________________________________________ 35
Running the Application: __________________________________________________________________ 40
Design Flaws____________________________________________________________________________ 45
Conclusion______________________________________________________________________________ 45
Introduction:
I have been practicing, reading a lot about RESTful services for past few days. To my surprise I could not find a
complete series of practical implementations of ASP.NET Web API’s on the web. My effort in this series will be
to focus on how we can develop basic enterprise level application architecture with Web API’s.
2. The complete series will be in a way that focuses on less theory and more practical scenarios to understand
how RESTful services can be created using an ORM (Object-relational mapping), I choose Entity Framework
here.
My first article in the series is to set up a basic architecture of REST service based application using Asp.net
MVC.In this article I'll explain how to expose pure REST (Representational State Transfer) endpoints of the
service that could be consumed by any client which wishes to use REST services. I’ll explain the
implementation of Entity Framework in conjunction with Repository Pattern and Unit of Work. I’ll also focus
on how to create a generic repository for all the entities that may come up as the application expands, in short
it should be quite scalable and extensible.
Second article in the series talks about loosely coupled architecture. This article throws some light on how we
can achieve a loosely coupled architecture in Asp.Net WebAPI’s using UnityContainer and Bootstrapper. I’ll try
to implement Dependency Injection to achieve same.
My third article is about overcoming the flaws of UnityContainer. It explain how we can leverage MEF
(Managed Extensibility Framework) to resolve the dependencies at runtime using IOC(Inversion of Control).
Unlike other web services, Asp.net WebAPI supports attribute based routing techniques .The fourth day of the
series explains how we can get multiple endpoints of a WebAPI using Attribute Routing and also overcome of
the traditional shortcomings of REST based services.
Security is always a concern in Enterprise level applications, Day #5 of the articles series explains how one can
implement a custom token based authentication technique to make the API’s more secure.
Sixth part of the article will explain the implementation of a centralized approach of logging and exception
handling with the help of Action Filters and Exception filters. It teaches how to implement nLog in conjunction
with Filters.
Developing an enterprise level infrastructure without Unit tests is worth not developing it. Day #7 teaches
how to leverage nUnit to accomplish this task of Unit Testing in WebAPIs. I’ll take live practical examples to do
so in the seventh day of the article.
Day #8 of the series teaches the new emerging concept of OData. It teaches on how one can request a service
with custom needs and requirements, on how one can implement OData support to WebAPIs.
4. My road for the series is as follows,
RESTful Day #1: Enterprise level application architecture with Web API’s using Entity Framework, Generic
Repository pattern and Unit of Work.
RESTful Day #2: Inversion of control using dependency injection in Web API's using Unity Container and
Bootstrapper.
RESTful Day #3: Resolving dependency of dependencies with dependency injection in Web API's using Unity
Container and Managed Extensibility Framework (MEF).
RESTful Day #4: Custom URL re-writing with the help of Attribute routing in MVC 4 Web API's.
RESTful Day #5: Token based custom authorization in Web API’s using Action Filters.
RESTful Day #6: Request logging and Exception handing/logging in Web API’s using Action Filters, Exception
Filters and nLog.
RESTful Day #7: Unit testing Asp.Net Web API's controllers using nUnit.
RESTful Day #8: Extending OData support in Asp.Net Web API's.
I’ll purposely use Visual Studio 2010 and .net Framework 4.0 because there are few implementations that are
very hard to find in .Net Framework 4.0, but I’ll make it easy by showing how we can do it.
REST:
Here is an extract from Wikipedia,
“Unlike SOAP-based web services, there is no "official" standard for RESTful web APIs. This is because REST is an
architectural style, while SOAP is a protocol. Even though REST is not a standard per se, most RESTful implementations
make use of standards such as HTTP, URI, JSON, and XML.”
I agree to it. Let’s do some coding.
Setup database:
I am using Sql Server 2008 as a database server. I have provided the sql scripts to create the database in Sql
Server, you can use the same to create one. I have given WebApiDb as my database name.My database
contains three tables for now, Products, Tokens, User. In this tutorial we’ll only be dealing with product table
to perform CURD operations using Web API and Entity framework.We’ll use Tokens and User in my upcoming
article. For those who fail to create database through scripts, here is the structure you can follow,
5. Web API project:
Open your Visual studio , I am using VS 2010, You can use VS version 2010 or above.
Step 1: Create a new Project in your visual studio,
6. Step 2: There after choose to create Asp.net MVC 4 Web application, and give it a name of your choice, I gave
it WebAPI.
7. Step 3: Out of different type of project templates shown to you, choose Web API project,
Once done, you’ll get a project structure like shown below, with a default Home and Values controller.
You can choose to delete this ValuesController , as we’ll be using our own controller to learn.
8. Setup Data Access Layer:
Let’s setup or data access layer first. We’ll be using Entity Framework 5.0 to talk to database. We’ll use
Generic Repository Pattern and Unit of work pattern to standardize our layer.
Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables
developers to work with relational data as domain-specific objects, eliminating the need for most of the data
access plumbing code that developers usually need to write. Using the Entity Framework, developers issue
queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM
implementation provides services like change tracking, identity resolution, lazy loading, and query translation
so that developers can focus on their application-specific business logic rather than the data access
fundamentals.”
In simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement
to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing and
storing the data in the database.
Step 1 : Create a new class library in your visual studio, and name it DataModel as shown below,
9. Step2: In the same way, create one more project i.e. again a class library and call it BusinessEntities,
I’ll explain the use of this class library soon.
Step 3: Move on to your DataModel project, right click on it and add a new item, in the list shown, choose
ADO.net Data Model, and name it WebApiDataModel.edmx.
10. The file .edmx will contain the databse information of our database that we created earlier, let’s set up this.
You’ll be presented a wizard like follows,
11. Choose, generate from database. Choose Microsoft SQl Server like shown in the following image,
Click continue, then provide the credentials of your database, i.e. WebAPIdb, and connect it,
12. You’ll get a screen, showing the connection string of the database we chose,
Provide the name of the connection string as WebApiDbEntities and click Next.
13. Choose all the database objects, check all the check boxes, and provide a name for the model. I gave it a name
WebApiDbModel.
Once you finish this wizard, you’ll get the schema ready in your datamodel project as follows,
14. We’ve got our schema in-place using Entity framework. But few work is still remaining. We need our data
context class and entities through which we’ll communicate with database.
So, moving on to next step.
Step 3 : Click on tools in Visual studio and open Extension manager. We need to get db context generator for
our datamodel.We can also do it using default code generation item by right clicking in the edmx view and add
code generation item, but that will generate object context class and that is heavier than db context. I want
light weighted db context class to be created, so we’ll use extension manager to add a package and then
create a db context class.
Search for Entity Framework Db context generator in online galary and select the one for EF 5.x like below,
15. I guess you need to restart Visual studio to get that into your templates.
Step 4 : Now right click in the .edmx file schema designer and choose “Add Code Generation Item..”.
16. Step 5 : Now you’ll see that we have got the template for the extension that we added, select that EF 5.x
DbContext Generator and click Add.
After adding this we’ll get the db context class and its properties, this class is responsible for all database
transactions that we need to perform, so our structure looks like as shown below,
17. Wow, we ended up in errors. But we got our db context class and our entity models, You can see them in our
DataModel project. Errors ? Nothing to worry about , it’s just we did not reference entity framework in our
project.We’ll do it right away.
Step 6 : Go to Tools -> Library Packet Manager->Packet manager Console.
You’ll get the console in left bottom of Visual studio.
18. Select dataModel project and write a command “Install-Package EntityFramework –Version 5.0.0” to install
Entity Framework 5 in our DataModel project.
Press enter. And all the errors get resolved.
Generic Repository and Unit of Work:
You can read about repository pattern and creating a repository in detail from my article
http://www.codeproject.com/Articles/631668/Learning-MVC-Part-Repository-Pattern-in-MVC-App.
Just to list down the benefits of Repository pattern,
It centralizes the data logic or Web service access logic.
It provides a substitution point for the unit tests.
It provides a flexible architecture that can be adapted as the overall design of the application evolves.
We’ll create a generic repository that works for all our entities. Creating repositories for each and every entity
may result in lots of duplicate code in large projects. For creating Generic Repository you can follow :
http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in
19. Step 1: Add a folder named GenericRepository in DataModel project and to that folder add a class named
Generic Repository. Add following code to that class, that servers as a template based generic code for all the
entities that will interact with databse,
#region Using Namespaces...
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
#endregion
namespace DataModel.GenericRepository
{
/// <summary>
/// Generic Repository class for Entity Operations
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class GenericRepository<TEntity> where TEntity : class
{
#region Private member variables...
internal WebApiDbEntities Context;
internal DbSet<TEntity> DbSet;
#endregion
#region Public Constructor...
/// <summary>
/// Public Constructor,initializes privately declared local variables.
/// </summary>
/// <param name="context"></param>
public GenericRepository(WebApiDbEntities context)
{
this.Context = context;
this.DbSet = context.Set<TEntity>();
}
#endregion
#region Public member methods...
/// <summary>
/// generic Get method for Entities
/// </summary>
/// <returns></returns>
public virtual IEnumerable<TEntity> Get()
{
IQueryable<TEntity> query = DbSet;
return query.ToList();
}
/// <summary>
/// Generic get method on the basis of id for Entities.
/// </summary>
/// <param name="id"></param>
20. /// <returns></returns>
public virtual TEntity GetByID(object id)
{
return DbSet.Find(id);
}
/// <summary>
/// generic Insert method for the entities
/// </summary>
/// <param name="entity"></param>
public virtual void Insert(TEntity entity)
{
DbSet.Add(entity);
}
/// <summary>
/// Generic Delete method for the entities
/// </summary>
/// <param name="id"></param>
public virtual void Delete(object id)
{
TEntity entityToDelete = DbSet.Find(id);
Delete(entityToDelete);
}
/// <summary>
/// Generic Delete method for the entities
/// </summary>
/// <param name="entityToDelete"></param>
public virtual void Delete(TEntity entityToDelete)
{
if (Context.Entry(entityToDelete).State == EntityState.Detached)
{
DbSet.Attach(entityToDelete);
}
DbSet.Remove(entityToDelete);
}
/// <summary>
/// Generic update method for the entities
/// </summary>
/// <param name="entityToUpdate"></param>
public virtual void Update(TEntity entityToUpdate)
{
DbSet.Attach(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
}
/// <summary>
/// generic method to get many record on the basis of a condition.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual IEnumerable<TEntity> GetMany(Func<TEntity, bool> where)
{
return DbSet.Where(where).ToList();
21. }
/// <summary>
/// generic method to get many record on the basis of a condition but query able.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity, bool> where)
{
return DbSet.Where(where).AsQueryable();
}
/// <summary>
/// generic get method , fetches data for the entities on the basis of condition.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public TEntity Get(Func<TEntity, Boolean> where)
{
return DbSet.Where(where).FirstOrDefault<TEntity>();
}
/// <summary>
/// generic delete method , deletes data for the entities on the basis of condition.
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public void Delete(Func<TEntity, Boolean> where)
{
IQueryable<TEntity> objects = DbSet.Where<TEntity>(where).AsQueryable();
foreach (TEntity obj in objects)
DbSet.Remove(obj);
}
/// <summary>
/// generic method to fetch all the records from db
/// </summary>
/// <returns></returns>
public virtual IEnumerable<TEntity> GetAll()
{
return DbSet.ToList();
}
/// <summary>
/// Inclue multiple
/// </summary>
/// <param name="predicate"></param>
/// <param name="include"></param>
/// <returns></returns>
public IQueryable<TEntity>
GetWithInclude(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate, params
string[] include)
{
IQueryable<TEntity> query = this.DbSet;
query = include.Aggregate(query, (current, inc) => current.Include(inc));
return query.Where(predicate);
22. }
/// <summary>
/// Generic method to check if entity exists
/// </summary>
/// <param name="primaryKey"></param>
/// <returns></returns>
public bool Exists(object primaryKey)
{
return DbSet.Find(primaryKey) != null;
}
/// <summary>
/// Gets a single record by the specified criteria (usually the unique identifier)
/// </summary>
/// <param name="predicate">Criteria to match on</param>
/// <returns>A single record that matches the specified criteria</returns>
public TEntity GetSingle(Func<TEntity, bool> predicate)
{
return DbSet.Single<TEntity>(predicate);
}
/// <summary>
/// The first record matching the specified criteria
/// </summary>
/// <param name="predicate">Criteria to match on</param>
/// <returns>A single record containing the first record matching the specified
criteria</returns>
public TEntity GetFirst(Func<TEntity, bool> predicate)
{
return DbSet.First<TEntity>(predicate);
}
#endregion
}
}
Unit of Work :
Again I’ll not explain in detail what Unit of Work is. You can google about the theory or follow my existing
article on MVC with Unit of Work.
To give a heads up, again from my existing article, the important responsibilities of Unit of Work are,
To manage transactions.
To order the database inserts, deletes, and updates.
To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code
may mark the same Invoice object as changed, but the Unit of Work class will only issue a single
UPDATE command to the database.
23. The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can
otherwise concentrate on business logic.
Step 1: Create a folder named UnitOfWork, add a class to that folder named UnitOfWork.cs,
Add GenericRepository properties for all the three entities that we got. The class also implements IDisposable
interface and it’s method Dispose to free up connections and objects. The class will be as follows,
#region Using Namespaces...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity.Validation;
using DataModel.GenericRepository;
#endregion
namespace DataModel.UnitOfWork
{
/// <summary>
/// Unit of Work class responsible for DB transactions
/// </summary>
public class UnitOfWork : IDisposable
{
#region Private member variables...
private WebApiDbEntities _context = null;
private GenericRepository<User> _userRepository;
private GenericRepository<Product> _productRepository;
private GenericRepository<Token> _tokenRepository;
#endregion
public UnitOfWork()
{
_context = new WebApiDbEntities();
}
#region Public Repository Creation properties...
/// <summary>
/// Get/Set Property for product repository.
/// </summary>
public GenericRepository<Product> ProductRepository
{
get
{
if (this._productRepository == null)
this._productRepository = new GenericRepository<Product>(_context);
return _productRepository;
}
}
/// <summary>
24. /// Get/Set Property for user repository.
/// </summary>
public GenericRepository<User> UserRepository
{
get
{
if (this._userRepository == null)
this._userRepository = new GenericRepository<User>(_context);
return _userRepository;
}
}
/// <summary>
/// Get/Set Property for token repository.
/// </summary>
public GenericRepository<Token> TokenRepository
{
get
{
if (this._tokenRepository == null)
this._tokenRepository = new GenericRepository<Token>(_context);
return _tokenRepository;
}
}
#endregion
#region Public member methods...
/// <summary>
/// Save method.
/// </summary>
public void Save()
{
try
{
_context.SaveChanges();
}
catch (DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format("{0}: Entity of type "{1}" in state
"{2}" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name,
eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format("- Property: "{0}", Error: "{1}"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(@"C:errors.txt", outputLines);
throw e;
}
25. }
#endregion
#region Implementing IDiosposable...
#region private dispose variable declaration...
private bool disposed = false;
#endregion
/// <summary>
/// Protected Virtual Dispose method
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
Debug.WriteLine("UnitOfWork is being disposed");
_context.Dispose();
}
}
this.disposed = true;
}
/// <summary>
/// Dispose method
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
Now we have completely set up our data access layer, and our project structure looks like as shown below,
26. Setup Business Entities:
Remember, we created a business entities project. You may wonder, we already have database entities to
interact with database then why do we need Business Entities?. The answer is as simple as that, we are trying
to follow a proper structure of communication, and one would never want to expose the database entities to
the end client, in our case is Web API, it involves lot of risk.Hackers may manipulate the details and get
accessto your database.Instead we’ll use database entities in our business logic layer and use Business Entities
as transfer objects to communicate between business logic and Web API project.So business entities may have
different names but, their properties remains same as database entities. In our case we’ll add same name
business entity classes appendint word “Entity” to them in our BusinessEntity project. So we’ll end up having
three classes as follows,
27. Product entity :
public class ProductEntity
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
Token entity :
public class TokenEntity
{
public int TokenId { get; set; }
public int UserId { get; set; }
public string AuthToken { get; set; }
public System.DateTime IssuedOn { get; set; }
public System.DateTime ExpiresOn { get; set; }
}
User entity :
public class UserEntity
{
public int UserId { get; set; }
28. public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
Setup Business Services Project:
Add a new class library to the solution named BusinessServices. This layer will act as our business logic layer.
Note that, we can make use of our API controllers to write business logic, but I am trying to segregate my
business logic in an extra layer so that if in future I want to use WCF,MVC, Asp.net Web Pages or any other
application as my presentation layer then I can easily integrate my Business logic layer in it.
We’ll make this layer testable, so we need to create an interface in and declare CURD operations that we need
to perform over product table.Before we proceed, add the reference of BusinessEntities project and
DataModel project to this newly created project
Step 1: Create an interface named IProductServices and add following code to it for CURD operations
methods,
using System.Collections.Generic;
using BusinessEntities;
namespace BusinessServices
{
/// <summary>
/// Product Service Contract
/// </summary>
public interface IProductServices
{
ProductEntity GetProductById(int productId);
IEnumerable<ProductEntity> GetAllProducts();
int CreateProduct(ProductEntity productEntity);
bool UpdateProduct(int productId,ProductEntity productEntity);
bool DeleteProduct(int productId);
}
}
Step 2 : Create a class to implement this interface.name that class ProductServices,
The class contains a private variable of UnitOfWork and a constructor to initialize that variable,
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public ProductServices()
{
_unitOfWork = new UnitOfWork();
}
29. We have decided not to expose our db entities to Web API project, so we need something to map the db
entities data to my business entity classes. We’ll make use of AutoMapper.You can read about AutoMapper in
my this article.
Step 3: Just right click project-> Extension manager, search for AutoMapper in online galary and add to
BusinessServices project,
Step 4: Implement methods in ProductServices class ,
Add following code to the class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;
namespace BusinessServices
{
/// <summary>
/// Offers services for product specific CRUD operations
/// </summary>
public class ProductServices:IProductServices
{
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public ProductServices()
30. {
_unitOfWork = new UnitOfWork();
}
/// <summary>
/// Fetches product details by id
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public BusinessEntities.ProductEntity GetProductById(int productId)
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
Mapper.CreateMap<Product, ProductEntity>();
var productModel = Mapper.Map<Product, ProductEntity>(product);
return productModel;
}
return null;
}
/// <summary>
/// Fetches all the products.
/// </summary>
/// <returns></returns>
public IEnumerable<BusinessEntities.ProductEntity> GetAllProducts()
{
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
{
Mapper.CreateMap<Product, ProductEntity>();
var productsModel = Mapper.Map<List<Product>, List<ProductEntity>>(products);
return productsModel;
}
return null;
}
/// <summary>
/// Creates a product
/// </summary>
/// <param name="productEntity"></param>
/// <returns></returns>
public int CreateProduct(BusinessEntities.ProductEntity productEntity)
{
using (var scope = new TransactionScope())
{
var product = new Product
{
ProductName = productEntity.ProductName
};
_unitOfWork.ProductRepository.Insert(product);
_unitOfWork.Save();
scope.Complete();
return product.ProductId;
}
}
31. /// <summary>
/// Updates a product
/// </summary>
/// <param name="productId"></param>
/// <param name="productEntity"></param>
/// <returns></returns>
public bool UpdateProduct(int productId, BusinessEntities.ProductEntity
productEntity)
{
var success = false;
if (productEntity != null)
{
using (var scope = new TransactionScope())
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
product.ProductName = productEntity.ProductName;
_unitOfWork.ProductRepository.Update(product);
_unitOfWork.Save();
scope.Complete();
success = true;
}
}
}
return success;
}
/// <summary>
/// Deletes a particular product
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public bool DeleteProduct(int productId)
{
var success = false;
if (productId > 0)
{
using (var scope = new TransactionScope())
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
_unitOfWork.ProductRepository.Delete(product);
_unitOfWork.Save();
scope.Complete();
success = true;
}
}
}
return success;
}
}
}
32. Let me explain the idea of the code. We have 5 methods as follows,
1. To get product by id ( GetproductById ) : We call repository to get the product by id. Id comes as a
parameter from the calling method to that service method. It returns the product entity from the
database.Note that it will not return the exact db entity, instead we’ll map it with our business entity
using AutoMapper and return it to calling method.
/// <summary>
/// Fetches product details by id
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public BusinessEntities.ProductEntity GetProductById(int productId)
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
Mapper.CreateMap<Product, ProductEntity>();
var productModel = Mapper.Map<Product, ProductEntity>(product);
return productModel;
}
return null;
}
2. Get all products from database (GetAllProducts) : This method returns all the products residing in
database, again we make use of AutoMapper to map the list and return back.
/// <summary>
/// Fetches all the products.
/// </summary>
/// <returns></returns>
public IEnumerable<BusinessEntities.ProductEntity> GetAllProducts()
{
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
{
Mapper.CreateMap<Product, ProductEntity>();
var productsModel = Mapper.Map<List<Product>, List<ProductEntity>>(products);
return productsModel;
}
return null;
}
3. Create a new product (CreateProduct) : This method takes product BusinessEntity as an argument and
creates a new object of actual database entity and insert it using unit of work.
/// <summary>
/// Creates a product
/// </summary>
/// <param name="productEntity"></param>
/// <returns></returns>
public int CreateProduct(BusinessEntities.ProductEntity productEntity)
{
33. using (var scope = new TransactionScope())
{
var product = new Product
{
ProductName = productEntity.ProductName
};
_unitOfWork.ProductRepository.Insert(product);
_unitOfWork.Save();
scope.Complete();
return product.ProductId;
}
}
I guess you can now write update and delete methods. So I am writing the code of complete class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;
namespace BusinessServices
{
/// <summary>
/// Offers services for product specific CRUD operations
/// </summary>
public class ProductServices:IProductServices
{
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public ProductServices()
{
_unitOfWork = new UnitOfWork();
}
/// <summary>
/// Fetches product details by id
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public BusinessEntities.ProductEntity GetProductById(int productId)
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
Mapper.CreateMap<Product, ProductEntity>();
var productModel = Mapper.Map<Product, ProductEntity>(product);
return productModel;
}
return null;
34. }
/// <summary>
/// Fetches all the products.
/// </summary>
/// <returns></returns>
public IEnumerable<BusinessEntities.ProductEntity> GetAllProducts()
{
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
{
Mapper.CreateMap<Product, ProductEntity>();
var productsModel = Mapper.Map<List<Product>, List<ProductEntity>>(products);
return productsModel;
}
return null;
}
/// <summary>
/// Creates a product
/// </summary>
/// <param name="productEntity"></param>
/// <returns></returns>
public int CreateProduct(BusinessEntities.ProductEntity productEntity)
{
using (var scope = new TransactionScope())
{
var product = new Product
{
ProductName = productEntity.ProductName
};
_unitOfWork.ProductRepository.Insert(product);
_unitOfWork.Save();
scope.Complete();
return product.ProductId;
}
}
/// <summary>
/// Updates a product
/// </summary>
/// <param name="productId"></param>
/// <param name="productEntity"></param>
/// <returns></returns>
public bool UpdateProduct(int productId, BusinessEntities.ProductEntity
productEntity)
{
var success = false;
if (productEntity != null)
{
using (var scope = new TransactionScope())
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
product.ProductName = productEntity.ProductName;
35. _unitOfWork.ProductRepository.Update(product);
_unitOfWork.Save();
scope.Complete();
success = true;
}
}
}
return success;
}
/// <summary>
/// Deletes a particular product
/// </summary>
/// <param name="productId"></param>
/// <returns></returns>
public bool DeleteProduct(int productId)
{
var success = false;
if (productId > 0)
{
using (var scope = new TransactionScope())
{
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
{
_unitOfWork.ProductRepository.Delete(product);
_unitOfWork.Save();
scope.Complete();
success = true;
}
}
}
return success;
}
}
}
Job done at business service level.Let’s move on to API controller to call these methods.
Setup WebAPI project:
Step1 :
Just add the reference of BusinessEntity and BusinessService in the WebAPI project, our architecture becomes
like this,
36. Step 2: Add a new WebAPI controller in Controller folder.Right click Controller folder and add a new controller.
37. We get a controller as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApi.Controllers
{
public class ProductController : ApiController
{
// GET api/product
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/product/5
public string Get(int id)
{
return "value";
}
// POST api/product
public void Post([FromBody]string value)
{
}
// PUT api/product/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/product/5
public void Delete(int id)
{
}
}
}
We get HTTP VERBS as method names. Web API is smart enough to recognize request with the name of the
VERB itself. In our case we are doing CRUD operations, so we don’t need to change the names of the method,
we just needed this . We only have to write calling logic inside these methods. In my upcoming articles of the
series, we will figure out how we can define new routes and provide method names of our choice with those
routes.
Step 3: Add logic to call Business Service methods, just make an object of Business Service and call its
respective methods, our Controller class becomes like,
using System.Collections.Generic;
using System.Linq;
using System.Net;
38. using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;
namespace WebApi.Controllers
{
public class ProductController : ApiController
{
private readonly IProductServices _productServices;
#region Public Constructor
/// <summary>
/// Public constructor to initialize product service instance
/// </summary>
public ProductController()
{
_productServices =new ProductServices();
}
#endregion
// GET api/product
public HttpResponseMessage Get()
{
var products = _productServices.GetAllProducts();
var productEntities = products as List<ProductEntity> ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not
found");
}
// GET api/product/5
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for
this id");
}
// POST api/product
public int Post([FromBody] ProductEntity productEntity)
{
return _productServices.CreateProduct(productEntity);
}
// PUT api/product/5
public bool Put(int id, [FromBody]ProductEntity productEntity)
{
if (id > 0)
{
39. return _productServices.UpdateProduct(id, productEntity);
}
return false;
}
// DELETE api/product/5
public bool Delete(int id)
{
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
}
}
}
Just run the application, we get,
But now how do we test our API? We don’t have client. Guys, we’ll not be writing a client now to test it.We’ll
add a package that will do all our work.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox
in online packages,
40. You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas->
HelpPage like shown below,
Running the Application:
Before running the application, I have put some test data in our product table.
Just hit F5, you get the same page as you got earlier, just append “/help” in its url, and you’ll get the test
client,
41. You can test each service by clicking on it.
Service for GetAllProduct,
42. For Create a new product,
In database, we get new product,
Update product:
45. Design Flaws
1. Architecture is tightly coupled. IOC (Inversion of Control) needs to be there.
2. We cannot define our own routes.
3. No exception handling and logging.
4. No unit tests.
Conclusion
We now know how to create a WebAPI and perform CRUD operations using n layered architecture.
But still there are some flaws in this design.In my next two articles I’ll explain how to make the system loosely
coupled using Dependency Injection Principle. We’ll also cover all the design flaws to make our design better
and stronger. Till then Happy Coding You can also download the source code from GitHub.
About Author
Akhil Mittal works as a Sr. Analyst in Magic Software and have an experience of more than 8 years in C#.Net. He is a
codeproject and a c-sharpcorner MVP (Most Valuable Professional). Akhil is a B.Tech (Bachelor of Technology) in
Computer Science and holds a diploma in Information Security and Application Development from CDAC. His work
experience includes Development of Enterprise Applications using C#, .Net and Sql Server, Analysis as well as Research
and Development. His expertise is in web application development. He is a MCP (Microsoft Certified Professional) in
Web Applications (MCTS-70-528, MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536).