Tuesday, December 8, 2015

Difference Between ViewData, ViewBag and TempData with Example

Introduction:
In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance. This article explains the differences among ViewData, ViewBag and TempData.

Difference Between ViewData, ViewBag and TempData with Example


ViewData

    1- ViewData is used to pass data from controller to view
    2- It is derived from ViewDataDictionary class
    3- It is available for the current request only
    4- Requires typecasting for complex data type and checks for null values to avoid error
    5- If redirection occurs, then its value becomes null

Example:- 
In controller

public ActionResult Index()
{
    ViewData["Name"] = "Vepsh Tech";
    return View();
} 

In View

@ViewData["Name"]


ViewBag

    ViewBag is also used to pass data from the controller to the respective view
    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
    It is also available for the current request only
    If redirection occurs, then its value becomes null
    Doesn’t require typecasting for complex data type

Example:-
In Controller 

public ActionResult Index()
{
    ViewBag.Name = "Vepsh Tech";
    return View();
}

In View

@ViewBag.Name 

TempData

    1- TempData is derived from TempDataDictionary class
    2- TempData is used to pass data from the current request to the next request
    3- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
    4- It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

Example:-

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}

Monday, December 7, 2015

Understanding jQuery Ajax - to async or not ?

Introduction:
This article explains a clear understanding on making synchronous and asynchronous ajax calls through jQuery ajax method. After going through it you can have a clear idea on how and when to do asynchronous ajax calls.

Ajax(Asynchronous Javascript + XML) is a new approach now a days very popular in web development.
Ajax taken our classic web development to a different level. It is a new approach to create
fast and dynamic web pages.It toally removed the reloading part from the classical web development.

There are many Ajax methods provided by jQuery library to accomplish ajax calls as listed below :-
get
post
getScript
getJSON
ajax

These all ajax methods can be used as per requirements you are having but, if you need extensive configurability and want to handle errors by yourself then '.ajax()' method is the best.

To work with the jQuery ajax method we need to set the options available for it properly, from which
'async' is an important setting about which we are going to discuss here as setting its value will have a major impact in getting response properly.

As async is an boolean property, we can set either TRUE or FALSE value for it.
Here i will explain various scenarios on setting each values for the particular property(async) and to help you understanding its importance and usability by situation.

Example:
Here i am explaining simple examples how and when to make your choice in between asynchronous or synchronous ajax calls using jQuery.

Both methods independent of each other :-

There will be no impact on result if both are independent whether it is a asynchronous or synchronous ajax calls :-

$(function () {
    // When both the method are independent & async=false
    // Ajax call will happen one by one
    GetData1(false); // called first
    GetData2(false); // called after GetData1 method processing finished

    // When both the method are independent & async=true
    // Call will happen simultaneously
    GetData1(true); // Both are called simultaneously in different threads
    GetData2(true); // Both are called simultaneously in different threads
});

First Method:-

