Saturday, March 25, 2017

New features of SQL 2016



SQL Server 2016 was (finally) released on June 1st, 2016 with an initial build number of 13.0.1601.5. Microsoft build SQL 2016 keeps a lot of things in mind like Cloud first, Security enhancement, JSON support, Temporal database support, Row level security, Windows server 2016 connectivity, Non-relational database connectivity (e.g. Hadoop), rich visual effects, etc.
In this article, we will take a walk-through all fresh SQL 2016 features and cover them one by one.

Always Encrypted

 As the word suggests, 'Always Encrypted' feature of SQL 2016 'Always' keeps your sensitive data 'Encrypted' either at rest (local environment) or at remote (Cloud/Azure). It will help to protect data from people who may play around it like DBAs, Cloud operators, high-privileged but unauthorized users.
How It Works
You can set Always Encrypted to individual column (where your sensitive data resides). While configuring columns, you need to specify encryption algorithm and cryptographic keys for data protection. There are basically two keys you need to define:
  1. Encryption Key for column data encryption (It will be used to encrypt data for specific column)
  2. Master Key: for Encryption of column encryption keys
So basically, it's a double encryption protection, only program can access it, client application will automatically encrypt and decrypt data before fetching data from database

JSON Support

SQL 2016 gives direct support to JSON (Java Script Object Notation), SQL has the facility to read JSON format data, load them in table, support index properties in JSON columns.
JSON data will be stored in NVARCHAR type. Due to NVARCHAR type, an application has the following benefits:
  • Already stored JSON data (as text) can be easily migrated on new feature.
  • As NVARCHAR is supported by all SQL components so is the JSON too.
You can easily fetch data FOR JSON from SQL with the below syntax:

SELECT column, expression, column as alias
FROM table1, table2, table3

It is a SELECT command so when we fire the above query, SQL will format each row/cell value and return as JSON object.
SQL has also provided in-built functions for JSON.

Dynamic Data Masking

This is again one of the security features of SQL 2016. As the name suggests, it just wraps MASK on your data, in short, it hides your confidential data that you don't want to display. It just avoids disclosure of your sensitive data.
After masking, SQL User with limited rights will not view original text, he can view only Masked Text, SQL has pre-defined masking functions you just need to apply it on different columns, see below:

Sr NoFunctionsApplied onPlain text (Input)Masking text(output)
1DefaultString, NumberABCDxxxx
4Custom StringTextRABBITRXXXX

To apply this on specific columns, you just need to ALTER column with 'MASKED WITH' function name, see below syntax:

//here I used function as Default(), you can change it to any of the above types
ALTER TABLE tablename ALTER COLUMN columnname MASKED WITH (FUNCTION=‚default()‘)

Row Level Security  

This is again one of the security features of SQL 2016. It allows you to secure your data row wise, in short you can define a row, that will be viewed by a particular SQL user only. So depending upon the SQL user access permission, we can restrict row level data, e.g., we can ensure if employees can view only their department data though department table is the same.
To implement Row level security, you need to define Security policy with a predicate and function.
Security policy:
We need to create a policy for security, here is simple syntax:


In the above syntax, FILTER and BLOCK are the predicates that will either FILTER rows and display only those that are available for read or BLOCK rows for write operation.

Function: Function is a simple user defined function, but here are some restrictions for user defined function that are used in Row Level Security syntax:
  • Database modification operations are not allowed
  • OUTPUT INTO clause is not allowed in function
  • Multiple result set should not be returned from function 

Stretch Database

As the name suggests, it gives flexibility to the user. In short, we can store portion of database to remote (Here, we can say cloud/Azure). The portion of data can be called as COLD DATA. (It is useful for those where transactional data needs to be keep for long time as industry requirement.) So we can say it's a cost-effective solution for COLD data storage, your data is available anytime for query and manage. You can access your data without changing queries either it is present on local or at stretch database.
To configure it, you need an Azure account and database instance that you need to stretch. The following snap will clear your idea.


Multiple TempDB

