Multiple URL Stress

Tool hoox trợ test tải server và website, nó cho phép bạn test nhiều URL cùng lúc.

Introduction

Multiple URL Stress is a tool to test the performance of servers and websites, allowing you to test multiple URLs at the same time.

It sets the number of requests for each of the sites, and few threads used, so the number of requests is multiplied by the number of configured threads.

It also has the ability to configure authentication and proxy server for your connection.

Using the Code

Browse the list of charged sites and initiates the configured number of threads for each.

foreach (string url in listBoxUrls.Items)
{
    for (int i = 1; i <= Settings.CountThreads; i++)
    {
        Thread workerThread = new Thread(() => WorkerThreadProc(url));
        workerThread.Start();
    }
}

The WorkerThreadProc method is responsible for conducting and requests to sites.

Interlocked.Increment allows increased variable that is located in the main thread to reflect the partial results in the user view.

public void WorkerThreadProc(string url)
{
    Interlocked.Increment(ref numWorkItems);
    int tries = 0;
    while ((!_shouldStop) && ((tries < Settings.CountRequest || (Settings.isforever))))
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = true;
        try
        {
            request.Method = "GET";
            
            if (Settings.autenticate)
            {
                var cache = new CredentialCache();
                cache.Add(new Uri(url), "Basic", 
                new NetworkCredential(Settings.authUser, Settings.authPass));
                request.Credentials = cache;
            }
            
            if (Settings.proxy)
            {
                WebProxy myproxy = new WebProxy(Settings.proxyHost, Settings.proxyPort);
                if (Settings.proxyUser != "")
                    myproxy.Credentials = 
                    new NetworkCredential(Settings.proxyUser, Settings.proxyPass);
                request.Proxy = myproxy;
            }
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            
            if (response.StatusCode == HttpStatusCode.OK) 
            		Interlocked.Increment(ref count200);
            if (response.StatusCode == HttpStatusCode.Unauthorized) 
            		Interlocked.Increment(ref count401);
            if (response.StatusCode == HttpStatusCode.NotFound) 
            		Interlocked.Increment(ref count404);
            if (response.StatusCode == HttpStatusCode.NotModified) 
            		Interlocked.Increment(ref count304);
            response.Close();
        }
        catch
        {
            Interlocked.Increment(ref countFailures);
        }
        
        tries++;
        Interlocked.Increment(ref requests);
        Interlocked.Increment(ref requestsLastSec);
    }
    Interlocked.Decrement(ref numWorkItems);
}

LINK: http://www.codeproject.com/Tips/1042236/Multiple-URL-Stress

SQL Prompt Review

I love tools that save me and my team time which ultimately translates to saving money for my employer and I’ll proceed to show you how SQL Prompt can do that for you .

Editorial Note

This article appears in the Third Party Product Reviews section. Articles in this section are for the members only and must not be used by tool vendors to promote or advertise products in any way, shape or form. Please report any spam or advertising.

What I Do

I work as a lead information architect on a large government health care services integration project and you might say I live in SQL Server Management Studio (SSMS) and Visual Studio (VS) during my work hours. I’m also a fan of Redgate’s tools and today I’d like to share some of the love I have for SQL Prompt. I love tools that save me and my team time which ultimately translates to saving money for my employer and I’ll proceed to show you how SQL Prompt can do that for you.

What SQL Prompt Can Do For You

I’m working with version 7 of SQL Prompt which can be downloaded for a free 28 day trial here: http://www.red-gate.com/products/sql-development/sql-prompt/

Major features provided by SQL Prompt are:

  • IntelliSense-style code completion
  • Customizable code formatting
  • Code snippet library
  • Refactor SQL code
  • SSMS tab history
  • SSMS tab coloring

IntelliSense and Formatting

Let’s begin with IntelliSense. This feature is a vast improvement over the out of the box experience you get with SSMS and VS. As you can see in the figure below, there is adequately more information present in the SQL Prompt pop ups.

I love the way suggestions work, and you can filter that behavior using the drop down list at the bottom of the first popup in the figure above. I started the example query using the * wild card for columns so I could show you one of my favorite features. Placing the cursor at the end of the * allows you to hit tab and expand the column list as seen below:

