Tuesday, July 31, 2018

OOPS Questions - Encapsulation and Abstraction in Simple Terms with Example



Encapsulation

Encapsulation means to encapsulate or put everything into one thing and provide others to use it.
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Abstraction

Abstraction is a process to abstract or hide the functionality and provide users or other programmer which are necessary,
Abstraction is "To represent the essential feature without representing the back ground details.
Like for the method Console.WriteLine(), no one knows what actually is happening behind the function calling. We are just using it by calling and passing the arguments. This is the thing called Abstraction.

Example

Let's assume you have to create a method to insert user’s data and pass it to other developers to use. So first, create a class and add a method to insert the data into database with validation.
There will be three fields:
1.       Name
2.       Email
3.       Phone number

Before insert into DB We will validate it.
First, create a class with all methods:

class User
{
    public bool AddUser(string name, string email, string phone)
    {
        if (ValidateUser(name, email, phone))
        {
            if (AddtoDb(name, email, phone) > 0)
            {
                return true;
            }
        }
        return false;
    }

    private bool ValidateUser(string name, string email, string phone)
    {
        // do your validation
        return true;
    }

    private int AddtoDb(string name, string email, string phone)
    {
        // Write the Db code to insert the data
        return 1;
    }
}

As you can see, there are three methods that are written in this User class.
·         AddUser: To call from outside the class. That is why the access modifier is public.

·         validateUser: To validate the user's details. Can't access from outside the class. It's private.

·         AddtoDb: To insert data into database table and again it is private, can't access from outside the class.
Now another user will just call AddUser method with parameters. And that user has no idea what is actually happening inside the method
To call the AddUser method, do as follows:

class Program
{
    static void Main(string[] args)
    {
        User objUser = new User();
        bool f = objUser.AddUser("John", "john@abc.com", "34354543455");
    }
}
Now come back to the main discussion.
Here, we are hiding the procedure of adding data into database from other users, this is Abstraction. And putting all the three methods into one User class and providing other users to use it, that is called Encapsulation.

So procedure hiding is Abstraction and putting every necessary thing into one is Encapsulation.

Monday, June 18, 2018

Generics Methods in C# with simple example

What is generics ? 


Generics is c# features which allow to define a class or method with type as a parameter.
In generics we can define a type at the time of declaration and initialization.


Facts about Generics.

 - We can use generics types to maximize code reuse. type safety and perfomance. 

 - We can create your own generic interfaces, classes, methods, events and delegates.

Generic - Perfomace -Type -safe

Let's Explain it using simple example of c# application.








1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;


namespace PracticleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // String and int array list 
            int[] intarray = new int[] { 1, 15, 55, 4, 31 };
            string[] strarray = new string[] { "Bengaluru", "Ahmedabad", "Pune", "Mumbai" };


            // Without Generic Method  Sort About int and string array. 
            // We need to call two different method for different data type.  
            sortingdemo obj = new sortingdemo();

            // Sort String array we need to call "sortstringarray" methods.
            string[] stroutputarray = obj.sortstringarray(strarray);

            //  Sort int array we need to call "sortintarray" methods.   
            int[] intoutarray = obj.sortintarray(intarray);



            //  Using Generic Method 
            // We can reuse the code by using generic methods. 
            // generic methods are always static. 
            int[] genericintarray = sortingdemo.sortgeneric(intarray);
            string[] genericstringarray = sortingdemo.sortgeneric(strarray);


        }


        public class sortingdemo
        {
            public string[] sortstringarray(string[] strarray)
            {
                // Using Sort function.
                string[] aryoutput;
                aryoutput = strarray;
                Array.Sort(aryoutput);
                return aryoutput;

            }
            public int[] sortintarray(int[] intarray)
            {
                int[] aryintout;
                aryintout = intarray;
                Array.Sort(aryintout);
                return aryintout;
            }

            public static T[] sortgeneric<T>(T[] array)
            {
                T[] arryout;
                arryout = array;
                Array.Sort(arryout);
                return arryout;
            }
        }
    }
}





Friday, November 17, 2017

What is Abstract Class - Facts About Abstract Class


  • What is Abstract Class  ?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation

Abstract classes may not be instantiated, and require sub -classes to provide implementations for the abstract methods.


  • Why do we need  Abstract Class ?

-   While you want to implementation detail to your child class but don't allow child to create instance      of  your class.  

-   We need to use abstract class when we want to follow certain hierarchy for all sub classes.

-   In simple words, it is a kind of contract that forces all the sub classes to carry on the same                    hierarchies or standards.

  • Facts About Abstract Class

- Abstract class can not be Sealed or static.

- We Can not create instance of the abstract class.

- An abstract class can have abstract as well as non abstract methods. 

- Abstract members can only be declared inside an abstract class

- An abstract member cannot be static or private

