Tuesday, 1 October 2019

Difference between rest and restful

REST based Services/Architecture VC RESTFUL Services/Architecture

To differentiate or compare these 2, you should know what is REST.
REST (REpresentational State Transfer) is basically an architectural style of development having some principles...
  • It should be stateless
  • It should access all the resources from the server using only URI
  • It does not have inbuilt encryption
  • It does not have session
  • It uses one and only one protocol that is HTTP
  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete
  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )
REST based services follow some of the above principles and not all
RESTFUL services means it follows all the above principles.
It is similar to the concept of:
Object-based languages supports all the OOPs concepts, examples: C++, C#
Object oriented languages supports some of the OOPs features, examples: JavaScript, VB

Example:
ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul.
MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.
MVC only supports the following from the REST API
  • We can access the resource using URI
  • It supports the HTTP verb to access the resource from server
  • It can return the results in the form of JSON, XML, that is the HTTPResponse.
However, at the same time in MVC
  • We can use the session
  • We can make it stateful
  • We can return video or image from the controller action method which basically violates the REST principles
That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

Thursday, 26 September 2019

Difference between subquery and corelated query in sql server

The difference between correlated and regular subquery is also a frequently asked SQL interview question. Mostly asked on telephonic interview where they cannot ask you to solve query and check the fundamentals and theoretical concepts.

In this article, I am going to compare correlated subquery with the regular one of different parameters e.g. their working, speed, performance, and dependency. I'll also give you a good example of correlated subquery e.g. the Nth highest salary problem and explain how exactly it solves the problem.

So, if interviewer ask you to find the 4th highest salary then there can only be at most 4 salary which are equal to or greater than the 4th highest salary.  This is just an example, you can use correlated subquery to solve many such problems in the world of data and SQL.

In short, here are the main difference between correlated and non-correlated subqueries in SQL

Working - 

A non-correlated subquery is executed only once and its result can be swapped back for a query, on the other hand, a correlated subquery executed multiple times, precisely once for each row returned by the outer query.

For example, following query is an example of non-correlated subquery:

SELECT MAX(Salary) FROM Employee 
WHERE Salary NOT IN ( SELECT MAX(Salary) FROM Employee)


Here the subquery is SELECT MAX(Salary) from Employee, you can execute and substitute the result of that query e.g. if subquery return 10000 then outer query is reduced to

SELECT MAX(Salary) from Employee where Salary NOT IN (10000). 


This is not possible with a correlated subquery, which needs to be executed multiple times as shown below:

SELECT e.Name, e.Salary FROM Employee e
WHERE 2 = (
SELECT COUNT(Salary) FROM Employee p WHERE p.salary >= e.salary)


In this example, the subquery is SELECT COUNT(Salary) FROM Employee p WHERE p.salary >= e.salary, you cannot swap it's value for the outer query because it needs to be executed for each employee.

Let's say the first row of employee has salary 5000, in this case, e.salary will be 500 and subquery will be

SELECT COUNT(Salary) FROM Employee p WHERE p.salary >= 5000

and subquery will find how many salaries are higher than 5000 if count return 2 then it's the second highest salary. This logic needs to be executed for each row outer query will process.

Tuesday, 24 September 2019

Difference between PUT and POST in REST WebService

If you remember REST WebServices uses HTTP methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. Even though both PUT and POST methods can be used to perform create and update operation in REST WebServices, Idempotency is the main difference between PUT and POST. Similar to the GET request, PUT request is also idempotent in HTTP, which means it will produce the same results if executed once more multiple times. Another practical difference PUT and POST method in the context of REST WebService are that POST is often used to create a new entity, and PUT is often used to update an existing entity. If you replace an existing entity using PUT than you should be aware that if only a subset of data elements is passed then the rest will be replaced by empty or null.

There is also another theory which says that for creating new things, you should use PUT if the unique identifier is provided by client i.e. client is responsible for creating entity e.g. client can create resource /user/joe/ by providing username joe and that would be unique URI. Similar, use POST if the server is responsible for creating new resources e.g. if ID is part of URI and automatically created by the server.

Let's see a couple of more differences between PUT and POST in REST WebServices.


PUT vs POST in REST WebService 

As I said, even though both PUT and POST can be used to create and update an entity, POST is usually preferred for creating and PUT is preferred for updating an existing entity.

For example, to create a new Order you should use:

POST /orders

and to update an existing order, you should use

PUT /orders/13892

which means modify the order with OrderId 13892

If you execute POST request multiple times, it will end up create that many orders, but when you execute PUT it will always produce the same result because of its idempotent. You should also remember that both PUT and POST are unsafe methods. Safe methods in HTTP do not modify the resource in the server e..g GET or HEAD, while Idempotent HTTP methods return same result irrespective of how many times you call them.


When to use PUT and POST methods in REST?