From there, I can easily edit the column list and save tons of time when dealing with tables that have a large number of columns often used in queries. While we’re working with this query, I also want to show you how easily you can change the format. Just highlight the SQL and right click to make your query look great!

Properly formatted SQL is easier to maintain, and SQL Prompt allows you to have a lot of control over how you prefer the formatting to work.

Snippets

SSMS has supported templates for several versions that allow you to reuse boilerplate scripts to easily create objects in your databases. SQL Prompt takes this concept further by implementing the code snippet library. They are many snippets already built into SQL Prompt and activating a snippet is as easy as typing the snippet definition like “st100” to select the top 100 rows from a table as shown below:

It’s easy to highlight an existing query and turn it into a snippet using placeholders. Built in placeholders are reserved words that are variables for specific pieces of information or they represent actions that can be applied to your snippet. To get a feel for how they are structured, simply open up the snippet manager and look over the definitions of existing snippets. You also have the ability to create custom placeholders which are basically free text fields. Alasdair Daw has a wonderful article here that examines the subtleties in this great feature:http://www.red-gate.com/blog/snippet-manager

The ability to create snippets is really useful for repetitive tasks, but before you reinvent the wheel, be sure to check out Gaurav Vohra’s repository of useful snippets on Git:

https://github.com/gvohra/sqlpromptsnippets

I mentioned SSMS templates earlier and want to note that you also have the ability to use those template parameters in SQL Prompt snippets. The nice folks at Redgate have an excellent walkthrough here:

http://documentation.red-gate.com/display/SP7/Using+SSMS+templates+in+SQL+Prompt+snippets

Refactoring

The ability to refactor code is one of the most valuable features of any toolset. I often find myself working on large legacy systems that employ poor, or in most cases, no naming conventions or consistent coding standards. I mentioned earlier when showing off the formatting features of SQL Prompt that well formatted code is easier to maintain thus leading to saving time and ultimately money.

SQL prompt has many amazing refactoring features starting with Smart Rename which allows you to right click and rename objects without breaking dependencies. This makes it easier to apply a naming standard to existing tables, views, stored procedures and functions along with their respective column names and parameters. You can also rename scripted variables.

I’ve long been a proponent of using stored procedures in my database projects, and SQL Prompt supports the ability to highlight any block of valid SQL and encapsulate it into a stored procedure.

The system I’m currently working on started with our team inheriting a legacy system. By using the aforementioned features, this allowed us to properly name and format the scripts and database objects in a timely fashion. We also had the opportunity to greatly improve the normalization of the database which required splitting several existing tables into two or more tables. SQL Prompt came to our rescue with support for that very action:

http://documentation.red-gate.com/display/SP7/Splitting+a+table

Tabs

Tab history (SQL 2008 or later) is a nice feature that stores the list of tabs you’ve opened and allows you to easily get back to them along with the ability to rename or delete them from the list. This may seem simple, but as I get older I sometimes forget where I parked at the mall so it is helpful for me to have that historical list handy.

I’ll wrap up my tour of SQL Prompt features with the new addition of colored tabs (SQL 2012 or later). This allows you to select different colors for tabs to represent different servers or database connections as shown in the figure below:

As you might imagine, this feature is a godsend when you have to work in different environments and need to stop the madness of running a script in the wrong environment. This is another simple feature that eliminates confusion with support for coloring at the database and server group levels and support for wildcard matches. You can read more about this great new feature here: https://documentation.red-gate.com/display/SP7/Coloring+query+tabs

Integration With Visual Studio

Just about all the great features we’ve looked at and more are also available in VS. As you can see from the figure below, SQL Prompt adds a menu entry in the VS development environment just like we have in SSMS as well as additional entries when you access a popup menu.

Conclusion

I’ve been using Redgate tools for over 10 years, and the Redgate team has done a fantastic job with SQL Prompt. The SQL Developer Bundle, which includes SQL Prompt, was one of the first tools I purchased for my team of database administrators and architects when I started my current project. I can honestly say the tools have saved us hundreds of man hours and paid for the purchase many times over.

You can read more about the return on investment with SQL Prompt in this excellent article: https://www.red-gate.com/assets/INTERIM/assets/products/sql-prompt/documents/sql-prompt-roi-guide.pdf. This product is free to try for 28 days. Just follow this link: http://www.red-gate.com/products/sql-development/sql-prompt/