It is always a good practice to have a Multiple Temp data files, if you are working on a big crucial data, up till now (SQL 2014), you need to manually add temp db files to your database but SQL 2016 provides you temp DB configuration settings, in which you can configure Number of TempDB files at the time of SQL installation. Default number of files are 8 with default size of 64 MB will be given.
So you no longer need to configure/create it manually.

Query Store

Up till now, to check Query plan and execution statistics, we need dynamic management views in SQL but neither will it give you Query plan that executed by past/old queries nor will it store them anywhere so that you can review, but SQL 2016 provides you 'Query Store' that takes you through query plan, statistics and Query execution for current and past queries.
To enable it, just right click on database (obviously, you need SQL 2016 SSMS), go to properties. You will see 'Query store' at the left corner, select it and click on Enable 'true' or you can do it using Query as follows:


Temporal Table

Do you want to store history of your SQL table? So you want to review your old records after table updation? Then you can go with this features. SQL 2016 provides record version facility in which it keeps a history of changed record and maintains it for timely analysis. This feature can be useful for Audit, checking data trend, accidental update/delete data and many more.

How It Works

Basically, the system keeps pair of a table for history and adds two additional columns in it named 'SysStartTime' and 'SysEndTime' for start time and end time for row respectively. Live table contains current record of row, whereas history table contains previous record of row. We can fetch data from History table, with the following query:

BETWEEN date1 AND date2
WHERE condition; 

R Introduction

Have you stored statistical data in SQL? Want to use R to analyze it? You export data each time from SQL to R? Then your headache will now be covered in SQL 2016, because it is now with R. You can run R script on SQL. You need to install this feature at the time of SQL setup.

We cannot cover all features in details, maybe I will be planning soon to cover them one by one.
Till then, you can enjoy this article.
Suggestion and queries are always welcome.

Happy querying!

**This article is already published at CodeProject

Thursday, February 16, 2017

Difference between Build, Rebuild and Clean

This article gives you explanation about Difference between Build, Rebuild and Clean

If you are using Visual studio you might have question that what is difference between Build, Rebuild and Clean ? here we are going to understand the diversity between them.