- A concrete class cannot inherit more than one abstract class, in other words multiple Inheritance is     not possible.


  • Practical Example For  Abstract Class using c# console application 

We will take example of of Apple. for example if we take Apple class has our base class have some basic functionality like "Call" and "SMS". Sub Classes can use this two method. We will define GetModelName method as  abstract and force sub classes to provide implementation for this method.

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    abstract class Apple
    {
        public void call()
        {
            // Non Abstract Method All SubClass can use without implementaion 
            Console.WriteLine("Call Method: This method provides Calling features");
            Console.WriteLine("Abstrac class called");
        }

        // Abstract Method Sub Classes must provide implementaion for this abstract method.
        public abstract string GetModelName();

        // Non Abstract Property 
        public string ModelName { get; set; }

        // Abstract Method
        public abstract string IMEI { get; }

    }

    class IPhone4 : Apple
    {
        // Implementaion of Abstract Property.
        public override string IMEI
        {
            get
            {
                return "34234324324324";
            }

        }

        // Implementaion of Abstract Method
        public override string GetModelName()
        {
            return "Iphone4";
        }

        static void Main(string[] args)
        {
            IPhone4 obj = new IPhone4();
            obj.call();
            obj.ModelName = obj.GetModelName();
        }
    }
}









Tuesday, November 14, 2017

File Upload Control Model MVC C#


TWO File Upload Control in Model With Custom Attribute -Data Annotations


For Understand file upload control in MVC C# (.Net) We are taking example of Upload Profile Pic & Covert Photo. We are defining "HttpPostedFileBase" in Model. Here "FileSize" and "FileTypes" are custom attributes we will create custom attibutes in step2. so don't worry if it's give compile time error.

Step 1 :  Create A Model  


public class FileUploadModel
    {
        [Required(ErrorMessage = "Please Choose Profile Pic")]
        [FileSize(102400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase ProfilePic { get; set; }

        [Required(ErrorMessage = "Please Choose Cover Photo")]
        [FileSize(1002400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase CoverPhoto { get; set; }
    }


Step 2 :  Create A Class for  Custom Validation Data Annotation Attribute for Validate Image File.


In above model we have used two custom attribute for validate image size and image type.Validation in MVC can be done using Data Annotations that are applied to both the client and server side, so Create one folder "Attributes" and define below mention class in it.  

Add reference of below class in model defined in step1.


public class FileSizeAttribute : ValidationAttribute
        {
            private readonly int _maxSize;

            public FileSizeAttribute(int maxSize)
            {
                _maxSize = maxSize;
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                return (value as HttpPostedFileBase).ContentLength <= _maxSize;
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("The file size should not exceed {0}", _maxSize);
            }
        }


        public class FileTypesAttribute : ValidationAttribute
        {
            private readonly List<string> _types;

            public FileTypesAttribute(string types)
            {
                _types = types.Split(',').ToList();
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                var fileExt = System.IO.Path.GetExtension((value as HttpPostedFileBase).FileName).Substring(1);
                return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types));
            }
        }


Step 1 :  Create File Upload Controller & View 


We will store profile pic and cover photo in two different directory. 

Controller


public class FileUploadController : Controller
    {
        // GET: FileUpload
        public ActionResult Index()
        {

            return View();
        }

        // HTTP Post Method
        [HttpPost]
        public ActionResult Index(FileUploadModel objfileModel)
        {

            if (ModelState.IsValid)
            {
                if (objfileModel != null && objfileModel.ProfilePic != null && objfileModel.ProfilePic.ContentLength > 0)
                {
                    var ProfilePicName = Path.GetFileName(objfileModel.ProfilePic.FileName);
                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\ProfilePic\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\ProfilePic\\"));
                    }
                    objfileModel.ProfilePic.SaveAs(Server.MapPath("~\\Uploads\\ProfilePic\\" + ProfilePicName));

                }

                if (objfileModel != null && objfileModel.CoverPhoto != null && objfileModel.CoverPhoto.ContentLength > 0)
                {
                    var CoverPicName = Path.GetFileName(objfileModel.CoverPhoto.FileName);

                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\CoverPhoto\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\CoverPhoto\\"));
                    }
                    objfileModel.CoverPhoto.SaveAs(Server.MapPath("~\\Uploads\\CoverPhoto\\" + CoverPicName));

                }
                ViewBag.Message = "Upload successfully";
                return RedirectToAction("Index");
            }
            else
            {

                ViewBag.Message = "Error during Upload";
                return View();
                
            }

        }
        
    }


Views


@model  WebApplication1.Models.FileUploadModel
@{
    Layout = null;
}

<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
    .input-validation-error {
        border: 1px solid #ff0000;
        background-color: #e96363;
    }

     .field-validation-error {
        color: #ff0000;
    }

    .field-validation-valid {
        display: none;
    }

    .input-validation-error {
        border: 1px solid ##ff0000;
        background-color: ##FF0000;
    }

    .validation-summary-errors {
        font-weight: bold;
        color: #ff0000;
    }

    .validation-summary-valid {
        display: none;
    }