LINK: http://www.codeproject.com/Articles/1039342/SQL-Prompt-Review

From No Factory to Factory Method

Introduction

When we hear the word Design Pattern, the first question that comes to our mind is, “What are Design Patterns?”
Design Patterns are reusable and documented solutions for recurring problems in software development.
Gang of four (GOF) have categorized Design Patterns into 3 categories

  • Creational
  • Structural
  • Behavioral

When I started to learn Design Pattern I found Factory method as a very intriguing pattern. It is one of the most controversial and confused Creational Pattern. There is a alot of confusion in People to understanding this pattern .
First of all let me make all of you clear there is nothing like Factory Pattern (as per GOF design pattern list), GOF has something called Factory Method Pattern. (We will come across with both the terminology later in this stage)

In this article for discussion and explanation purpose I am introducing to you, two fictional characters Alexander (a .NET developer) and Thomas (CEO of an IT institute called Programmer24X7).

Story begins on the day when Thomas contacts Alexander and asks him to take up role of architect in his in-house project called “Course Management System”. We will see how Alexander progresses his knowledge about Factory Method Pattern day by day and how finally he come up with a great solution.

Before you starts reading this article, a small advice from my side, keep some snacks ready besides you, because it’s going to be a weary 6 day story. Basically I am trying to play with your patience. Smile | <img src= don’t worry just kidding. It’s gonna be fun, you will enjoy reading this article and towards the end of this article you can proudly say “I know Factory Method Pattern”.

So relax and let’s start our journey to learn Factory Method Pattern

Index

Day 1

Alexander (our .NET developer) collects requirements from Thomas (our Programmer24X7 CEO). One of his primary requirements was to build a module which will manage online courses offered in the Programmer24X7 (technical institute).

How Alexander started?

I) The system Alexander is going to develop is Course Management System, so the first logical step was to start creating Course Library.

II) Next step will be creating instance of courses and building the UI – User Interface. Following is the most obvious code every programmer thinks about and even Alexander did the same.

Approach 1 – Without Factory Approach

AbstractCourse objCourse = null;
switch(StrUserInput)
{
    case "N":
    objCourse = new NetCourse();
    break;
    case "J":
    objCourse = new JavaCourse();
    break;
}
objCourse.CreateCourseMaterial();
objCourse.CreateSchedule();
//Display objCourse.CourseName and objCourse.CourseDuration

Final step – demonstration

Since module was ready, Alexander demonstrated the same to Thomas, and Thomas felt great about the architecture. Alexander’s efforts were well appreciated but, it all didn’t end there. He then took the requirement to next logical level where he shared his further plan with regards to the application. He said,

  • He is planning to add new online courses like C++, VC++ etc. and would like to stop few courses in future.
  • In future In Programmer24X7 offline courses are going to be conducted, so make sure to make everything reusable.

Thomas requested Alexander to make changes as per this advance scope. Well it came to Alexander as a Big Surprise

It was like out of the frying pan but into the fire situation for Alexander.

“Adding a new course means”, open the existing UI Code existing logic (add some more switch cases and in future remove some existing case.)

Consider a situation of builder, who is asked to add one more floor between 1st and 2nd floor after the building construction is over taking care that building doesn’t collapse.

Problem with the Approach 1

  • SOLID principle OCP (Open Closed Principle) will be violated when Course library modifies. (OCP says, software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification)
  • Reusing the same (Course creation) logic in another UI is not possible.

What Alexander learnt?

Alexander realized an important thing about software development and learnt a great lesson “Changes are integral part of development and system should developed in such a way that it can be easily adapted to such changes without modifying existing tested sections.”

Isn’t it funny, change the system but don’t change the code. Well let’s see how we can do that.

Move to Index

Day 2

How Alexander Proceeded?

Alexander woke up early morning next day. Coffee was in his hand but mind was still thinking about the problem in hand. It was very difficult for him to find the right star from dark sky but finally he managed to find the Moon and there came Approach 2.

  • Sky – My Brain
  • Stars – Thoughts
  • Moon – Solution for Course Library problem

 

Approach 2 – Simple Factory Approach

 

In the first approach UI was creating Course Objects.