Now' it's time for some practical knowledge about when to use the PUT and POST methods to call RESTful WebServices.

1) You should use POST to create new resources and PUT to update existing resources.

2) Use PUT when you know the "id" of the object e.g. Order, Book, Employee

3) Use POST when you need the server to be in control of URL generation of your resources.

4) Examples
PUT /items/1 update
POST /items create

You can further read REST in Practice book to learn more guidelines about designing a RESTful API. Sometimes reading a couple of books on the topic help to reduce confusion.

Btw, there is also another theory, which states that if the client is responsible for creating the ID's of the resource, use PUT to create new things e.g.

PUT /users/john

Here John is unique and given by the client, this is a new URI.

Similarly, if server is responsible for creating the ID's of the new resources then use POST, for example

POST /users/

Now, POST will carry a key and value which client uses to send username=john and ID will be automatically generated by Server.




That's all about the difference between PUT and POST HTTP methods in REST WebServices. You should remember even though both PUT and POST are not safe methods, PUT is idempotent. Which means it will return the same result even if you call multiple times. The general advice is that POST is used to create new objects and PUT is used to update existing objects.















Monday, 23 September 2019

What is Anonymous method

C# - Anonymous Method

As the name suggests, an anonymous method is a method without a name. Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of delegate type.
Example -
public delegate void Print(int value);

static void Main(string[] args)
{
    Print print = delegate(int val) { 
        Console.WriteLine("Inside Anonymous method. Value: {0}", val); 
    };

    print(100);
}

Output: Inside Anonymous method. Value: 100
Anonymous methods can access variables defined in an outer function.
Example -
public delegate void Print(int value);

static void Main(string[] args)
{
    int i = 10;
    
    Print prnt = delegate(int val) {
        val += i;
        Console.WriteLine("Anonymous method: {0}", val); 
    };

    prnt(100);
}
Output: Anonymous method: 110
Anonymous methods can also be passed to a method that accepts the delegate as a parameter.
In the following example, PrintHelperMethod() takes the first parameters of the Print delegate:
Example - Anonymous method with Parameter-
public delegate void Print(int value);

class Program
{
    public static void PrintHelperMethod(Print printDel,int val)
    { 
        val += 10;
        printDel(val);
    }

    static void Main(string[] args)
    {
        PrintHelperMethod(delegate(int val) { 
      Console.WriteLine("Anonymous method: {0}", val); }, 100);
    }
}

Output - Anonymous method: 110
Anonymous methods can be used as event handlers:
Example - Anonymous method with Parameter as Event handler
saveButton.Click += delegate(Object o, EventArgs e)
{ 
    System.Windows.Forms.MessageBox.Show("Save Successfully!"); 
};

Anonymous Method Limitations

  • It cannot contain jump statement like goto, break or continue.
  • It cannot access ref or out parameter of an outer method.
  • It cannot have or access unsafe code.
  • It cannot be used on the left side of the is operator.
  1. Anonymous method can be defined using the delegate keyword
  2. Anonymous method must be assigned to a delegate.
  3. Anonymous method can access outer variables or functions.
  4. Anonymous method can be passed as a parameter.
  5. Anonymous method can be used as event handlers.
Other Example -

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

namespace AnonymousFunction
{
    //sample example of single cast deligate invocation

    class Program
    {
        delegate int SampleDeligate(int x);

        static void Main(string[] args)
        {
            //SampleDeligate del = Show;
            //Or,
            SampleDeligate del = new SampleDeligate(Show);
            Console.WriteLine(del(20));
            Console.ReadLine();
        }

        static int Show(int x)
        {
            return x;
        }
    }

    //Anonymous function are known as un-named method which do not have 
    any name defined
    //Anonymous function is created by using deligate

    class Program
    {
        delegate double CalculateAreaDeligate(int r);

        static void Main(string[] args)
        {
           
            CalculateAreaDeligate del = new CalculateAreaDeligate(
                                         delegate(int r) //unnamed method
                                         {
                                             return 3.14 * r * r;
                                         }
                                        );

            Console.WriteLine(del(20));

            //by lamda expression
            CalculateAreaDeligate del1 = r => (3.14 * r * r);

            Console.WriteLine(del1(40));

            Console.ReadLine();
        }
    }
}


Thursday, 12 September 2019

How to filter records from one list to another list

 employeeList  has 5 employee records so to filter only those empoyees name having in employeeList2 -

List<Employee> employeeList = new List<Employee>() { new Employee() { Name = "Ashish"},
             new Employee() { Name = "Aman"},
             new Employee() { Name = "Soni"},
             new Employee() { Name = "Akash"},
             new Employee() { Name = "Rahul"},
             new Employee() { Name = "Mukesh"}};

            var employeeList2 = new List<Employee>() { new Employee() { Name = "Ashish"}, new Employee() { Name = "Mukesh" } };


            var filterData =  employeeList.Where(x => employeeList2.Any(y => y.Name.Equals(x.Name)));

