Friday, August 30, 2019

C# Tutorial - Tuple Type

C# Tuple type was introduced in .Net Framework 4.0 and a tuple is a data structure that contains a sequence of elements of different data types.
Basically it is very useful to return the multiple values from method without creating new type.


Creation of Tuple object:

Here is an example of Tuple type, which is holding employee information like employee ID, First Name and Last Name

Tuple<int, string, string> employee = new Tuple<int, string, string>(1, "Steve", "Bobs");

We can create an instance of the tuple by calling Create(T1,) method of static class Tuple.

Tuple<int, string, string> employee = Tuple.Create(1, "Steve", "Bobs");

tuple object stores data as collection of Item properties like Item1, Item2, Item3, Item4, Item5, Item6, Item7 and Rest, so max tuple can stores only 8 item in one dimension and if you want to store more elements, you need to use nested tuples

Here is an example of nested tuple,  how to store the employee information including address by using nested Tuple:

var emp = new Tuple<int, string, string, Tuple<string, string, string, string, string>>(1, "Steve", "Jobs", new Tuple<string, string, string, string, string>("Street Address","City","State","County","ZipCode"));

Access of Tuple Element:

The element of a tuple can be accessed by using element property like Item1, Item2.

Here is an example how to access the tuple data.

Tuple<int, string, string> employee = Tuple.Create(1, "Steve", " Bobs");

int employeeID = employee.Item1;
string firstName = employee.Item2;
string lastName = employee.Item3;


Tuple in a method:

A Tuple type can be used as a method parameter or return type of a method.

Here is an example of a method returns multiple value as a tuple type

public Tuple<int, string, string> GetEmployeeTuple(int employeeID, string FirstName, string LastName )
{
   Tuple<int, string, string> employee = Tuple.Create(employeeID, FirstName, LastName);
   return employee;
}


Thursday, August 29, 2019

JavaScript Class : The super and extends keywords

In blog, we learn about JavaScript class and how to implement inheritance by using supper and extends keyword

The keyword extends is used to implement the inheritance in JavaScript class and we can create a subclass or child class by using the ‘extends’ keyword. In inheritance, the child class is derived with base class and has own extra business logic.


Here is an example which demonstrates how to inherit Person Class and create an Employee Class.

  class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };

    class Employee extends Person {
        constructor(firstName, lastName, employeeID, department) {        
            super(firstName, lastName);
            this.employeeID = employeeID;
            this.department = department;
        }     
    };

The keyword ‘super’ is used to call the constructor method of base class. The child class has always a constructor method, it should call to super() method to invoke base class constructor method and initialize the properties of base class.

    var _person = new Employee("Henry", "Ford", 100, "IT");

    console.log(_person.name()); 
    console.log(_person.department);

Console message:

Henry Ford
IT

Introduction to JavaScript class


A JavaScript class is a type of function. Classes are declared with the class keyword, and always add a constructor method and this constructor method is called each time when the class object is initialized

Defining a Class:

We use keyword Class to create a class.

Here is an example which demonstrates how to define the class “Person”

  class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }
    }


As we know, the constructor method always be called, when the class Person will be initialized.

We will create an instance of Person Class by using the new keyword, and can pass values through constructor.

 var _person = new Person("Henry", "Ford");

Here is a complete example (HTML & JS)

<h2>JavaScript Class - Demo</h2>

<p id="personDiv"></p>

<script>
    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }
    };

    var _person = new Person("Henry", "Ford");
    document.getElementById("personDiv").innerHTML = _person.firstName;

</script>

Defining a Method:

The constructor of class is a default of method, it is used to initialize the class properties. You can define own custom method.

Here is an example which demonstrates how to define method name() in Person class to get person’s full name

    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };


Inheritance - Extending a Class:

We use keyword extends to implement class inheritance and derived class inherits all properties and method of base class.

We use keyword super to call the constructor method of base class or parent class.

Here is an example which demonstrates how to inherit Person Class and create an Employee Class.

https://d.adroll.com/cm/aol/out?adroll_fpc=dadc06851b6c20ac88ab6464b1659917-1567086153020&xid_ch=f&advertisable=S4BPDI4QWNB57PEKEZSLIPclass Employee extends Person {
        constructor(firstName, lastName, employeeID, department) {        
            super(firstName, lastName);
            this.employeeID = employeeID;
            this.department = department;
        }     
    };
Here is a complete example (HTML & JS)

<h2>JavaScript Class - Demo</h2>

<p id="personDiv"></p>
<p id="personDepartment"></p>
<p id="personEmpID"></p>

<script>
    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };

    class Employee extends Person {
        constructor(firstName, lastName, employeeID, department) {        
            super(firstName, lastName);
            this.employeeID = employeeID;
            this.department = department;
        }     
    };
   

    _person = new Employee("Henry", "Ford", 100, "IT");

    document.getElementById("personDiv").innerHTML = _person.name();
    document.getElementById("personDepartment").innerHTML = _person.department;
    document.getElementById("personEmpID").innerHTML = _person.employeeID;
</script>

Tuesday, August 27, 2019

ASP.NET Web API Action Filter with parameters

Bascailly Web API Action Filter is used to add extra logic before or after action method execute, it could be used for authentication, authorization and logging.


Pass the single parameter to Action Filters:

Here is a custom action filter, which is used to authorize the request based on supplied token and accepts single value for Role property

Custom Action Filter:

public class RestrictedAction : ActionFilterAttribute
    {
        public string Role { get; set; }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Unauthorized Access");
            }

            base.OnActionExecuting(actionContext);
        }
    }


Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
        [RestrictedAction(Role="Admin")]
        public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create a Order");
            }
            return Ok(order);
        }


Pass the multiple parameters to Action Filters:

Here is a custom action filter which accepts collections of values for Role property and error message string

Custom Action Filter:

  public class RestrictedAction : ActionFilterAttribute
    {
        public [] string Role { get; set; }

   public string ErrorMessage { get; set; }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, ErrorMessage);
            }

            base.OnActionExecuting(actionContext);
        }
    }

Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
   [RestrictedAction(Role= new string[] { "Admin", "IT" },ErrorMessage= "Unauthorized Access")]       
public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create an Order");
            }
            return Ok(order);
        }

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...