Now how it will be if the power of object creation is taken away from UI and give it to someone else. Here someone else is called Simple Factory class.

What is Simple Factory?

Simple Factory is a class with a public static method which will actually do the object creation task according to the input it gets.

public class CourseFactory
{
    public static AbstractCourse CreateCourse(string ScheduleType)
    {
        AbstractCourse objCourse = null;
        switch(ScheduleType)
        {
            case "N":
            objCourse = new NetCourse();
            break;
            case "J":
            objCourse = new JavaCourse();
            break;
            //Add more case conditions here for VC++ and C++
        }
        objCourse.CreateCourseMaterial();
        objCourse.CreateSchedule();
        return objCourse;
    }
}

UI

AbstractCourse objCourse = CourseFactory.CreateCourse(StrUserInput);    
//Display objCourse.CourseName and objCourse.CourseDuration

Advantages of the Approach 2

  • Whenever new course will be introduced, the one which gets changed is factory not client code.
  • As Factory is class any one can use it who have access. In short Course logic now can be reused.

Final step – demonstration

Later in the evening Alexander reached Programmer24X7 office to demonstrate this revised architecture. But before Alexander started to express his anxiety, there came another surprising request. Thomas said, “I think, it’s better if we add one more UI for corporate schedule as well. Reason is that, Now-a-days my corporate training count has increased a lot, so it’s becoming impossible for me to manage.”

I) Now the very first thing we should do is, changing course library (because we need to add corporate courses as well).

II) Add some more case conditions to our Simple Factory class.

public class CourseFactory
{
    public static AbstractCourse CreateCourse(string ScheduleType)
    {
        AbstractCourse objCourse = null;
        switch(ScheduleType)
        {
            case "CN":
            objCourse = new CNetCourse();
            break;
            case "CJ":
            objCourse = new CJavaCourse();
            break; 
            case "CB":
            objCourse = new CBICourse();
            break; 
            case "OJ":
            objCourse = new OJavaCourse();
            break;
            case "ON":
            objCourse = new ONetCourse();
            break;
        }
        objCourse.CreateCourseMaterial();
        objCourse.CreateSchedule();
        return objCourse;
    }
}

Problem with the Approach 2

New requirements are easily covered using Simple Factory Approach, then what’s the matter?

  • All though all classes are derived from Abstract Course, adding five case conditions in a single Simple Factory violates SOLID Principle SRP – Single Responsibility Principle. (SRP says a class should have only one reason to change.)
    And here Factory class will be changed

    • Whenever new corporate course introduces or modified.
    • Whenever new online course introduces or modified.

So this Simple Factory solution will not workout in current problem context.

Move to Index

Day 3

Let’s list down all our requirements.

  • We need Factory for online Courses
  • We need Factory for corporate Courses
  • We don’t want to create single Factory for both modules.

 

 

  • How if use Multiple Simple Factories.
    1. OnlineCourseFactory
    2. CorporateCourseFactory

 

Approach 3 – Multiple Simple Factory Approach

 

In this approach we will have multiple simple factories each having a static method which will create an instance based on input it gets.

public class CorporateCourseFactory
{
    public static AbstractCourse CreateCourse(string ScheduleType)
    {
        AbstractCourse objCourse = null;
        switch(ScheduleType)
        {
            case "N":
            objCourse = new CNetCourse();
            break;
            case "J":
            objCourse = new CJavaCourse();
            break;
            case "B":
            objCourse = new CBICourse();
            break;
        }
        objCourse.CreateCourseMaterial();
        objCourse.CreateSchedule();
        return objCourse;
    }
}
public class OnlineCourseFactory
{
    public static AbstractCourse CreateCourse(string ScheduleType)
    {
        AbstractCourse objCourse = null;
        switch(ScheduleType)
        {
            case "N":
            objCourse = new ONetCourse();
            break;
            case "J":
            objCourse = new OJavaCourse();
            break;
        }
        objCourse.CreateCourseMaterial();
        objCourse.CreateSchedule();
        return objCourse;
    }
}

Online Course UI

AbstractCourse objCourse = OnlineCourseFactory.CreateCourse(StrUserInput);
//Display objCourse.CourseName and objCourse.CourseDuration

Corporate Course UI