Output - Ashish and Mukesh records

difference between caching and session

  1. Session data is stored at the user level but caching data is stored at the application level and shared by all the users.
  2. Sessions may not improve performance whereas Cache will improve site performance.
  3. Items in cache can expire after given time to cache while items in session will stay till session expires.
  4. Sessions may change from user to user whereas a single Cache will be maintained for the entire application.
  5. Cache wont maintain any state, whereas Sessions will maintain separate state for every user.
OR,

As we all know Session, Application and Cache are State Management Techniques. We have two types of State Management Techniques:
  1. Client Side
  2. Server Side
So Session and Application are server-side techniques and Cache works on the client side as well as the server side, in other words thereby all these three stores the information on the server (since browsers are stateless) and these are widely used in ASP.Net applications. The question now arises of when and where do we need to use all these. So before using them we should know what the uses of these techniques are. Let's start with sessions.

1. Session: A Session is basically used to store user-specific information. Typically you save username, email ID, Department and so on and this information cannot be shared by another user.
2. Application: As in the preceding snapshots you see that the Application and Cache values are the same all over the application. Basically we use a static value in the Application Object that we want to show somewhere in the application that will be visible for every form in the Application.

We can use the Application Object in the global.asax file.

The Application Object maintains its data until the web application is shut down or we release the data manually by assigning null or call the Clear() method. The Application Object does not have any timeout.

Basically we use The Application Object to hit a counter on the Application, or read a readonly file or table to display in various web pages.

3. Cache: A Cache is very useful in web applications for performance optimization. Since application data can only be stored on the server, Cache data is stored on both the client side as well as the server side. We can define the time period for the cache using the Cache.Insert() or Cache.Add() method and the time period can be assigned from seconds to years. We even can maintain an absolute time expiration for the Cache.

We can assign value in the Cache only from web forms, not from the global.asax (we only can pass in the case of the Application and Session) file.

We retrieve the Cache data from the Cache without repeating the full cycle, which doesn't happen in the case of the Application.

And we can use the Cache if we want to calculate the time the user was logged in. Or if we are giving an online examination, then we can maintain the questions in the cache and retrieve them from there for better performance.
Or,

1. In Session after storing the session, when you copy the URL and paste it into another browser then you can't access the URL but when you do that for caching, in other words after storing into the cache variable, it can be accessed by a different user also.
So now we can say that a session has user-level storage on the server but caching has application-level storage on the server.

2. A session has a relative or sliding expiration, in other words by default a session has an expiration time of 20 minutes, but an application that is not being used will be relatively increased, in other words if the user is not using that application for more than 20 minutes then the session will be automatically expired and if the user is not using it then the time will be relatively increased, well we can also provide a custom time of session expiration. But caching has 2 types of expiration as in the following:
  1. Absolute Expiration
  2. Relative Expiration or Sliding Expiration 
Absolute expiration means in caching the cache memory will be deleted after a fixed amount of time, the same as for cookies
Sliding expiration means in caching the cache memory will be deleted after a fixed amount of time if that memory is not in use, if it is used in that specific time then it can be relatively increased. the same as for a session.

1. How to provide Absolute Expiration in caching
  1. Cache.Insert("Uname", txtUser.Text, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero); 

2. How to provide Sliding Expiration in caching
  1. Cache.Insert("Uname", txtUser.Text, null, DateTime.MaxValue, TimeSpan.FromSeconds(20));

Tuesday, 23 April 2019

Difference between == and Equals() in c#

= = operator  compares if object references are same
.Equals() method compares if the contents are same not the object references
In case of string, it always compares on contents not the object references

Example: -

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

namespace ConsoleAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //case-1
            string name = "Ashish";
            string myName = name;

            Console.WriteLine("== operator result is {0}", name == myName); // True
            Console.WriteLine("Equals method result is {0}", name.Equals(myName)); // True

            //case-2
            object name1 = "sandeep";
            char[] values = { 's', 'a', 'n', 'd', 'e', 'e', 'p' };
            object myName1 = new string(values);
            Console.WriteLine("== operator result is {0}", name1 == myName1); //False
            Console.WriteLine("Equals method result is {0}", myName1.Equals(name1)); // True

            //case-3
            string name2 = "sandeep";
            char[] values2 = { 's', 'a', 'n', 'd', 'e', 'e', 'p' };
            string myName2 = new string(values2);
            Console.WriteLine("== operator result is {0}", name2 == myName2); //True
            Console.WriteLine("Equals method result is {0}", myName2.Equals(name2)); // True

            //case-3
            string name3 = "sandeep";
            string myName3 = null;
            Console.WriteLine("== operator result is {0}", name3 == myName3); //False
            Console.WriteLine("Equals method result is {0}", myName3.Equals(name3)); // Throw error


            Console.ReadKey();
        }
    }
}