Build :
 When we build any solution then Visual studio will build/compile all assemblies (Dlls and EXE's) that are changed, it is basically incremental or partial process in which only CHANGED assemblies are compiled if there is no changed assemblies it won't get build

Rebuild :
It is full compiled case, in which all assemblies (either changed or not) are deleted and recompiled again, irrespective of changed or not

Clean :
It is not compile case, it just delete all assemblies (Dlls and EXE's) from folder but not compiled them again, it remove all compiled files from previous build

Hope you understand this simple article

Thanks and Happy building


Wednesday, July 20, 2016

ASP.NET MVC Interview Questions and Answers

ASP.NET MVC is getting popular more and more day by day, it has different features, it is popular due to its Modal-View-Controller architecture.
This article contains ASP.NET MVC interview questions that will help you to brush up your MVC concepts, this is the one point stop where you can get interview breaker Q & A.

Let's go through it

1. What is ASP.NET MVC ?
This is the most common asked question, it is an architectural pattern which separates the UI and code. It's basically divided into Model, View, and Controller section.
- As name suggest, The View is responsible for the look and feel.
- Model is real world object and provides data to the View.
- This is the heart of the architecture, it responsible for request and loading the appropriate Model and View.

2. What are the features of ASP.NET MVC?
- Clear separation of application concerns.
- Supports for Test Driven Development
- Supports Membership and roles, authentication and authorization, provider model and caching

3. What is Routing in ASP.NET MVC?
Routing is very easy in ASP.NET MVC. it shows user friendly URL in application, it is just like a URL rewriting. ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes
see below image in which you can see difference between ASP.NET path and ASP.NET MVC path, We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller
When URL redirect to another page it collect routing rules that are defined in Global.asax file and process the request

4. How to navigate from One view to another ?
You can easily do it using Hyperlink, by using 'ActionLink' method we can navigate to destination action
see below snippet
<%= Html.ActionLink("Home","GotoDestination") %>

5. What is VIEWDATA in ASP.NET MVC ?
To pass data from controller to view and in next subsequent request, ASP.NET MVC uses VIEWDATA. But it is limited to only server call and to main the state. When i redirect to another page
it gives me 'null' value, it acts between a link in VIEW and CONTROLLER. ViewData being a dictionary object is accessible using strings as keys.
ViewData requires typecasting for complex data type and check for null values to avoid error.
see below sample
//add some value to VIEWDATA
public ActionResult Index()
 ViewData["Text"] = "This is from view data";
 return View();

//access it in dictonary

6. What is VIEWBAG in ASP.NET MVC ?
It is simply same as VIEWDATA, which used to maintain state and transfer values between controller to view and in next subsequent request, just the difference is ViewBag is a dynamic property that takes advantage of the new dynamic features
ViewBag doesn't require typecasting for complex data type, both VIEWDATA and VIEWBAG has short life means, they are 'null' if redirect to another page
see below sample

//add some value to VIEWDATA
public ActionResult Index()
 ViewBag.Name = "This is from VIEWBAG";
 return View();

//access it
7. What is TEMPDATA in ASP.NET MVC ?
TEMPDATA is also dictionary type but it access request data and maintain state between multiple redirect, from one controller to the other controller or from one action to other action.
it uses HTTP request to transfer data. It internally uses session variables. it can be used to store only one time messages like exceptions.

see below sample
//in controller 1
public ActionResult Index()
 var model = new Review()
 Body = "i am controller 1",
 TempData["CON1"] = model;
 return RedirectToAction("Test");

//in controller 2
public ActionResult Test() 
 var model= TempData["CON1"]; 
 return View(model); 
8. How to transfer values in ASP.NET MVC between Controller and View ?
There are following ways to transfer values in ASP.NET MVC
1. ViewData : Transfer values only between Controller to View
2. ViewBag : Transfer values only between Controller to View
3. TempData : Transfer values only between Controller to Controller
4.Session Variables : It is very strong and dynamic way to Transfer values in ASP.NET MVC, it supports values transfer between Controller to Controller, Controller to View and View and Controller
5. Hidden Fields : Transfer values only between View to Controller

9. Is TempData can persist values between multiple request ?
This is very weird question The answer of this question is YES and NO,
YES cause it can persist values between request and NO cause once the value of TempData is read, it is empty

10. What is Model ?
Model is the layer between UI and input, in simple ways it handles all business logic, validation and database part, it manipulates it and saved back to database

11. Can i use ASP.NET MVC in Windows application
No. Model, View, controller framework is used to create web applications only, in windows you can Model, View, Presenter model

12. What is Razor in ASP.NET MVC ?
As word suggest Razor is acts like cleaner, it just trim the coding brackets and allow new style of coding
see below snippet

//in Classic ASP.NET we uses brackets to render variable
<% foreach (var empname in Model)
{ %>
 <li> <% %> </li>
<% }%>

//in ASP.MVC, Razor cleans unused tags and make it faster
@foreach (var empname in Model)
 <li> </li>
13. What is partial view
It is like a user control in we can use them multiple time, its a reusable view.Partial and RenderPartial methods are used to show partial view
see below snippet
14. What are the different result ASP.NET MVC can produce
Basically ASP.NET MVC produce only one result, that is 'ActionResult' but it has again different sub class like,
1. ViewResult - Get the response and render specific view.
2. PartialViewResult - Renders a specific but partial view to the response
3. EmptyResult - Return an empty result
4. RedirectResult - Returns an HTTP redirection to a given URL
5. RedirectToRouteResult - Depending on the routing engine get the URL and redirect the result
6. JsonResult - Return given ViewData object to JSON format
7. JavaScriptResult - Return code piece of Javascript that can later execute on client machine
8. ContentResult - Return content to the response
9. FileContentResult - Returns a file with content to the client
10.FileStreamResult - Returns a file to the client but in the form of a Stream
11.FilePathResult - Returns a file with path to the client

15. How to add style sheet in ASP.NET MVC
it is same like your classic ASP.NET
<link rel="StyleSheet" href="@Href(test.css)" type="text/css" />
16.What is the HTML Helper in ASP.NET MVC ?
HTML Helper is like a Classic ASP.NET controls but they are very light weight in comparison with traditional controls, an HTML helper does not have an event model and a view state.
all HTML links and HTML form elements are the part of HTML helper class
e.g. see below HTML link control in HTML Helper

@Html.ActionLink("Check this Website", "Newwebsite")
//when we run this code on Browser we get following output in HTML
<a href="Newwebsite">Check this Website</a>
17. What is minification, and why it is necessary ?
Minification is the process of reducing the size of script and CSS files by removing blank spaces, comments. This process removes whitespaces and comments, it will leads to minimize in file size, and thus increasing performance.
see below snippet
//simple javascript code is below
var a = 10;
a = a + 1;
a = a * 2;

//after minification we will get
var a=10;a=a+1;a=a*2;
Now with above code you can see your .js file size get reduced

18.What is Web API 's in ASP.NET MVC ?
- Web API is a new framework for building on HTTP to consuming Services over REST, it support wide range of Web browsers,desktop,mobile, smart phones

19. What is display Modes ?
with the help of Display Modes, Views selected automatically by application depending on the browser. e.g. for desktop browser application return URL as 'Views\test\Login.cshtml' and for same application mobile browsers will redirect to 'Views\test\'

Summing up
We have seen very basic and frequently asked Q&A series, In next part of this Article I will cover more complex scenario's about ASP.NET MVC, till then enjoy this stuff.

Comments/Suggestions/Doubts are always welcome


Thursday, May 5, 2016

Check all functionality using Javascript in Gridview

This is a small article that helps you to implement popular functionality of check all, it helps you to put checkbox in gridview view header and on click of that checkbox, all check boxes will checked at once

We have to developed a customized outlook a small interface that take care of all incoming mails. This interface is also used to delete the mails if not necessary.
for that use gridview to show all incoming mails and a facility in the form of checkbox to delete them either one by one or all at once. Now a list of problems come up
- How to add a checkbox in gridview header ?
- How check all columns on single click ?
- Can we do it on client side so we can save additional load on server execuion ?

In this article we go through the concept adding checkbox at gridview header, check/uncheck all checkboxes with the help of javascript on client side
here we go to collect cooking material. This simple demo is ready to use and handy in many codes.

What we need to make it ?
we need a gridview, A auto generated column of checkbox, gridview header temaple to keep checkbox in header and finally a javascript to work on checkboxes

Code in action
- Create a new ASP.NET website
- on default.aspx, add a gridview from toolbox and add asp:TemplateField for checkbox
- Set HeaderStyle, ItemStyle, Row style as desired
- Now we have design our gridview successfully, but how to add checkbox in gridview header ?
- it's simple, add checkbox in under , it will generate a checkbox in gridview header.

Header template

           <asp:CheckBox ID="chkHeaderSelect" runat="server" onclick="return callCheckAll()" />

I have put a code for you to copy it directly, copy the code and add it in ASPX page.
//paste the code in ASPX page
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" BackColor="White"
        BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px" Font-Size="10" 
        GridLines="Both" Width="80%" HorizontalAlign="Center">
            <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                    <asp:CheckBox ID="chkSelect" runat="server" />
                <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
                    <asp:CheckBox ID="chkHeaderSelect" runat="server" onclick="return callCheckAll()" />
        <RowStyle HorizontalAlign="Center" />
        <HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />

now, use the javascript to work "checkAll" functionality
see below script snippet

//copy following code in <head> section
  <script language="Javascript" type="text/javascript">
        function callCheckAll() 
          var checkList = GridView1.getElementsByTagName("input");
      var bChecked = false;
      if (checkList[0].checked)
           bChecked = true;
     for (var i = 0; i < checkList.length; i++) 
         //The First check box is Header Checkbox
             var headerCheck = checkList[0];
             var checked = true;
             if (checkList[i].type == "checkbox" && checkList[i] != headerCheck)
        checkList[i].checked = bChecked;

now fill the gridview and Ready for the effect

//Add this code on page load, to fill gridview using Datatable
         DataTable dt = new DataTable();

        //Put some columns in it. 
        dt.Columns.Add(new DataColumn("No", typeof(int)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Address", typeof(string)));

        for (int iCount = 0; iCount < 10; iCount++)
            // Create the record 
            DataRow dr = dt.NewRow();
            dr["No"] = iCount + 1;// i; 
            dr["Name"] = "DemoName" + iCount;//xmn2[1].InnerText;  //value from textbox on screen 
            dr["Address"] = "Address" + iCount;//xmn4[1].InnerText; //value from textbox on screen 

        //Bind the GridView to the data in the data table for display. 
        this.GridView1.Visible = true;
        GridView1.DataSource = dt;
This simple snippet/article really helpful to you to implement checkAll functionality.

Suggestion are most welcome.

Friday, April 22, 2016

Tricky SQL Server Interview Question and answers

Are you preparing for a SQL server interview? want some tricky questions and answers that will give you break through ? Then you are at the correct place. Here i have some bunch of tricky SQL Server interview questions and answers that will really help you to go through the interview

1.With is the Sixth normal form in SQL server? - Ohhh...You may think that, i have heard about first to forth only but what is this SIXTH? Friends, do not try to impress the interviewer just skip this question.
Sixth normal form does exist but use it when you want a relational system in conjunction with time. At this moment SQL Server does not support it directly.

2. In which Files does SQL Server Actually Store Data? - SQL server has 2 data files associated with it
1. MDF : Which is actual data file storage
2. LDF : (Log data files) which stores transaction log

3. Do you know How many locks are exist in SQL Server ? - We have these many locks exist here, see below
1. Intent
2. Shared
3. Update
4. Exclusive
5. Schema
6. Bulk Update

4.What is SQL Profiler?- It is a tool that allows administrator to monitor different events and transaction of SQL server instance, You can capture and save data about each event to a file or SQL Server table to analyze later
it is not available with EXPRESS edition

5. Can i insert into a table having just one IDENTITY column?- Yes you can, Use following Query
6. How to drop primary key from a column using Query
- See below query to drop primary key constraint
7. What is the difference between a DDL trigger and a DML trigger?- DDL commands are always deal with table structures, these command can update/modify table structure (CREATE, ALTER, DROP)
DMS commands are always deal with data/records not with table structure (INSERT, UPDATE, DELETE)

8. What the difference between UNION and UNIONALL?
- Union will remove the duplicate rows from the result set while UNIONALL does not remove them. So to avoid data redundancy you need to use UNION

9. What is the clustered and a non-clustered index?
- Clustered index is the physical index that reorders the way records in the table are physically stored, In non-clustered index logical order of the index does not match the physical stored order of the rows on disk

10. What's the difference between a primary key and a unique key?
- Both keys are not allow duplicate entries but primary key create a cluster index where as unique key create a non clustered index. Secondly primary key doesn't allow NULLs, but unique key allows one NULL only.
11. How to change the data type of a column- The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Here is the query to change column datataype
ALTER TABLE table_name ALTER COLUMN column_name data type

12. How to check the version of SQL server and operating system?
- With the help of the following query we can get it
SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition').

13. What is CHECK Constraint?
- CHECK Constraint used to limit the values that can be placed in a column

14. How can you delete duplicate records in a table where there is no primary key?
- You can take Use of the SET ROWCOUNT command. Here if you had 2 duplicate rows you would issue SET ROWCOUNT 1, then your DELETE command then SET ROWCOUNT 0.
15. What is NOT NULL Constraint?- This constraint force the column to not accept NULL values

16. How to copy data from one table to another table?
- With the help of 'INSERT INTO SELECT' or 'SELECT INTO' queries you can copy data from a datatable to another

17. What is PIVOT
- To automatically sort, count, and total the data stored in one table we use PIVOT. It will also rotate table as rows to columns and vice versa

18. What are DBCC commands?
- These are the Database Consistency Checker commands; They will Check disk allocation consistency, Display information about recent transactions.
19. Find the 3rd MAX salary in the emp table
Select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <= e2.sal);
20. What is the difference between Trigger and Stored Procedure?- Triggers cannot be called directly they need to associated with different quires

Suggestion/Queries always welcome

Happy Interview
- Prasad

Monday, April 18, 2016

JQuery Interview Questions

Are you preparing a Jquery interview? Then read this blog to know more about JQuery, here I have given some frequently asked JQuery Interview Questions and answers, which will surely help you to crack your interview

1. What is JQuery?
- Most simple but frequently asked question, JQuery is a library designed by javascript, it is light weight, it is simple than JavaScript, it has many inbuilt methods and it can handle events, Html DOM and Ajax

2. What is $ in JQuery?
- Simple it is a function selector or a JQuery object, some says $ is a shortcut to the jQuery function

3. Can i use Javascript and JQuery on same page?
- Yes, we can use Javascript and JQuery on same page, for the use of JQuery we need to add .JS library reference to the page, where as for JavaScript for separate library reference is needed.

4. How to use JQuery?
 - JQuery can be easily called with the help of its referenced libraries, first we need to give JQuery library reference to page and then call it using '$' sign
see below snippet, we can write JQuery in HEAD section
//here is JQuery reference
<script src=""></script>
 alert("Message on on page load")

above snippet shows, we can write JQuery in HEAD section and above code will call on Page load
5. What are the features of JQuery?
- JQuery is highly intractable, it has following features
  • Rich Inbuilt methods that easily interact with controls
  • Events handling
  • Special widgets
  • Animation and effect supports
  • Good alternative to flash
  • Strong AJAX support
  • HTML DOM Manipulation
  • Can Bind Multiple Event Handlers in single method
6. What is JQuery UI?
- JQuery UI is also a JavaScript library, as name suggest it is a user interface portal that is built using JavaScript and can be easily added in new and existing applications
it contains interactions, widgets and effects, we can build UI rich and highly interactive applications using it.

7. Which are the performance responsive selector?
- The elements which are selected using ID are the performance responsive selector as the ID is unique throughout the rendered page

8. JQuery or JavaScript which is quicker in execution?
- Native JavaScript is always faster in operation than JQuery cause JQuery is a JavaScript library,
e.g. Through we call '$(#EmpName)' in JQuery, it internally convert the syntax to javascript's 'getElementById("EmpName")' method and then execute in browser

9. What is has() in JQuery? - has() is selection filter, it checks Check if an Element 'Has Something', means if i want to traverse my HTML file and check if DIV has list tag (OL) then we can check with has(), see below snippet
above code will select all element with 'ol'
10. Can JQuery parse XML?
- No, currently JQuery supports only HTML DOM parser

11. Can JQuery Run on MAC or Linux instead of Windows?
- JQuery support cross browser and cross platform compatibility hence it fluidly runs on Windows/MAC/Linux with all major browser compatibility (IE/Chrome/FF/NN/Safari)

12. When to use JQuery?
- Basically JQuery can be use more than validation part, Alone JavaScript can be able to handle validation part, you can us JQuery when you want rich user interface with client side events, when you want to remove flash plug inns and put some animations

13. Which effects has inbuilt supported by JQuery?
- Hide, Show, Toggle, SlideDown, SlideToggle, SlideUp, FadeIn, FadeOut, Animate, FadeTo, FadeToggle, has inbuilt support by JQuery

14. Can we replace any character or variable instead of $ in JQuery?
- Yes,
we can replace $ by using no Conflict () method, see below snippet to replace $
var szDoll = $.noConflict()

15. Tell me something about JQuery debugging? JQuery can be debugged easily using following ways
  1. using debugger; keyword : Add debugger; keyword just before the line where you want to debug
  2. using Breakpoint : If you have visual studio then you can place breakpoint on line where you want to start debugging
  3. Placing a Alert box : It is traditional way, if you don't have visual studio, you need to place a alert boxes in lines from where you want start debugging
16. What is Method chaining in JQuery?
 - As name suggest it is the chain of methods executed in sequence, it is executed in single statement, see following snippet
$("#div1").text("DIV 1");
$("#div1").css("color", "red");

//instead we can write
$("#div1").text("DIV 1");
          .css("color", "red");

17. How to redirect a page using JQuery?
- There is no specific JQuery syntax to redirect a page, you can use Javascript syntax instead, see below snippet
window.location.href = http://test/default.aspx;

18. How to refresh a page using JQuery?
- you can use location.reload() method, to refresh page, see below snippet

19. How to check if element is hidden or visible using JQuery?
- You can use 'is()' method for 'display' or 'hidden' property, it returns boolean variable, see below snippet

20. What is difference in return false and preventDefault in JQuery?
- when we call return false, it first call e.preventDefault and then call e.stopPropagation which stop execution, where as e.preventDefault will prevent event to be bubbling up.

21. What is difference between "#" and "." selector in JQuery? - Basically JQuery uses following notation as selector
  1. $("div") : It is global selector which Selects all DIV element in page
  2. $("#btnSubmit") : # is a specific ID selector which select element having ID as 'btnSubmit'
  3. $(".classBold") : . is a specific Class selector which select element having class as 'classBold'
22. Which are the most common JQuery evens?
  • click () : Raise when any element is clicked
  • dblclick() : Raise when any element is double clicked
  • mouseenter() : Raise when mouse pointer enter in element
  • mouseleave() : Raise when mouse pointer leave an element
  • mousedown() : Raise when mouse pointer clicked down on element
  • mouseup() : Raise when mouse pointer clicked and release on element
  • focus() : Raise when element got focus
Rome was not built in a day, still more to come, i will cover some more complex Q&A in Next version of this article, till then you can enjoy this most commonly asked question

Suggestion and queries are most welcome

Thanking you

Wednesday, November 25, 2015

ASP.NET MVC Do's and Dont's/Best practices


ASP.NET MVC (Model-View-Controller architectural pattern) is getting popular day by day, due to Separation of code, extensive templates, data-binding, test-driven development (TDD), Scaffolding and no view state like features, it has REST and SEO support nature. it is really an plugged and extensible framework. We get complete control over HTML with MVC support.  But before going to code on ASP.NET MVC we should take care of some Do's and Dont's or best practices. Here i am explaining some Do's and Don'ts of ASP.NET MVC code
         Many developers/organizations thinking of migrating their exiting application to ASP.NET MVC, This article will help them to understand code facts

Do's and Dont's/Best Practices

1. Business logic should be the part of Model only
Before start code on MVC we should make understand that Business logic should be reside in Model only, it will add your security and code duplication can be avoided. The view load faster as there is no business present in view.

2.  Use only specific view engine
View engines are used to create HTML markup from your view, it is the combination of HTML and programming code, ASP.NET has its own engine where as ASP.NET MVC has its razor engine. You should only use your specified view engine, it will increase application performance, see below snippet
protected void Application_Start()
    ViewEngines.Engines.Clear(); //clear all engines
    ViewEngines.Engines.Add(new RazorViewEngine());
3. Create separate assembly for Model
if the application is large and complex then make separate assembly for Model to avoid An unfortunate mishap.  Basically Model should contain business logic, Validation part, session maintenance and data logic part.

4. HTML and data access part should be done from VIEW only
As we know VIEW is the presenter part and it should be very flexible. VIEW should not contains any business logic and session maintenance, use ViewData to access data in View.

5.  Business logic and data access should not exist in ControllerViewData
Controller should be only responsible for calling model, Prepare view, return view, redirect to action etc

6. Delete Demo code from application when you create it
Delete AccountController and all other auto created code from application it will slow down the performance

7. Disable request validation
Request validation validate the request submitted to server and avoid the potential dangerous characters, but it will also block the contents to post HTML markup tags to the server, so disable it, with the help of ValidateInput we can do it, see below snippet
public ActionResult Create([Bind(Exclude="Name")]TestEmployee clsEmp)
//code goes here
8. Master view model may be use for Uniformness
In ASP.NET master pages are used to maintain uniformness in look and feel, same way in ASP.NET MVC we use master view for it.

9.  Data Annotations can be used for server side validation
Use System.ComponentModel.DataAnnotations namespace for server side validation, just use it in model with attribute, see snippet
Public class GetAddress
    [Required(ErrorMessage="Address is mandatory")]
    public string Address { get; set; }
10. Use extension methods
Extension method help us to simplify LINQ queries and improve application performance, these methods are the static methods and access with this keyword.

11. Remove un-necessary folders and references
When you start creating new ASP.NET MVC application, visual studio does create lot of un-necessary folders and references that are not useful, we can remove them to avoid additional overhead on application

12. Do Bundling and Minifying CSS Files
Bundling and Minifying is the process of minimizing the size of referenced file like .JS, .JSON, .CSS we can reduce the size of such files which will ultimately boost the application performance, in Bundling we merge all CSS in one file and same done for .JS and .JSON file in Minification we remove extra spaces and enters from file and reduce file size

13. For each view there should be a view model
Do you have view ? if yes then create ViewModel. it should used only for data binding and may not contain any presenter code. ViewModel is essential when we want to show some data in different format, in such case view only responsible for present and ViewModel does the job of data transformation

14. Design Routing properly not URL re-writing
URL routing is very much different than URL re-writing, may developers consider them as unique thing. URL routing does not create new URL for old URL but it maps resources with route

15.  Use ViewData and ViewBag for large data storage
If you want to work with lage data, spread sheets, dashboards or volume data sources then ViewData is good option, both views and controllers can easily access ViewData and ViewBag

16. For current and the subsequent requests use TempData
TempData is very short-lived instance, it should use only For current and the subsequent requests.

17. Use Glimpse, fidder, F-12 like package to monitor and improve performance of ASP.NET MVC
Glimpse NuGet package provide detail diagnostic information of ASP.NET apps, where as fidder, F-12 shows you client side activities, more information can be found on Here

18.  Deploy code in Release mode
Code with Release is more compressed than debug mode as it does not conain .pdb file so less memory is utilized by it

19. Remove unnessary HTTP headers
Remove X-AspNetMvc version from global.asax.cs as it will not provide no direct benifit and un-necessarily use small amount of bandwidth, see below snippet
MvcHandler.DisableMvcResponseHeader = true;
20. Use CDN (Content Delivery Networks)
CDN is helping you to download your supportive things (like required .JS, .CSS, .JSON files) from nearest location/server, so travelling time of resources from one location to another will save significantly.

21. Use validationSummary to show all validations in one snap
see below method to use to show all validation in one snap
<%= Html.ValidationSummary() %>
22. Razor is recommended
We know ASP.NET MVC support multiple engines but Razor is recommended by Microsoft as it is light weight and it has very simple syntax

23. Do you want some repetitive UI to be display on each page ? use Partial view
Partial view is like a user control in classic ASP.NET, you can use them if you want to show piece of UI on each page

24. If you are not using bundles and WebAPI then simple remove their associated files
Go to App_start directory and remove BundleConfig file, now go to Application_Start method, in Global.asax.cs and remove the line BundleConfig.RegisterBundles, same thing you can do for WebApiConfig

This is not a detail level document, this document at least need a basic knowledge of ASP.NET MVC, i will cover more detail documentation in next version of this document till then enjoy this stuff

Suggestion and Queries are always welcome


New features of SQL 2016

  Introduction SQL Server 2016 was (finally) released on June 1 st , 2016 with an initial build number of 13.0.1601.5. Microsoft bui...