AbstractCourse objCourse = CorporateCourseFactory.CreateCourse(StrUserInput);    
//Display objCourse.CourseName and objCourse.CourseDuration

Everything settled problem solved.

Move to Index

Day 4

Next day Alexander reached Programmer24X7 and explained the architecture to Thomas What is Thomas’s reply? Good or Bad?

Small transcript of the big discussion we had after looking into the architecture.

Thomas: Sorry Alexander but I don’t think this solution will work.

Alexander: Why Sir?

Thomas: See, it’s great that there exist a separate Factory for every Course group. (OnlineCourseFactory, CoporateCourseFactory).
But how will you keep a control over each and every factory. I meant how you will make sure that every factory is creating objects properly, for instance how will you be sure that each factory is following a company standard and creates course materials and schedule prior to returning the object.
It may possible that in future one more kind of factory say OfflineCourseFactory is added for managing offline courses and unknowingly it just violates the company standard and creates course materials in his own way.

Alexander: You are right Sir. Let me think about a full proof and final solution, Give me a day.

Thomas: No problem Alexander. Have a nice day.

Problem with the Approach 3

  • Every factory is independent here. There is no strict rule for defining factories. In this approach each factory can have their own structure and standards.

Move to Index

Day 4 – Night

Let’s list down all our requirements.

  • We need Factory for online Courses
  • We need Factory for corporate Courses
  • We don’t want to create single Factory for both modules.
  • There should be some rule how to define factories, which everybody should follow.

 

 

  • How it would be if we use combination of approach 3 (that is whenever required create new factory)
    plus Inheritance or Composition.

 

 

  • Time to sleep.

Move to Index

Day 5

What Alexander was talking about last night?

  • Put all common functionalities in a single place (class) and reuse them in all factories.
    We call it “ReusbaleClass” for discussion purpose. We need reusability –
    we can do it by 2 ways.

    • With inheritance – Derive all Factories from ReusbaleClass –> Call it Solution 1
    • With composition – All factories will have a member of type ReusbaleClass –> Call it Solution 2
  • Let factories override some functionality (which is different for every factory) defined in ReusbaleClass.
    • We need to override means Solution 1 will fit perfect.

Approach 4 – Factory Method Approach

In short we need a class here which will do all the common tasks and expose a virtual or abstract function.

So let’s create AbstractCourseFactory which will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our OnlineCourseFactory and CorporateCourseFactory.

public abstract class AbstractCourseFactory
{
    public AbstractCourse CreateCourse(string ScheduleType)
    {
        AbstractCourse objCourse = this.GetCourse(ScheduleType);        
        objCourse.CreateCourseMaterial();
        objCourse.CreateSchedule();
        return objCourse;
    }
    public abstract AbstractCourse GetCourse(string ScheduleType);
}

Please note GetCourse method is abstract

Now everyone (every factory) will easily override this GetCourse method.

public class CorporateCourseFactory:AbstractCourseFactory
{
    public override AbstractCourse GetCourse(string ScheduleType)
    {
        switch(ScheduleType)
        {
            case "N":
            return new CNetCourse();            
            case "J":
            return new CJavaCourse();
            default:
            return null;
        }
    }
}
public class OnlineCourseFactory : AbstractCourseFactory
{
    public override AbstractCourse GetCourse(string ScheduleType)
    {
        switch(ScheduleType)
        {
            case "N":
            return new ONetCourse();
            case "J":
            return new OJavaCourse();
            default:
            return null;
        }
    }
}

How Gang of Four defined Factory Method Pattern

“This pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses”.
Definition is self-explanatory now.

Move to Index

Day 6

Time to show the final demo to Thomas.

Now final UI code will look like

Online Course UI

AbstractCourseFactory objFactory = new OnlineCourseFactory();
AbstractCourse objCourse = objFactory.CreateCourse(StrUserInput);
//Display objCourse.CourseName and objCourse.CourseDuration

Corporate Course UI

AbstractCourseFactory objFactory = new CorporateCourseFactory();
AbstractCourse objCourse = objFactory.CreateCourse(StrUserInput);
//Display objCourse.CourseName and objCourse.CourseDuration

Advantages with the Approach 4

  • If in the future a new course group (say for instance offline course) introduced in Programmer24X7, a new factory will be derived from AbstractCourse, encapsulating creation of all concrete courses (say for instance Offline Java Courses, Offline .NET Course) related to that group. It’s that simple.

