niedziela, 4 sierpnia 2013

Managing Android emulator in .NET

Automated coded UI testing become very popular in the past few years. Its allow developers to create tests which are executed directly on UI level and simulate user actions. At the same time HTML5 become a standard for creating universal modern applications which can be hosts in a native browser controls.

New model of creating applications brings a new challenges in the testing fields that's why in this post I want to present my solution (it takes me almost two days to get this working!) which is first step in the process of creation an end-to-end test automation for mobile applications. My solution is prototype of a .NET console application which can be use to control Android emulator and simulate user standard operation like installing app, typing and rotating. This prototype can be use as 'emulator manager' which controls device emulator on which tests are performed - for example by using  Selenium.

As initial requirements to run the project:
1) Install the latest Java build :(  (sorry .NET geeks but it`s required)
2) Install Android SDK

Now we have all environment in place so we can create our emulator device. To do that we need to use Android Virtual Devices Manager tool which is located in the '..\\sdk\tools\' path inside Android SDK folder. To run this tool we need start cmd, navigate to the SDK tools folder and type 'android avd'. Now we can create a new emulator by specifying all setting we need - in the picture below I presented settings for my AVD called 'nexus'. To make sure that all configuration if correct we should run out AVD by calling emulator.exe  from  '..\\sdk\tools\'  for example 'emulator -avd nexus' - this cause our emulator start running and first run might take some time so be patient.

Picture 1. Configuration of a new  device emulator.
Now its time to back to the C# code a present solution which can manage Android emulator through .NET code. Basically solution based on the simple console application which is calling externals console applications:

  • emulator.exe - console application which allow to start device emulator by device name with specific parameters.
  • adb.exe - console application which allow communication with device emulator; allow to run shell mode directly on the emulator.
Picture 2. Application architecture.

There is two very important parts inside this solution. First one is the IEmulator interface which expose all functions which are currently supported by the program. The idea is that this solution can be extended to all main three mobile platforms (iOS, Android, Windows) and the IEmulator interface will remain common an contract for all of them so just implementation of each emulator will be different (now only AndroidEmulator class is implemented). IEmulator interface implementation is as follow:

Code Snippet
  1. /// <summary>
  2. /// Expose all emulator tasks.
  3. /// </summary>
  4. public interface IEmulator
  5. {
  6.     /// <summary>
  7.     /// Starts the emulator.
  8.     /// </summary>
  9.     /// <returns>Value which determines emulator is ready for use.</returns>
  10.     bool Initialize();
  11.  
  12.     /// <summary>
  13.     /// Enable shell mode on the emulator.
  14.     /// </summary>
  15.     void StartShell();
  16.  
  17.     /// <summary>
  18.     /// Checks the emulator is running.
  19.     /// </summary>
  20.     bool IsRunning();
  21.  
  22.     /// <summary>
  23.     /// Install app on the emulator.
  24.     /// </summary>
  25.     /// <param name="packagePath">Path to the apk package to intsall.</param>
  26.     /// <returns>True if application installed correctly.</returns>
  27.     bool InstallApp(string packagePath = null);
  28.  
  29.     /// <summary>
  30.     /// Uninstall specyfic package from emulator.
  31.     /// </summary>
  32.     /// <param name="packageName">Specyfic package name to uninstall.</param>
  33.     void UninstallApp(string packageName = null);
  34.  
  35.     /// <summary>
  36.     /// Run monkey on package.
  37.     /// </summary>
  38.     /// <param name="activitiesCount">Action count.</param>
  39.     void RunMonkey(int activitiesCount = 500);
  40.  
  41.     /// <summary>
  42.     /// Simulating keypress events on emulator.
  43.     /// </summary>
  44.     /// <param name="codes">Hardware codes array.</param>
  45.     void TypeAsHardwareInput(int[] codes);
  46.  
  47.     /// <summary>
  48.     /// Change orientation of the emulator.
  49.     /// </summary>
  50.     void ChangeOrientation();
  51. }

As you can see here, not all options are implemented but the most important functions are on place so let`s have a quick look on its:
  • Initialize: function which starts device emulator by calling emulator.exe as separate process and pass AVD name from the configuration file.
  • StartShell:  using 'adb shell' command from adb.exe tool in separated process to start shell mode on the currently running AVD. Process which hosts shell will remain active until application close.
  • IsRunning: function which call  'adb devices'  command  in separated process from adb.exe tool to check if AVD  is currently running.
  • InstallApp: install APK file from specific path in local PC by calling 'adb wait-for-device install <apk full-path>' command from adb.exe as separated process. Additional wait-for-device command ensure that emulator is ready to install app. 
  • UninstalApp: uninstall app from shell level by using package name (ex. com.android.tools.sdkcontroller stored in AndroidInstalledAppName App.config)
  • RunMonkey: from shell mode run monkey random actions on the installed package by executing N (activitiesCount) random activities.
  • TypeAsHardwareInput: allow to use simulate hardware keys to input any supported input. Under the hood its calling shell command 'input keyevent <key_code>' with key code specified for the platform. Key-codes list is available here.
Last function I want to describe in not supported by the Android SDK and from testing point of view it`s crucial -I mean here changing emulator orientation during the run-time. I spent a lot of time reading and investigating any potential possibility of changing emulator orientation by no of solutions I`ve found  was working for me. There is only one official way to switch emulator orientation - by pressing CTRL+F11, and I`m implemented it. Source code for this using  an external library called InuputSimulator (thank you Michael) to simulate keystroke. Additionally I used emulator process  name to find exact process and get focus on their main window before simulate keystroke.   

Code Snippet
  1. [DllImport("user32.dll")]
  2.         static extern bool SetForegroundWindow(IntPtr hWnd);
  3.  
  4.         /// <summary>
  5.         /// Change orientation of the emulator.
  6.         /// </summary>
  7.         public void ChangeOrientation()
  8.         {
  9.             var emulatorProcess = Process.GetProcessesByName("emulator-arm");
  10.             if (emulatorProcess.Count() == 0)
  11.             {
  12.                 throw new InvalidOperationException("Unable to find emulator process.");
  13.             }
  14.  
  15.             BringToFront(emulatorProcess[0]);
  16.             WindowsInput.InputSimulator.SimulateModifiedKeyStroke(WindowsInput.VirtualKeyCode.CONTROL, WindowsInput.VirtualKeyCode.F11);
  17.         }
  18.         
  19.         /// <summary>
  20.         /// Set focus on the process.
  21.         /// </summary>
  22.         /// <param name="pTemp">Process to be focused.</param>
  23.         private void BringToFront(Process pTemp)
  24.         {
  25.             SetForegroundWindow(pTemp.MainWindowHandle);
  26.         }

Now when all functions are on place we can call them in logical order.

Code Snippet
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.         var emulator = EmulatorFactory.GetEmulator(EmulatorType.Android);
  6.  
  7.         emulator.Initialize();
  8.  
  9.         emulator.InstallApp();
  10.  
  11.         emulator.StartShell();
  12.  
  13.         emulator.ChangeOrientation();
  14.         emulator.ChangeOrientation();
  15.  
  16.         emulator.RunMonkey();
  17.         emulator.UnistallApp();
  18.     }
  19. }

I can`t guarantee but I hope that soon I will add next emulator - keep your fingers crossed!

Whole source code of the project is available here.

Thank you

More info:

sobota, 20 lipca 2013

Playing with a .NET types definition

In the last few days I spent some time trying to unify structure of one of the project I`m currently working on. Most of the changes were about changing variable types because it`s were not used right way. That is why in this post I want to share my observations and practices with you.

First of all we need to understand what 'variable definition' is and how it`s different from 'variable initialization'. This part should be pretty straightforward:
  •  variable definition consist of data type and variable name only <data_type> <variable_name>; for example int i; . It`s important to understand how variable definition affects your code because it behaves differently depends weather you work with value or reference types. In the case of value types after defining variable it always has default value and it`s never null value. However after defined reference type variable without initializing it has null value by default.
  • variable initialization is a process of assigning value to the variable - variable_name = value; it can be merged with the definition into one line expression <data_type> <variable_name> = value;
Code Snippet
  1. public class Test
  2. {
  3.     public Test()
  4.     {
  5.         // variable definition for value type.
  6.         int i; // i == 0 as this stage.
  7.  
  8.         // variable definition for reference type.
  9.         string s; // s == null at this stage.
  10.  
  11.         // value type variable initialization
  12.         i = 10; // i == 10.
  13.  
  14.         // referece type variable initialization
  15.         s = "Test";
  16.     }
  17. }

Now we can go forward and compare a different types of a variable definition. As many of you remember in the past, in .NET Framework 2.0, only one type of variable definition exists. Here I mean classic, strongly typed, combination of type and variable name (example below line 13.). It was very popular (because at this time there was nothing else to replace it) but this approach requires creating separated type for each problem. This cause in many project multiple very similar types exists so it was not a perfect solution.

Code Snippet
  1. public class Test
  2. {
  3.     public class SomeType
  4.     {
  5.         internal void DoSomething()
  6.         {
  7.         
  8.         }
  9.     }
  10.  
  11.     public Test()
  12.     {
  13.         SomeType type = new SomeType();
  14.         type.DoSomething();
  15.     }
  16. }

Since .NET Framework 3.0 developers was  able to switch their mind into different kind of thinking about defining variables because a new var keyword became in use. A var keyword  is separated type of defining variables, which are still strongly typed but it`s resolved by the compiler based on value assigned to it during initialization (a var variable have to be defined and initialized in the same line of code). Why is so cool to use it? This is a  very good question and a lot discussions around that already exists in the Internet. First of all variables defined with var keyword in general have more descriptive name because in other case even developer might have a problem with reading own code. Let see an example:

Code Snippet
  1. using System.Collections.Generic;
  2. public class Test
  3. {
  4.     public class SomeType
  5.     {
  6.         internal void DoSomething()
  7.         {
  8.         
  9.         }
  10.     }
  11.  
  12.     public Test()
  13.     {
  14.  
  15.         // SomeType someType = new SomeType();
  16.         var someType = new SomeType(); // equivalent to line above.
  17.         var someTypeList= new List<SomeType>();
  18.     }
  19. }

However the real power of using var keyword ins`t naming convention but something which is called anonymous types. It`s really powerful tool in developers hands!! Anonymous types are generated by the compiler, are strongly typed and not exists physically as a class or structure in a project code but provide a convenient way to encapsulate a set of read-only properties into a single object. Let`s see example of using it:
Code Snippet
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System;
  4. public class Test
  5. {
  6.     public class User
  7.     {
  8.         public int Id { get; set; }
  9.         public string Name { get; set; }
  10.         public string Surname { get; set; }
  11.         public string Department { get; set; }
  12.         public byte[] HugeArray { get; set; }
  13.     }
  14.  
  15.     public Test()
  16.     {
  17.         var userList = new List<User>();
  18.  
  19.         // code to populate the list.
  20.  
  21.         // Creating a new anonymous type with HrId and FullName properties.
  22.         var userInHrDepartment = from user in userList
  23.                                  where user.Department == "HR"
  24.                                  select new { HrId = user.Id, FullName = user.Name + " " + user.Surname };
  25.  
  26.         // Tterate through collection of anonymous type.
  27.         foreach (var hrUser in userInHrDepartment)
  28.         {
  29.             Console.WriteLine(hrUser.FullName);
  30.         }
  31.     }
  32. }

As you can see by using a very simple LINQ query I`m extracting only variable I really want to process, and without creating strong type explicit I`m using anonymous type to iterate through the collection and accessing specific properties.

Last type of a variable definitions comes with .NET Framework 4.0 which introduce a new dynamic type.
This is completely different type of thinking for developers because this type of object behaves very similar to the well know object type.  However the difference between those two is huge because object is so powerful because of inheritance while dynamic type is not strongly typedlate-bound and exists only at run-time. Basically it`s a bag where we can put everything and expect everything but we can`t be sure that something exist there. Let see dynamic type in action.

Code Snippet
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System;
  4. public class Test
  5. {
  6.     public class User
  7.     {
  8.         public int Id { get; set; }
  9.         public string Name { get; set; }
  10.         public string Surname { get; set; }
  11.         public string Department { get; set; }
  12.         public byte[] HugeArray { get; set; }
  13.     }
  14.  
  15.     public Test()
  16.     {
  17.         var user = new User();
  18.         dynamic userModyfied = user;
  19.  
  20.         // Adding extra property to the User type.
  21.         userModyfied.AdditionalProperty = "Test value";
  22.         Console.WriteLine(userModyfied.AdditionalProperty);
  23.  
  24.         dynamic userModyfied2 = new User();
  25.         userModyfied2.AdditionalProperty2 = "Test value 2";
  26.  
  27.         Console.WriteLine(userModyfied.AdditionalProperty2); // value exists
  28.         Console.WriteLine(userModyfied.AdditionalProperty); // value doesn`t exist
  29.     }
  30. }

