Sunday 11 November 2018

Step by Step implementation pf Repository Pattern using C# for Beginners

Design Pattern:
         Create a pattern for your code so it can be reusable and with well maintained code. So easy to add new modules without writing too much code.

Repository Pattern:
Basic Purpose of design pattern is to have separation between Business Logic and DB calls.
Advantages:
1: Easily testable business Logic
2: Application works on API calls
3: All modules have API so it can easily integrate able with any other platforms.
4: Maximum implementation OOP concepts like Templates, Interfaces and Inheritance.

Implementation of Repository Patterns step by step:


2 step:
3rd step:
4th step:
5th step:
6th step:
7th step:
8th step:
9th step:
10th step:
11 step:
12th step:
13th step:
14th step:
15th step:
16th step:
17th step:
18th step:
19th step:


Further Implementation projects:
Common Project

1: Create folder APIResponse
2: Add 3 classes as per the image
3: Install Nuget package of Json.net in common project

4: Add AppConstant class as per the image

5: Add HttpHelper class and add below functions one function to get data and second for post

   public static List<T> DownloadSerializedJsonViaGET<T>(string url) where T : new()
        {
            using (var client = new WebClient())
            {
                try
                {
                    client.Encoding = Encoding.UTF8;
                    client.Headers[HttpRequestHeader.ContentType] = AppConstant.ContentType;
                    client.Headers[HttpRequestHeader.Accept] = AppConstant.ContentType;

                    string jsonData = client.DownloadString(url);
                    var response = JsonConvert.DeserializeObject<List<T>>(jsonData);
                    ResponseList<T> responseForCurrentObject = new ResponseList<T>();
                    responseForCurrentObject.data = response;
                    responseForCurrentObject.Message = "Successful Transaction";
                    return responseForCurrentObject.data;
                }
                catch (WebException exception)
                {
                    #region EXCEPTION HANDLING
                    var errorResponseText = "";
                    if (exception.Response != null)
                    {
                        var responseStream = exception.Response.GetResponseStream(); // Get API error and show as message
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                errorResponseText = reader.ReadToEnd();
                            }
                        }
                    }
                    return JsonConvert.DeserializeObject<List<T>>(errorResponseText);
                    #endregion
                }

            }
        }

        public static Response<T> DownloadSerializedJsonViaPOST<T>(string url, object data, string method = "POST") where T : new()
        {
            using (var client = new WebClient())
            {
                try
                {
                    client.Encoding = Encoding.UTF8;
                    client.Headers[HttpRequestHeader.ContentType] = AppConstant.ContentType;
                    client.Headers[HttpRequestHeader.Accept] = AppConstant.ContentType;

                    var obj = JsonConvert.SerializeObject(data);

                    string jsonData = client.UploadString(url, method, obj);
                    var response = JsonConvert.DeserializeObject<T>(jsonData);
                    Response<T> responseForCurrentObject = new Response<T>();
                    responseForCurrentObject.data = response;
                    return responseForCurrentObject;
                }
                catch (WebException exception)
                {
                    #region EXCEPTION HANDLING
                    var errorResponseText = "";
                    if (exception.Response != null)
                    {
                        var responseStream = exception.Response.GetResponseStream(); // Get API error and show as message
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                errorResponseText = reader.ReadToEnd();
                            }
                        }
                    }
                    return JsonConvert.DeserializeObject<Response<T>>(errorResponseText);
                    #endregion
                }

            }
        }



Service Project

1: Add two folder one for interface and second for implementation
 2: Implementation of interfaces



Web Project 
1: Call service function in your web project


API Project
1: Install nuget package AutoMapper in your api project
2: Do basic configuration for Mapper. (Auto Mapper is for to map input entities with db context entities)
3: Create Folder DTO in Common project 
4: Copy entities from Model and paste in UserDTO class

5: Use auto mapper as per the below image in your API project controller:




In case of any query feel free to reach me. Thanks for reading the blog.