That’s all about the Factory Method patterns. Finally Thomas seems happy because all his requirements seem satisfied and Alexander is also happy because now he has become champ in Factory Method Pattern.

Move to Index

Additional approaches and thoughts

  • Is parent factory has to be abstract always?
    Answer for this question is No. We can make it non abstract if required and add default implementation to GetCourse method making it virtual.
  • Is switch is must in factories?
    No. We can replace switch loop with the Dictionary in .NET.
  • Is inheritance from second level factory is possible?
    Yes absolutely and that’s how factory method works. Initially we had AbstractCourseFactory with its default implementation for GetCourse method, which will be later extended by OnlineCourseFactory adding its own implementation for GetCourse method, which in turn can be a virtual method. So that later say when a new OnlineAdvanceCourse is introduced in Programmer24X7 existing, OnlineCourseFactory can easily be extended.
  • What will be the advantage of using MultiLevel inheritance in case of Factory Method Pattern?
    Well, consider following scenario.

    • We have our AbstractCourseFactory and OnlineCourseFactory.
    • OnlineCourseFactory override GetCourse method for defining online courses that is Java and .net.
    • Now let’s assume new courses are added after some year to Online Course and we are not even interested in opening OnlineCourseFactory.
    • OnlineCourseFactoryVersion2 will be introduced now.
    • Now if we derive OnlineAdvanceCourseFactory from AbstractCourseFactory we are supposed to define all previous courses like Java and .NET along with new one resulting redundant code.
    • Other than that what we can do is we will take help of Dictionaries for storing all available courses, and goes adding courses to it on each level.

Let’s look at the code snippet for same.

public abstract class AbstractCourseFactory
{
    protected Dictionary<string, AbstractCourse> ObjCourses;
    public AbstractCourseFactory()
    {
        ObjCourses = new Dictionary<string, AbstractCourse>();
    }
}
public class OnlineCourseFactoryVersion2 : OnlineCourseFactory
{
    public OnlineCourseFactoryVersion2()
    {
        ObjCourses.Add("V", new OVCourse());
    }    
}

Note: So using Dictionaries in Factory Method Pattern is always considered as a good approach.

So this completes my first article on Factory Pattern… Hope you liked it… Please don’t forget to leave your comments below…. Your positive and negative comments will encourage me to write better… Thank you!!! Smile | <img src=

 

LINK: http://www.codeproject.com/Articles/492900/From-No-Factory-to-Factory-Method

Generic Repository in ASPNET5

In this post, I am explaining generic repository pattern using EF7. The Repository Pattern is a common construct to avoid duplication of data access logic throughout our application. The purpose of the repository is to hide the details of accessing the data. We can easily query the repository for data objects, without having to know how to provide things like a connection string. The Repository pattern adds a layer between the data and domain layers of an application. It also makes the data access parts of an application better testable.

Here is the initial version of repository interface.

1 public interface IEmployeeRepository
2 {
3     Task<Employee> Get(Guid? id);
4     Task Save(Employee employee);
5     Task Delete(Employee employee);
6     Task Update(Employee employee);
7     Task<IEnumerable<Employee>> FindAll();
8 }

It is specific to Employee class, respository contains CRUD operations. And here is the implementation ofEmployeeRepository class with DbContext.

 1 public class EmployeeRepository : IEmployeeRepository
 2 {
 3     private EmployeeContext _employeeContext;
 4     public EmployeeRepository()
 5     {
 6         _employeeContext = new EmployeeContext();
 7     }
 8     public async Task<Employee> Get(Guid? id)
 9     {
10         return await _employeeContext.Employees.FirstOrDefaultAsync(x => x.Id == id);
11     }
12     
13     public async Task Save(Employee employee)
14     {
15         _employeeContext.Employees.Add(employee);
16         await _employeeContext.SaveChangesAsync();
17     }
18     
19     public async Task Delete(Employee employee)
20     {
21         _employeeContext.Employees.Remove(employee);
22         await _employeeContext.SaveChangesAsync();
23     }
24     
25     public async Task Update(Employee employee)
26     {
27         _employeeContext.Employees.Update(employee);
28         await _employeeContext.SaveChangesAsync();
29     }
30     
31     public async Task<IEnumerable<Employee>> FindAll()
32     {
33         return await _employeeContext.Employees.ToListAsync();
34     }
35 }