</style>

<div class="container">
    <h2>File Upload Control Using Strongly Bind Model</h2>
    @using (Html.BeginForm("Index", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span>@ViewBag.Message</span>
        <form>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.ProfilePic)  &nbsp;</span>
                @Html.TextBoxFor(m => m.ProfilePic, new { type = "file" ,@class="custom-file-input" })
                @Html.ValidationMessageFor(m => m.ProfilePic) <br />
            </div>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.CoverPhoto) &nbsp;</span>
                @Html.TextBoxFor(m => m.CoverPhoto, new { type = "file" })
                @Html.ValidationMessageFor(m => m.CoverPhoto)
            </div>


            <input type="submit" value="Upload" class="btn btn-default" />
        </form>
    }


</div>








Sunday, November 12, 2017

Calling / Consume a Web API using HttpClient in c# with Example

Calling / Consume a Web API using HttpClient in c# 

Step 1 :  Open Visual Studio  Add new Console application.

We will create a client Application which will consume GET & POST method.





Step 2 :   Add Reference System.Net.Http.HttpClient.  for  use HttpClient 


We are using HttpClient to  sending and receive Http request -responses. we need to add below two reference in console application for call Web Api  using HttpClient .

System.Net,Http;              
System.Web.Exension;     // used for Deserialize   

Step 3 :  Create a helper class 

We will create a method for consume GET & POST  API using c#.  we are using generic types for maximize code reuse, type safety and performance.  




#region Helper Class
    public class clsHelper
    {

        public ClsAPIResponse CallAPI<U, P, T>(U url, P param, T type)
        {

            HttpClient client = new HttpClient();
            ClsAPIResponse objresponse = new ClsAPIResponse();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            dynamic response;
            if (type.ToString() == MethodTypes.POST.ToString())
            {
                response = client.PostAsync(url.ToString(), new StringContent(new JavaScriptSerializer().Serialize(param), Encoding.UTF8, "application/json")).Result;
            }
            else if (type.ToString() == MethodTypes.GET.ToString())
            {
                response = client.GetAsync(url.ToString()).Result;

            }
            else
            {
                response = client.PostAsync(url.ToString(), new StringContent(new JavaScriptSerializer().Serialize(param), Encoding.UTF8, "application/json")).Result;
            }


            var contents = response.Content.ReadAsStringAsync();

            // Bind Response. 

            objresponse.StatusCode = (int)response.StatusCode;
            objresponse.Message = response.ReasonPhrase.ToString();
            objresponse.ResponseString = contents.Result.ToString().TrimStart('\"').TrimEnd('\"').Replace("\\", "");



            return objresponse;
        }

        public enum MethodTypes { GET, POST, PUT, DELETE };

        public class ClsAPIResponse
        {
            public int StatusCode { get; set; }

            public string Message { get; set; }

            public string ResponseString { get; set; }


        }
    }
    #endregion





Step 4 :  Create a classes for GET & Post




#region Classes For Post Method
    public class clsInput
    {
        public string name { get; set; }
        public string job { get; set; }
    }

    public class clsPostResponse
    {
        public string name { get; set; }
        public string job { get; set; }
        public string id { get; set; }
        public DateTime createdAt { get; set; }
    }

    #endregion

    #region Classes For Get Method
    public class clsGetResponseData
    {
        public int id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string avatar { get; set; }
    }

    public class clsGetResponse
    {
        public clsGetResponseData data { get; set; }
    }
    #endregion




Step 5 :  Call GET & POST Method Using HttpClient.

we are using "reqres.in" API for demo purpose.  




static void Main(string[] args)
        {

            clsHelper obj = new clsHelper();

            #region PostMethod
            // 1. For Post Method Call 

            clsHelper.ClsAPIResponse objPostResponse = new clsHelper.ClsAPIResponse();

            // Input 
            clsInput objinput = new clsInput();
            objinput.job = "morpheus";
            objinput.name = "leader";

            // Call Method 
            objPostResponse = obj.CallAPI<string, clsInput, clsHelper.MethodTypes>("https://reqres.in/api/users", objinput, clsHelper.MethodTypes.POST);
            clsPostResponse objPostResult = JsonConvert.DeserializeObject<clsPostResponse>(objPostResponse.ResponseString);
            #endregion

            #region GetMethod
            clsHelper.ClsAPIResponse objGetResponse = new clsHelper.ClsAPIResponse();
            objGetResponse = obj.CallAPI<string, clsInput, clsHelper.MethodTypes>("https://reqres.in/api/users/2", objinput, clsHelper.MethodTypes.GET);

            clsGetResponse objGetResult = JsonConvert.DeserializeObject<clsGetResponse>(objGetResponse.ResponseString);
            #endregion

        }







Featured Post