As you can see in the example above. This is very strange type and might bring a lot or troubles when used incorrectly. Additionally usage it  hurts performance  of our solution so use it wisely only if necessary.

Thank you

Creating API with MVC ApiController part 3 - moving to asynchronous code

In my two previous posts (part 1 and part 2) I described both simple and more advance approach of creating Rest-full API in MVC 4. Today I want to take another step forward and go a little deeper  in the creation of API. In this post I`m going to describe how we can create asynchronous API functions which bring better performance to our applications.

The first thing that need to be understand is an asynchronous operation in .NET Framework. In .NET Framework 4.0 one of the most important changed was introducing Task class.The Tasks in System.Threading.Tasks namespace are a method of fine grained parallelism, similar to creating and using threads, but they have a few key differences and the main difference is that Tasks in .NET 4.0 don’t actually correlate to a new thread, they are executed on the new thread pool that is being shipped in .NET 4.0. More about task you can read here but to understand this article all you need to understand about the Task<T> class is that this type encapsulate asynchronous action which returns T type object. Task<T> type also expose a result of it in the Result<T> property and allow to verify execution  state by checking Status or IsCompleted property. 

Now we know more about asynchronous tasks in .NET Framework 4.0 but it`s not all because .NET Framework 4.5 offers a two completely new keywords in C# async and await. Those keywords exist together and work (in one function) to make functions completely asynchronous. To understand how to use it first of all we need to aware of plate to put it:
  • async - exist in function signature right after access modifiers; it`s mark function to be asynchronous
  • await - exists in the function body which is marked as async; it placed before function result which was called asynchronously 
Usage of both new keywords is very easy as far as you can see on the example presented below (from MSDN) but still restrictions still and you can read about it here

async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

Now, when working with  asynchronous operations is not problem for us, it`s time to back to our Rest API and make is asynchronous. As example of asynchronous API  I want to use the same API I presented in my previous post and instead of changing logic just change it to fully asynchronous - so in other words I want to extend existing API with all CRUD operation form managing users to work non synchronous way.