And here is the Employee context object.

 1 public class EmployeeContext : DbContext
 2 {
 3     private static bool _created = false;
 4 
 5     public EmployeeContext()
 6     {
 7         if (!_created)
 8         {
 9             Database.EnsureCreated();
10             _created = true;
11         }
12     }
13     
14     public DbSet<Employee> Employees { get; set; }
15     protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder)
16     {
17         optionsBuilder.UseInMemoryStore();
18     }
19 }

There are two problems with current EmployeeRepository implementation. First one it is using one model class, Employee, if you have multiple model classes, you need to duplicate lot of code. Second is it is not testable. The first problem you can fix by make it generic. And the second problem you can resolve by injecting the context object. Here is the generic repository interface.

1 public interface IGenericRepository<T> where T: class, IEntity, new()
2 {
3     Task<T> Get(Guid? id);
4     Task Save(T employee);
5     Task Delete(T employee);
6     Task Update(T employee);
7     Task<IEnumerable<T>> FindAll();
8 }

The IEntity interface contains only one property, Id.

1 public interface IEntity
2 {
3     Guid Id { get; set; }
4 }

And here is the implementation of GenericRepository class.

 1 public class GenericRepository<T> : IGenericRepository<T> where T: class, IEntity, new()
 2 {
 3     private DbContext _dbContext;
 4     public GenericRepository(DbContext dbContext)
 5     {
 6         _dbContext = dbContext;
 7     }
 8 
 9     public async Task Delete(T employee)
10     {
11         _dbContext.Set<T>().Remove(employee);
12         await _dbContext.SaveChangesAsync();
13     }
14 
15     public async Task<IEnumerable<T>> FindAll()
16     {
17         return await _dbContext.Set<T>().ToListAsync();
18     }
19 
20     public async Task<T> Get(Guid? id)
21     {
22         return await _dbContext.Set<T>().FirstOrDefaultAsync(x => x.Id == id);
23     }
24 
25     public async Task Save(T employee)
26     {
27         _dbContext.Set<T>().Add(employee);
28         await _dbContext.SaveChangesAsync();
29     }
30 
31     public async Task Update(T employee)
32     {
33         _dbContext.Set<T>().Update(employee);
34         await _dbContext.SaveChangesAsync();
35     }
36 }

In this implementation, one more problem exists, in the DbContext implementation, you need the reference ofEmployee model. You can make it DbContext also generic using Reflection.

 1 public class GenericDbContext : DbContext
 2 {
 3     private static bool _created = false;
 4     public GenericDbContext()
 5     {
 6         if (!_created)
 7         {
 8             Database.EnsureCreated();
 9             _created = true;
10         }
11     }
12     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
13     {
14         optionsBuilder.UseInMemoryDatabase(true);
15     }
16     protected override void OnModelCreating(ModelBuilder modelBuilder)
17     {
18         var types = Assembly.GetExecutingAssembly().GetTypes()
19             .Where(type => typeof(IEntity).IsAssignableFrom(type) && type.IsClass);
20         var method = typeof(ModelBuilder).GetMethods().First(m => m.Name == "Entity"
21             && m.IsGenericMethodDefinition
22             && m.GetParameters().Length == 0);
23         foreach (var type in types)
24         {
25             method = method.MakeGenericMethod(type);
26             method.Invoke(modelBuilder, null);
27         }
28 
29         base.OnModelCreating(modelBuilder);
30     }
31 }

In OnModelCreating method, all the types which implements IEntity interface are added to the DbContextusing Entity() method. This method is invoked dynamically using reflection. In ASP.NET 5, you can inject the repository and the context using inbuilt dependency injection feature.

1 public void ConfigureServices(IServiceCollection services)
2 {
3     services.AddMvc();
4     services.AddScoped<DbContext, GenericDbContext>();
5     services.AddScoped<IGenericRepository<Employee>, GenericRepository<Employee>>();
6 }

And here are the unit tests for create.

Happy programming! Smile | :)

LINK: http://www.codeproject.com/Articles/1035618/Generic-Repository-in-ASPNET