function GetData1(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData1",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second Method:-


function GetData2(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData2",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second method dependent on first one :-

But when second method is dependent on result supplied from first method it will definitely have impact

$(function(){
// When second method depends on result of the first method & async=false
// If it is a synchronous call then you can get 
the result from first method before the second method call
    var result = GetData3(false); 
// As second method will be called after first method execution completed 
// so proper result can be found in above method
    GetData4(false, result);

// When second method depends on result of the first method & async=true
// If it is an asynchronous call then both the calls will 
happen asynchrously/simultaneously and 
    // you will not get the result from first method before call of 
second method as happens in below example
    var result = GetData3(true); 
// As both the methods will be called simultaneously second method will be called 
// before first method returning the result and here it will get NULL value in result.
    GetData4(true, result);
});

First Method:-

function GetData3(isAsync) {
    var result = null;
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData3",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
    return result;
}

Second Method : Takes an extra argument which is the result of first method.

function GetData4(isAsync, result) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData4",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            if (result.id == 1) {
                var result = JSON.parse(response.d);
                // do your operation here
            }
            else alert('No operation required..');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Note-

This will definitely of help to the developers who started working on jQuery Ajax method. There are many scenarios and requirements, we need to understand the fundamentals so that we can make right choice one at right place.

How to find second highest or maximum salary of Employee in SQL - Interview question

Introduction:
In this section we will write SQL query to get second highest salary of Employee. Before writing query its good to be familiar with schema as well as data in table. Here is the Employee table we will be using this SQL example:

SQL query to find second maximum salary of Employee

How to find second highest or maximum salary of Employee in SQL - Interview question
If you look data, you will find that second maximum salary in this case is 6000 and employee name is Henry. Now let’s see some SQL example to find out this second maximum salary.

Second maximum salary using sub query and IN clause:
Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of subquery.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:
How to find second highest or maximum salary of Employee in SQL - Interview question
Both of above SQL example will work on all database including Oracle, MySQL, Sybase and SQL Server as they are written using standard SQL keywords. But sometime you can also use database specific features like TOP keyword of SQL Server or Sybase database to find out second highest salary of Employee.

Second highest salary using TOP keyword of Sybase or SQL Server database:
TOP keyword of Sybase and SQL Server database is used to select top record or row of any result set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as shown below.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is what this SQL query is doing : First find out top 2 salary from Employee  table and list them in descending order, Now second highest salary of employee is at top so just take that value. Though you need to keep in mind of using distinct keyword if there are more than one employee with top salary, because in that case same salary will be repeated and TOP 2 may list same salary twice.

Second maximum salary using LIMIT keyword of MYSQL database:
LIMIT keyword of MySQL database is little bit similar with TOP keyword of SQL Server database and allows to take only certain rows from result set. If you look at below SQL example, its very much similar to SQL Server TOP keyword example.
How to find second highest or maximum salary of Employee in SQL - Interview question
That’s on How to find second highest salary of Employee using SQL query.



Friday, December 4, 2015

Basic SQL Query that Frequently asked in Interview Questions

Introduction:
In this article, I am giving some examples of SQL queries which is frequently asked when you go for a programming interview, having one or two year experience on this field.

These queries test your SQL skill on Joins, both INNER and OUTER join, filtering records by using WHERE and HAVING clause, grouping records using GROUP BY clause, calculating sum, average and counting records using aggregate function like AVG(), SUM() and COUNT(), searching records using wildcards in LIKE operator, searching records in a bound using BETWEEN and IN clause, DATE and TIME queries etc. If you have faced any interesting SQL query or you have any problem and searching for the solution, you can post it here for everyone's benefit.

SQL Query Interview Questions and Answers

Question 1: SQL Query to find second highest salary of Employee
Answer: There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery:

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Emp

Question 2: SQL Query to find Max Salary from each department.
Answer: You can find the maximum salary for each department by grouping all records by DeptId and then using MAX() function to calculate maximum salary in each group or each department.

SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID.

These questions become more interesting if Interviewer will ask you to print department name instead of department id, in that case, you need to join Employee table with Department using foreign key DeptID, make sure you do LEFT or RIGHT OUTER JOIN to include departments without any employee as well.  Here is the query

SELECT DeptName, MAX(Salary) FROM Employee e 
RIGHT JOIN Department d ON e.DeptId = d.DeptID GROUP BY DeptName;

In this query, we have used RIGHT OUTER JOIN because we need the name of the department from Department table which is on the right side of JOIN clause, even if there is no reference of dept_id on Employee table.

Question 3: Write SQL Query to display the current date.
Answer: SQL has built-in function called GetDate() which returns the current timestamp. This will work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent functions.

SELECT GetDate();

Question 4: Write an SQL Query to check whether date passed to Query is the date of given format or not.
Answer: SQL has IsDate() function which is used to check passed value is a date or not of specified format, it returns 1(true) or 0(false) accordingly. Remember ISDATE() is an MSSQL function and it may not work on Oracle, MySQL or any other database but there would be something similar.

SELECT  ISDATE('1/08/13') AS "MM/DD/YY"; 

It will return 0 because passed date is not in correct format. 

Question 5: Write an SQL Query to print the name of the distinct employee whose DOB is between 01/01/1960 to 31/12/1975.
Answer: This SQL query is tricky, but you can use BETWEEN clause to get all records whose date fall between two dates.

SELECT DISTINCT EmpName FROM Employees 
WHERE DOB  BETWEEN 01/01/1960 AND 31/12/1975;

Question 6: Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.
Answer :

SELECT COUNT(*), sex from Employees  
WHERE  DOB BETWEEN '01/01/1960' AND '31/12/1975' GROUP BY sex;

Question 7: Write an SQL Query to find an employee whose Salary is equal or greater than 10000.
Answer :

SELECT EmpName FROM  Employees WHERE  Salary>=10000;

Question 8: Write an SQL Query to find name of employee whose name Start with ‘M’
Answer :

SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of whether it was stored as JOE, Joe, or joe.
Answer :

SELECT * from Employees  WHERE  UPPER(EmpName) like '%JOE%';

Question 10: Write an SQL Query to find  the year from date.
Answer:  Here is how you can find Year from a Date in SQL Server 2008

SELECT YEAR(GETDATE()) as "Year";





Wednesday, December 2, 2015

Is MVC a design pattern or an architectural pattern?

Is MVC a design pattern or an architectural pattern?
Introduction:
MVC which stands for Model-View-Controller describes a software pattern that you can use in interactive computer systems. To understand if it is a design pattern or an architectural pattern, let's look at what these two are:

Architectural pattern: Concerned with the subsystems of an application with their relationships and collaborations with each other.
Design pattern: Concerned with the (further small) components of a subsystem with their relationships and collaborations with each other.

MVC is a pattern that you can use in both ways (as architectural or design) and ample amounts of real world cases where the pattern is used in both these worlds can be found.

MVC as an architectural pattern
Here the core functionality and data of an application are abstracted as the model. You have one or more views and one or more controllers collectively representing the user interface. A view is responsible for displaying information to the user. A controller is responsible for accepting user inputs, interpret them to understand what should be done and act accordingly (for example update data or invoke a functionality of the model).

A real world example is the implementation of a web application that follows the MVC architectural pattern. Many such web application frameworks exists. The key is that an application is broken down into components (call them subsystems) by the MVC pattern.

MVC as an architectural pattern
MVC architectural of a web application

MVC as a design pattern
Consider the many UI widget libraries available out there where MVC is used as a design pattern to implement widgets. Take for example the JSlider class (in Java Swing library). A JSlider instance represents a slider widget where a user can move the knob of the slider to change its position. JSlider is implemented as follows:

MVC as a design pattern
MVC design pattern

Note that in Java Swing library the xxxUI classes capture both the view and controller aspects of a widget. It's slightly different from MVC and Swing creators call this “separable model architecture”. For the purpose of this discussion, just don't care about this difference.

Here the model (BoundedRangeModel) doesn't represent the core functionality or data of the application. It's limited to represent the data (state) of the slider widget (Models of complex widgets may implement some amount of model specific functionality.). SliderUI's view related code is responsible for painting the slider (the background, knob,...). SliderUI's controller is responsible for interpreting a mouse click-and-drag as a semantic event that represents a slider position change. Accordingly the controller related code goes about updating the model. And then the view goes about painting the knob at a different position.

The scope of the MVC pattern here is just limited to implementing a slider widget. Would you call it architectural? I would not since I cannot consider the slider a collection of subsystems of an application. With the frame or reference set to a typical application, you wouldn't even recognize it as a top level subsystem. It's more appropriate to consider it a low level subsystem or a component and hence the MVC manifests as a design pattern in this context (Read initial paragraphs - What is considered a design pattern?).

Confusion:
Why is that the Swing creators gave the name “separable model architecture” to their widget design pattern? Probably because what is considered architectural itself is a question that leads to multiple explanations.

One such explanation is that if something (a quality, design aspect,.. ) is found spread throughout a system, it's considered architectural. That's a different way to think about architecture which is not the same as what I mentioned at the beginning of this article (See the description of a architectural pattern). Probably that's one reason why Swing creators used “architecture” in their pattern since it's found throughout the Swing library.

Yet another reason that I can think of is that they just focused on the UI “system”.

Fair  enough. Let's not argue. We understand what is what. Based on the first given description, this widget design pattern cannot be considered an architectural pattern.

Conclusion:

MVC can either be used as an architectural pattern or a design pattern.