[1] The very first thing I want to change is all API function signatures. I mean here change all functions from HttpResponseMessage Get() to async Task<HttpResponseMessage> Get(). I also  believe that the new function signature is not mysterious for you after you read this article introduction.

[2] As second change I want to make is encapsulate all API functions logic execution to be part of the Task<T> as presented in example below.

Code Snippet
  1. [HttpGet]
  2.         public HttpResponseMessage Get()
  3.         {
  4.             return Request.CreateResponse<ReadOnlyCollection<User>>(HttpStatusCode.OK, FakeDbContext.Instance.Users.AsReadOnly());
  5.         }
  6.  
  7.         // Changing synchonous code to asynchonous function
  8.  
  9.         [HttpGet]
  10.         public async Task<HttpResponseMessage> Get()
  11.         {
  12.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  13.             {
  14.                 var allUsers = FakeDbContext.Instance.Users.ToArray();
  15.                 var resultCollection = new Collection<User>(allUsers);
  16.                 return Request.CreateResponse<Collection<User>>(HttpStatusCode.OK, resultCollection);
  17.             });
  18.         }

That`s it! It was really straightforward as you can see. Now our API  is working fully asynchronous and can be called without blocking. Let  have overall look of it.

Code Snippet
  1. using MvcApplication1.Controllers;
  2.  
  3. namespace WebApi.Controllers
  4. {
  5.     using System;
  6.     using System.Collections.ObjectModel;
  7.     using System.Net;
  8.     using System.Net.Http;
  9.     using System.Threading.Tasks;
  10.     using System.Web.Http;
  11.     using WebApi.Common;
  12.     using WebApi.Models;
  13. using MvcApplication1.Controllers;
  14.  
  15.     /// <summary>
  16.     /// Asynchonous controller for managing <see cref="User"/>.
  17.     /// </summary>
  18.     public class AsyncController : ApiController
  19.     {
  20.         /// <summary>
  21.         /// Add a new <see cref="User"/> to the collection.
  22.         /// </summary>
  23.         /// <param name="user">User to add.</param>
  24.         /// <returns>The added <see cref="User"/>.</returns>
  25.         /// <remarks>GET http://xy.z/api/async/ </remarks>
  26.         [HttpPost]
  27.         public async Task<HttpResponseMessage> Post(User user)
  28.         {
  29.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  30.             {
  31.                 if (user == null)
  32.                 {
  33.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid user.");
  34.                 }
  35.  
  36.                 user.Id = RandomGenerator.Instance.NextInt();
  37.                 FakeDbContext.Instance.Users.Add(user);
  38.                 return Request.CreateResponse<User>(HttpStatusCode.Created, user);
  39.             });
  40.         }
  41.  
  42.         /// <summary>
  43.         /// Returns all users.
  44.         /// </summary>
  45.         /// <returns>Collection of all users.</returns>
  46.         /// <remarks>GET http://xy.z/api/async/ </remarks>
  47.         [HttpGet]
  48.         public async Task<HttpResponseMessage> Get()
  49.         {
  50.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  51.             {
  52.                 var allUsers = FakeDbContext.Instance.Users.ToArray();
  53.                 var resultCollection = new Collection<User>(allUsers);
  54.                 return Request.CreateResponse<Collection<User>>(HttpStatusCode.OK, resultCollection);
  55.             });
  56.         }
  57.  
  58.         /// <summary>
  59.         /// Get user by user ID.
  60.         /// </summary>
  61.         /// <param name="id">Id of the user.</param>
  62.         /// <returns>User with specyfied ID.</returns>
  63.         /// <remarks>GET http://xy.z/api/async/32</remarks>
  64.         [HttpGet]
  65.         public async Task<HttpResponseMessage> GetById(int id)
  66.         {
  67.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  68.             {
  69.                 var selectedUser = FakeDbContext.Instance.Users.Find(u => u.Id == id);
  70.                 return Request.CreateResponse<User>(HttpStatusCode.OK, selectedUser);
  71.             });
  72.         }
  73.  
  74.         /// <summary>
  75.         /// Updates user.
  76.         /// </summary>
  77.         /// <param name="user">User to update.</param>
  78.         /// <returns>Updated user.</returns>
  79.         [HttpPut]
  80.         public async Task<HttpResponseMessage> Put(User user)
  81.         {
  82.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  83.             {
  84.                 if (user == null || user.Id == 0)
  85.                 {
  86.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid user.");
  87.                 }
  88.  
  89.                 var selectedUser = FakeDbContext.Instance.Users.Find(u => u.Id == user.Id);
  90.                 if (selectedUser == null)
  91.                 {
  92.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found.");
  93.                 }
  94.  
  95.                 var index = FakeDbContext.Instance.Users.IndexOf(selectedUser);
  96.                 user.Id = selectedUser.Id;
  97.  
  98.                 FakeDbContext.Instance.Users.RemoveAt(index);
  99.                 FakeDbContext.Instance.Users.Insert(index, user);
  100.  
  101.                 return Request.CreateResponse<User>(HttpStatusCode.NoContent, user);
  102.             });
  103.         }
  104.  
  105.         /// <summary>
  106.         /// Delete user from storage.
  107.         /// </summary>
  108.         /// <param name="id">ID of the user to remove.</param>
  109.         /// <returns>Response without content.</returns>
  110.         [HttpDelete]
  111.         public async Task<HttpResponseMessage> Delete(int id)
  112.         {
  113.             return await Task<HttpResponseMessage>.Factory.StartNew(() =>
  114.                {
  115.                    if (id == 0)
  116.                    {
  117.                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid ID.");
  118.                    }
  119.  
  120.                    var selectedUser = FakeDbContext.Instance.Users.Find(u => u.Id == id);
  121.  
  122.                    if (selectedUser == null)
  123.                    {
  124.                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found.");
  125.                    }
  126.  
  127.                    FakeDbContext.Instance.Users.Remove(selectedUser);
  128.  
  129.                    return Request.CreateResponse(HttpStatusCode.NoContent);
  130.                });
  131.         }
  132.     }
  133. }

Whole source code of the project is available here.

Thank you.

poniedziałek, 8 lipca 2013

Creating API with MVC ApiController part 2

In my previous post I wrote about first steps in creating Rest-full API by using ApiController. Now it`s time to make next step and go a little bit dipper inside web services created in MVC. In this post I want to describe two very important aspect:
  • creating a real life scenario for web service implementation of POCO entity
  • extend presented scenario and make it asynchronous
To complete this tutorial one more class is needed. This class is a simple fake of some database which  is wrapper around a very few collections and allow all CRUD operation. Moreover the implementation of this fake database uses a singleton design pattern to prevent creating instance of it each time and maintain state between web service calls.

Code Snippet
  1. /// <summary>
  2.         /// Represents a fake database.
  3.         /// </summary>
  4.         public sealed class FakeDbContext
  5.         {
  6.             private static volatile FakeDbContext instance;
  7.             private static object syncRoot = new Object();
  8.  
  9.             private FakeDbContext()
  10.             {
  11.                 this.Users = new List<User>();
  12.                 this.Dictionary = new Dictionary<string, string>();
  13.             }
  14.  
  15.             public static FakeDbContext Instance
  16.             {
  17.                 get
  18.                 {
  19.                     if (instance == null)
  20.                     {
  21.                         lock (syncRoot)
  22.                         {
  23.                             if (instance == null)
  24.                                 instance = new FakeDbContext();
  25.                         }
  26.                     }
  27.  
  28.                     return instance;
  29.                 }
  30.             }
  31.  
  32.             public List<User> Users { get; set; }
  33.  
  34.             public Dictionary<string, string> Dictionary { get; set; }
  35.         }

The real life scenario that we want to implement is a simple web service which expose all CRUD operation and of course it`s base on REST. In the following class each API functions return the same type HttpResponseMessage which represent a standard HTTP response. This type contains two important properties: StatusCode - which represent a  HTTP response status code and Content - which store body of the response if any. The the easiest to produce a HttpResponseMessage is calling one of many build-in functions which are responsible for creating a fully qualified response based on several input parameter:
Code Snippet
  1. /// <summary>
  2.         /// Represent a controller for managing <see cref="User"/>.
  3.         /// </summary>
  4.         public class UserController : ApiController
  5.         {
  6.             public UserController()
  7.             {
  8.                 if (!FakeDbContext.Instance.Users.Any())
  9.                 {
  10.                     FakeDbContext.Instance.Users = new List<User>()
  11.                 {
  12.                     new  User(){ Id = 1, FirstName = "Roberto", LastName="Carlos", Email="robi_carlo@gmail.com"},
  13.                     new  User(){ Id = 2, FirstName = "Zinédine", LastName="Zidane", Email="zizu@live.com"},
  14.                     new  User(){ Id = 2, FirstName = "Peter", LastName="Schmeichel", Email="scheisse@yahoo.com"},
  15.                 };
  16.                 }
  17.             }
  18.  
  19.             // GET api/person
  20.             [HttpGet]
  21.             public HttpResponseMessage Get()
  22.             {
  23.                 return Request.CreateResponse<ReadOnlyCollection<User>>(HttpStatusCode.OK, FakeDbContext.Instance.Users.AsReadOnly());
  24.             }
  25.  
  26.             // GET api/person/5
  27.             [HttpGet]
  28.             public HttpResponseMessage Get(int id)
  29.             {
  30.                 var resultUser = FakeDbContext.Instance.Users.FirstOrDefault(u => u.Id == id);
  31.                 if (resultUser == null)
  32.                 {
  33.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  34.                 }
  35.  
  36.                 return Request.CreateResponse<User>(HttpStatusCode.OK, resultUser);
  37.             }
  38.  
  39.             // POST api/person
  40.             [HttpPost]
  41.             public HttpResponseMessage Post(User value)
  42.             {
  43.                 if (value == null)
  44.                 {
  45.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Null User object.");
  46.                 }
  47.  
  48.                 // Checking user already exists in a list.
  49.                 if (FakeDbContext.Instance.Users.Contains(value))
  50.                 {
  51.                     return Request.CreateErrorResponse(HttpStatusCode.Conflict, "User already exists.");
  52.                 }
  53.                 else
  54.                 {
  55.                     FakeDbContext.Instance.Users.Add(value);
  56.                 }
  57.  
  58.                 return Request.CreateResponse(HttpStatusCode.Created);
  59.             }
  60.  
  61.             // PUT api/person/5
  62.             [HttpPut]
  63.             public HttpResponseMessage Put(int id, [FromBody] User value)
  64.             {
  65.                 if (value == null)
  66.                 {
  67.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Null User object.");
  68.                 }
  69.  
  70.                 if (!FakeDbContext.Instance.Users.Any(u => u.Id == id))
  71.                 {
  72.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  73.                 }
  74.                 else
  75.                 {
  76.                     FakeDbContext.Instance.Users.Remove(value);
  77.                     FakeDbContext.Instance.Users.Add(value);
  78.                 }
  79.  
  80.                 return Request.CreateResponse(HttpStatusCode.OK);
  81.             }
  82.  
  83.             // DELETE api/person/5
  84.             [HttpDelete]
  85.             public HttpResponseMessage Delete(int id)
  86.             {
  87.                 var personToDelete = FakeDbContext.Instance.Users.FirstOrDefault(u => u.Id == id);
  88.                 if (personToDelete == null)
  89.                 {
  90.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  91.                 }
  92.                 else
  93.                 {
  94.                     FakeDbContext.Instance.Users.Remove(personToDelete);
  95.                 }
  96.  
  97.                 return Request.CreateResponse(HttpStatusCode.OK);
  98.             }
  99.         }

Now our service is ready to use and we run it and we can call each GET, POST, PUT and DELETE function by using any of HTTP Client.

Picture 1. Calling GET and POST API  from test HTTP Client.
Whole source code of the project is available here.

Thank you.