Drag-able Div with Native javascript

Need to call this method bindStudylistEvents() in load event.

private bindStudylistEvents() {
var self = this;
$(‘.close-button’).off(‘click’).on(‘click’,() => {
$(‘.div’).hide();
});
$(‘.div-panel-header’).off(‘mousedown’).on(‘mousedown’, function (e) {
self.mousedownEventHandlers(e);
});
$(window).off(‘mouseup’).on(‘mouseup’, function (e) {
self.mouseupEventHandlers(e);
});
$(window).off(‘mousemove’).on(‘mousemove’, function (e) {
self.mousemoveEventHandlers(e);
});

}

private mousemoveEventHandlers(e) {
if (this.isMoving) {
this.offsetdivX = this.offsetdivX + e.clientX – this.mouseX;
this.offsetdivY = this.offsetdivY + e.clientY – this.mouseY;
this.mouseX = e.clientX;
this.mouseY = e.clientY;
$(‘.div’).css({ “left”: this.offsetdivX, “top”: this.offsetdivY });
}
}

private mousedownEventHandlers(e) {
this.isMoving = true;
this.mouseX = e.clientX;
this.mouseY = e.clientY;
}

private mouseupEventHandlers(e) {
this.isMoving = false;
}

https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: “ca-pub-3531312797721300”,
enable_page_level_ads: true
});

Multi selection list with select2.js

A sample page is prepared below, Just used CDNs for Jquery & CSS.

<html>
<head>
<link rel=”stylesheet” href=”http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css”&gt;
http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js

$(document).ready(function () {
$(“#e1”).select2();
$(“#checkbox1”).click(function(){
if($(“#checkbox1”).is(‘:checked’) ){
$(“#e1 > option”).prop(“selected”,”selected”);
$(“#e1”).trigger(“change”);
}else{
$(“#e1 > option”).removeAttr(“selected”);
$(“#e1”).trigger(“change”);
}
});

$(“#button”).click(function(){
$(‘#txt’).text($(“#e1”).val());

});
});

</head>
<body>

/*

Kerala
TamilNadu
Karnataka
Goa
Andra Pradesh

Select All

Select values will be displayed here

</div>*/

</body>

Normalization,Types of Normalization and Denormalization in MS SQL

  1. Q) What is Normalization? What are the Different Types of Normalization?

Note: A regular .NET programmer working on projects often stumbles on this question, which is but obvious. The bad part is sometimes the interviewer can take this as a very basic question to be answered and it can be a turning point for the interview. So let’s cram it.

It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization.

Benefits of Normalizing your database include:

  • Avoiding repetitive entries
  • Reducing required storage space
  • Preventing the need to restructure existing tables to accommodate new data
  • Increased speed and flexibility of queries, sorts, and summaries

Note: During an interview, people expect to answer a maximum of three normal forms and that’s what is expected practically. Actually you can normalize database to fifth normal form. But believe this book, answering three normal forms will put you in a decent shape during an interview.

The three normal forms as follows:

First Normal Form

For a table to be in first normal form, data must be broken up into the smallest units possible. In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields.

Figure 1.8: Repeating groups example

In the above example, city1 and city2 are repeating. In order for these tables to be in First normal form, you have to modify the table structure as follows. Also note that the Customer Name is now broken down to first name and last name (First normal form data should be broken down to the smallest unit).

Figure 1.9: Customer table normalized to first normal form

Second Normal Form

The second normal form states that each field in a multiple field primary key table must be directly related to the entire primary key. In other words, each non-key field should be a fact about all the fields in the primary key.

In the above table of customer, city is not linked to any primary field.

Figure 1.10: Normalized customer table.

Figure 1.11: City is now shifted to a different master table.

That takes our database to a second normal form.

Third Normal Form

A non-key field should not depend on another Non-key field. The field Total is dependent on Unit price andqty.

Figure 1.12: Fill third normal form

So now the Total field is removed and is the multiplication of Unit price * Qty.

(Q) What is Denormalization?

Denormalization is the process of putting one fact in numerous places (it is vice-versa of normalization). Only one valid reason exists for denormalizing a relational design – to enhance performance. The sacrifice to performance is that you increase redundancy in a database.

(DB) Can you Explain Fourth Normal Form?

Note: Whenever the interviewer is trying to go above the third normal form, there can be two reasons, ego or to fail you. Three normal forms are really enough, practically anything more than that is an overdose.

In fourth normal form, it should not contain two or more independent multi-valued facts about an entity and it should satisfy “Third Normal form”.

So let us try to see what multi-valued facts are. If there are two or more many-to-many relationship in one entity and they tend to come to one place, it is termed as “multi-valued facts”.

Figure 1.13: Multi-valued facts

In the above table, you can see that there are two many-to-many relationships between Supplier / Productand “Supplier / Location (or in short multi-valued facts). In order for the above example to satisfy the fourth normal form, both the many-to-many relationships should go in different tables.

Figure 1.14: Normalized to Fourth Normal form.

(DB) Can you Explain Fifth Normal Form?

Note: UUUHHH if you get this question after joining the company, do ask him if he himself really uses it?

Fifth normal form deals with reconstructing information from smaller pieces of information. These smaller pieces of information can be maintained with less redundancy.

Example: Dealers sell Product which can be manufactured by various Companies. Dealers in order to sell theProduct should be registered with the Company. So these three entities have a mutual relationship within them.

Figure 1.15: Not in Fifth Normal Form.

The above table shows some sample data. If you observe closely, a single record is created using lot of small information. For instance: JM Associate can sell sweets under the following two conditions:

  • JM Associateshould be an authorized dealer of Cadbury
  • Sweetsshould be manufactured by Cadbury company

These two smaller bits of information form one record of the above given table. So in order for the above information to be “Fifth Normal Form” all the smaller information should be in three different places. Below is the complete fifth normal form of the database.

Figure 1.16: Complete Fifth Normal Form

(DB) What is the Difference between Fourth and Fifth normal form?

Note: There is a huge similarity between Fourth and Fifth normal form, i.e. they address the problem of “Multi-Valued facts”.

“Fifth normal form” multi-valued facts are interlinked and “Fourth normal form” values are independent. For instance in the above two questions Supplier/Product and Supplier/Location are not linked. While in fifth form, the Dealer/Product/Companies are completely linked.

(DB) Have you Heard about Sixth Normal Form?

Note: Arrrrggghhh yes there exists a sixth normal form also. But note guys you can skip this statement. Just in case you want to impress the interviewer…

If you want a relational system in conjunction with time, you use sixth normal form. At this moment SQL Server does not support it directly.

Performance Improvement in View Engine Setup

As of now we are using the default view engine settings.The idea behind is ,will get a bit of performance improvement by attaching right view engine in MVC and then we will extend the existing Razor view engine with our own customization.

The MVC framework has two engines ( Web form & Razor) ,normally the web form engine is get fired initially and then fired the Razor engine but our assumption was wrong, we thought  that it would choose Razor engine only.

When I tried with below code, in any of the Action method in a controler
 public class TestController : Controller
      {
        public ActionResult Index()
        {
            return View(“Test”);
        }
    }
Obviously, we should see the below snapshot, because we don’t have the view at all. If we check the search step closely, then we will see that MVC framework is searching .aspx page at first, then .cshtml and all, so the Web Form view is performing at first then Razor view.
Inline image 1
 
After doing some modification in Frame work level :
Now, if we run the application, we will see that the custom view Engine is searching for .cshtml page only. It will increase the view rendering performance.

Inline image 2

Global.asax File Modification
 
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas();// Please comment this line if you are not using Areas in your project RouteConfig.RegisterRoutes(RouteTable.Routes); //Remove all view engine ViewEngines.Engines.Clear(); //Add Razor view Engine ViewEngines.Engines.Add(new RazorViewEngine()); Bootstrapper.Initialise(); } }
—————————————-
Add a class file (ex: name: CustomRazorViewEngine) in App_start
Inline image 1
public class CustomRazorViewEngine : RazorViewEngine {
  public CustomRazorViewEngine() {
        AreaViewLocationFormats = new[]
    {
      “~/Areas/{2}/Views/{1}/{0}.cshtml”, “~/Areas/{2}/Views/Shared/{0}.cshtml” };
       AreaMasterLocationFormats = new[]
    {
       “~/Areas/{2}/Views/{1}/{0}.cshtml”,     “~/Areas/{2}/Views/Shared/{0}.cshtml” };
        AreaPartialViewLocationFormats = new[]
         { “~/Areas/{2}/Views/{1}/{0}.cshtml”, “~/Areas/{2}/Views/Shared/{0}.cshtml” };
ViewLocationFormats = new[]
{ “~/Views/{1}/{0}.cshtml”, “~/Views/Shared/{0}.cshtml” };
MasterLocationFormats = new[] { “~/Views/{1}/{0}.cshtml”, “~/Views/Shared/{0}.cshtml” };
PartialViewLocationFormats = new[] { “~/Views/{1}/{0}.cshtml”, “~/Views/Shared/{0}.cshtml” };
}
}
}

Select list option operations in Javascript.

UI:

 

 

Dialog

Code:

 

/// <reference path=”../../../Scripts/typings/jquery/jquery.d.ts” />
/// <reference path=”../../../Scripts/typings/perf.d.ts” />
module WorkflowUI.Menu {

export class ColumnSettings {

private metaDataColumns: Array<any>;
private columnSettingsDialog: string;
private popupDialogMask: string;
private grid: any;
private gridType: string;
private event: any;

public SCROLL_FACTOR: number = 16;

constructor(private invokingGrid: WorkflowUI.Grid.GridBase, private eventSource: any, private invokingGridType: string) {
this.columnSettingsDialog = “.columnSettings-dialog”;
this.popupDialogMask = ‘.popup-mask’;
this.grid = invokingGrid;
this.gridType = invokingGridType;
this.event = eventSource;
}

public showColumnSelectorWindow() {
var availableList = [],
swatList: string = “”,
customList: string = “”;
this.metaDataColumns = JSON.parse(JSON.stringify(this.grid.headerInfo.Columns));
for (var i = 0; i < this.metaDataColumns.length; i++) {
if (this.metaDataColumns[i].IsHidden == false) {
if (this.metaDataColumns[i].Width === 0 ||
this.metaDataColumns[i].Width == null) {
availableList.push(this.metaDataColumns[i]);
}
else {
var label = this.metaDataColumns[i].Label !== “” ? this.metaDataColumns[i].Label : this.metaDataColumns[i].Name;
customList += “<option name='” + this.metaDataColumns[i].Name + “‘>” + label + “</option>”;
}
}
}
availableList.sort(this.dynamicSort(“Label”));
swatList=this.createAvailableList(availableList);

var columnDiv = ‘<div class=”columnSettings-header”><span class=”columnSettings-headertext”>’ + WorkflowUI.Common.Utils.localTranslate(‘Column Customization’) + ‘<span></div><div class=”columnSettings-content”><div class=”listColumns”><strong>’ + WorkflowUI.Common.Utils.localTranslate(‘Available’) + ‘</strong><select multiple=”multiple” class=”swatList”>’ + swatList + ‘</select></div>’ +
‘<div class=”listColumn-button”><button type=”submit” class=”fmsicons glyphicons right_arrow column-customization-button moveto-selected”></button> <button type=”submit” class=”fmsicons glyphicons left_arrow column-customization-button moveto-available” ></button></div>’ +
‘<div class=”listColumns” ><strong>’ + WorkflowUI.Common.Utils.localTranslate(‘Selected’) + ‘</strong><select multiple=”multiple” class=”customList”>’ + customList + ‘</select></div>’ +
‘<div class=”listColumn-button”> <button type=”submit” class=”fmsicons glyphicons up_arrow column-customization-button moveColumnUp”></button><button type=”submit” class=”fmsicons glyphicons down_arrow column-customization-button moveColumnDown”></button></div></div>’ +
‘<div class=”listColumn-save-cancel”><button type=”submit” class=”save-and-close-columnSettings columnSettings-button btn btn-primary” > ‘ + WorkflowUI.Common.Utils.localTranslate(‘Save and Close’) + ‘</button><button type=”submit” class=”save-columnSettings columnSettings-button btn btn-primary” > ‘ + WorkflowUI.Common.Utils.localTranslate(‘Save’) + ‘</button><button type=”submit” class=”cancel-columnSettings columnSettings-button btn btn-primary” > ‘ + WorkflowUI.Common.Utils.localTranslate(‘Cancel’) + ‘</button></div>’;
this.showColumnSettingsDialog(columnDiv);
this.enableOrDisableRightAndLeftControls();
}

private createAvailableList(availableList) {
var _swatList: string = ”;
for (var i = 0; i < availableList.length; i++) {
var label = availableList[i].Label !== “” ? availableList[i].Label : availableList[i].Name;
_swatList += “<option name='” + availableList[i].Name + “‘>” + label + “</option>”;
}
return _swatList;
}

private showColumnSettingsDialog(data: string) {
var clientX,
windowWidth = 600;

if ($(window).width() < this.event.pageX + windowWidth) {
clientX = $(window).width() – windowWidth;
} else {
clientX = this.event.pageX;
}
$(this.columnSettingsDialog).css({ “left”: clientX, “top”: this.event.pageY });
$(this.columnSettingsDialog).html(data);
$(this.popupDialogMask).fadeTo(500, 0.25).css(‘z-index’, 1);
this.bindcolumnSettingsDialogEvents();
$(“.columnSettingsbutton-container”).addClass(‘columnSettingsbutton-container-active’);
$(this.columnSettingsDialog).show();
}

private bindcolumnSettingsDialogEvents() {
var defaultWidth = 10;
var hiddenWidth = 0;

$(‘.save-columnSettings’).off(‘click’).on(‘click’,() => {
this.saveColumnInformation();
});

$(‘.save-and-close-columnSettings’).off(‘click’).on(‘click’,() => {
this.saveColumnInformation();
$(this.popupDialogMask).hide();
this.hideColumnSettingsDialog();
});

$(‘.cancel-columnSettings’).off(‘click’).on(‘click’,() => {
$(this.popupDialogMask).hide();
this.hideColumnSettingsDialog();
});

$(‘.moveto-selected’).off(‘click’).on(‘click’,(e) => {
this.moveColumn(‘swatList’, ‘customList’, defaultWidth);
});

$(‘.moveto-available’).off(‘click’).on(‘click’,(e) => {
this.moveColumn(‘customList’, ‘swatList’, hiddenWidth);
this.sortSelect(‘swatList’);
});

$(‘.moveColumnUp’).off(‘click’).on(‘click’,(e) => {
this.moveUp(‘customList’);
});

$(‘.moveColumnDown’).off(‘click’).on(‘click’,(e) => {
this.moveDown(‘customList’);
});

$(‘.swatList’).off(‘click’).on(‘click’,(e) => {
$(‘.customList option’).removeAttr(“selected”);
}).off(‘dblclick’).on(‘dblclick’,(e) => {
this.moveColumn(‘swatList’, ‘customList’, defaultWidth);
this.sortSelect(‘swatList’);
});

$(‘.customList’).off(‘click’).on(‘click’,(e) => {
$(‘.swatList option’).removeAttr(“selected”);
//up and down arrow disabling code
var op = $(‘.customList option:selected’);

this.enableOrDisableUpAndDownControls();
if (this.isQBEOrSortApplied(op.attr(“name”))) {
$(‘.moveto-available’).prop(‘disabled’, ‘disabled’);
} else {
$(‘.moveto-available’).removeAttr(‘disabled’);
}
}).off(‘dblclick’).on(‘dblclick’,(e) => {
var op: any = $(“.customList option:selected”);
if (!this.isQBEOrSortApplied(op.attr(“name”))) {
this.moveColumn(‘customList’, ‘swatList’, hiddenWidth);
}
});
}

private enableOrDisableRightAndLeftControls() {
if ($(“.swatList option”).length == 0) {
$(‘.moveto-selected’).prop(‘disabled’, ‘disabled’);
} else {
$(‘.moveto-selected’).removeAttr(‘disabled’);
}
}
// This method will move the selected item to the other list box
private moveColumn(from, to, width) {
if (from === ‘customList’ && $(“.customList option”).length == 1 || $(“.customList option:selected”).length === $(“.customList option”).length) {
return;
}
var lstfrom = $(“.” + from + ” option:selected”);
var self = this;
lstfrom.each(function (index, elem) {
var selectElem = $(elem);
if (selectElem.val()) {
var name = selectElem.attr(“name”);
if (!self.isQBEOrSortApplied(name)) {
selectElem.remove();
$(‘.’ + to).append(“<option name='” + name + “‘>” + selectElem.text() + “</option>”);
self.updateMetadataColumnWidth(name, width);
}
}
});
this.enableOrDisableUpAndDownControls();
this.enableOrDisableRightAndLeftControls();
}

// This method will move the selected item down in the list box
private moveDown(cntrl) {
var op: any = $(‘.’ + cntrl + ” option:selected”);
if (op.length == 0) {
return;
}
if (WorkflowUI.Common.Utils.detectIE()) {
if ($(‘.customList’).scroll().length > 0 && $(‘.customList’).prop(“selectedIndex”) > 6) {
$(‘.customList’)[0].scrollTop += this.SCROLL_FACTOR;
}
}
if ($(‘.’ + cntrl + ” option”).length – 2 === op.index()) {
$(‘.moveColumnDown’).prop(‘disabled’, ‘disabled’);
} else {
$(‘.moveColumnUp’).removeAttr(‘disabled’);
}
op.last().next().after(op);
}
// This method will move the selected item Up in the list box
private moveUp(cntrl) {
var op = $(‘.’ + cntrl + ” option:selected”);
if (op.length == 0) {
return;
}
if (WorkflowUI.Common.Utils.detectIE()) {
if ($(‘.customList’).scroll().length > 0 && $(‘.customList’).prop(“selectedIndex”) < $(‘.customList option’).length- 6) {
$(‘.customList’)[0].scrollTop -= this.SCROLL_FACTOR;
}
}
if (op.index() === 1) {
$(‘.moveColumnUp’).prop(‘disabled’, ‘disabled’);
} else {
$(‘.moveColumnDown’).removeAttr(‘disabled’);
}
op.first().prev().before(op);
}
private hideColumnSettingsDialog() {
$(this.columnSettingsDialog).hide();
$(this.popupDialogMask).hide();
$(“.columnSettingsbutton-container”).removeClass(‘columnSettingsbutton-container-active’);
}

private updateMetadataColumnWidth(columnName, width) {
for (var i = 0; i < this.metaDataColumns.length; i++) {
if (this.metaDataColumns[i].Name === columnName) {
this.metaDataColumns[i].Width = width;
}
}
}

private enableOrDisableUpAndDownControls() {
var op = $(‘.customList option:selected’);
if ($(‘.customList option’).length === 1 || $(‘.customList option’).length === op.length) {
$(‘.moveColumnUp , .moveColumnDown’).prop(‘disabled’, ‘disabled’);
} else {
if (op.index() === 0) {
$(‘.moveColumnUp’).prop(‘disabled’, ‘disabled’);
$(‘.moveColumnDown’).removeAttr(‘disabled’);
} else if (op.index() === $(‘.customList option’).length – 1) {
$(‘.moveColumnDown’).prop(‘disabled’, ‘disabled’);
$(‘.moveColumnUp’).removeAttr(‘disabled’);
} else {
$(‘.moveColumnUp , .moveColumnDown’).removeAttr(‘disabled’);
}
}
}

private isQBEOrSortApplied(columnName) {
var status = false;
if (this.grid.listFilters && this.grid.listFilters.length > 0) {
for (var i = 0; i < this.grid.listFilters.length; i++) {
if (this.grid.listFilters[i].Column === columnName) {
return true;
}
}
}
if (this.grid.listSorts && this.grid.listSorts.length > 0) {
for (var i = 0; i < this.grid.listSorts.length; i++) {
if (this.grid.listSorts[i].Column === columnName) {
return true;
}
}
}
return status;
}

private updateMetadataColumnOrder() {
for (var i = 0; i < this.metaDataColumns.length; i++) {
var element = $(“.customList option[name='” + this.metaDataColumns[i].Name + “‘]”);
if (element.length > 0) {
this.metaDataColumns[i].Order = element.index() + 1;
}
}
}

private saveColumnInformation() {
this.updateMetadataColumnOrder();
var qbeUpdateParams = new Models.QbeUpdateParams();
if (this.gridType === “worklist”) {
if (this.grid.listData.WorklistType === WorkflowUI.Common.Utils.worklistTypes.LINK_FOLDER) {
var linkUpdateParams = new Models.LinkUpdateParams();
linkUpdateParams.columns = this.metaDataColumns;
linkUpdateParams.displayName = this.grid.listData.FolderName;
linkUpdateParams.userLogin = WorkflowUI.Common.Utils.loggedInUser;
linkUpdateParams.uuid = this.grid.listData.Identifier;
WorkflowUI.Services.WorklistServices.updateLinkFolder(linkUpdateParams, this.grid.initializeGrid.bind(this.grid), this.grid.ajaxErrorCapture.bind(this.grid));
} else {
qbeUpdateParams.isOverride = true;
qbeUpdateParams.identifier = this.grid.listData.Identifier;
qbeUpdateParams.folderName = this.grid.listData.Label ? this.grid.listData.Label : this.grid.listData.FolderName;
qbeUpdateParams.columns = this.metaDataColumns;
qbeUpdateParams.filters = this.grid.listFilters;
qbeUpdateParams.worklistType = this.grid.listData.WorklistType;
qbeUpdateParams.userLogin = WorkflowUI.Common.Utils.loggedInUser;
WorkflowUI.Services.WorklistServices.updateQbeFolder(qbeUpdateParams, true, this.grid.initializeGrid.bind(this.grid), this.grid.ajaxErrorCapture.bind(this.grid));
}
} else {
qbeUpdateParams.isOverride = true;
qbeUpdateParams.identifier = qbeUpdateParams.folderName = this.grid.identifier;
qbeUpdateParams.columns = this.metaDataColumns;
qbeUpdateParams.filters = this.grid.headerInfo.Filters;
qbeUpdateParams.groupByColumns = this.grid.headerInfo.GroupByColumns;
qbeUpdateParams.worklistType = WorkflowUI.Common.Utils.worklistTypes.QBE_FOLDER;
qbeUpdateParams.userLogin = WorkflowUI.Common.Utils.loggedInUser;
WorkflowUI.Services.WorklistServices.updateQbeFolder(qbeUpdateParams, true, this.grid.initializeGrid.bind(this.grid), this.grid.ajaxErrorCapture.bind(this.grid));
}
}

private dynamicSort(property) {
return function (a, b) {
return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 :
(a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
};
}

private sortSelect(listID) {
var list = $(“.” + listID + ” option”);
var availableList = [];
for (var i = 0; i < list.length; i++) {
var element = $(list[i]);
var item: any = { ‘Name’: element.attr(“name”), ‘Label’: element.text() };
availableList.push(item);
}
availableList.sort(this.dynamicSort(“Label”));
var selectedList = this.createAvailableList(availableList);
$(“.” + listID + “”).empty();
$(“.” + listID + “”).append(selectedList);
}

}
}

New Features in ASP.NET Web API 2

We can say there are mainly 5 new features are available in Web API 2.

  1. Attribute Routing

According to convention-based routing, Web API 2 now supports attribute routing as well.

In case of convention-based routing, we can define multiple route templates. When a request comes, it will be matched against already defined route templates, and forwarded to specific controller action according to matched template.

You can see the following default route template in routing table for Web API:

Config.Routes.MapHttpRoute(

name: “DefaultApi”,

routeTemplate: “api/{Controller}/{id}”,

defaults: new { id = RouteParameter.Optional }

);

This routing approach has benefits that all routing templates are defined at one common location but for certain URI patterns, it really becomes difficult to support (like nested routing on same controller).With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as well. Following shows an example of a URI pattern with attribute routing.If we need to change the URL pattern for the specific clients, we can easily map the URL what they exactly asked.

URI Pattern –> users/1/user

[Route(“users/{userId}/user”)]

public IEnumerable GetUserById(int UserId) { ….. }

  1. CORS – Cross Origin Resource Sharing

Normally, browsers does not  allow making cross-domain calls due to same-origin policy and we know that. So, what exactly is CORS (Cross Origin Resource Sharing)?

CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the domain which actually rendered that specific web page. CORS is compliant with W3C standards and now ASP.NET Web API has support for it in version 2.

  1. OWIN (Open Web Interface for .NET) self hosting

ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi. OwinSelfHost.

According to http://owin.org/
“OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.”
So, according to above description, OWIN is an ideal option for self hosting a web application in a process other than IIS process.

There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web API frameworks.

Here you can see the sample code,

using Microsoft.Owin.Hosting;

using System;

using System.Net.Http; 

namespace OwinSelfhostSample

{
    public class Program

    {
        static void Main()

        {

            string baseAddress = “http://localhost:9000/&#8221;; 

            // Start OWIN host

            using (WebApp.Start(url: baseAddress))

            {

                // Create HttpCient and make a request to api/values

                HttpClient client = new HttpClient(); 

                var response = client.GetAsync(baseAddress + “api/values”).Result; 

                Console.WriteLine(response);

                Console.WriteLine(response.Content.ReadAsStringAsync().Result);

            }

            Console.ReadLine();  

           }   

       }  

   }

  1. IHttpActionResult

Along with the existing two approaches of creating response from controller action, ASP.NET Web API 2 now supports another way of doing the same. IHttpResponseMessage is basically an interface which acts as a factory for HttpResponseMessage. It’s very powerful because it extensify web api. Using this approach we can compose any specific type of response.

A Web API controller action can return any of the following:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Some other type

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response.

 

 Return type How Web API creates the response
void Return empty 204 (No Content)
HttpResponseMessage Convert directly to an HTTP response message.
IHttpActionResult Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other type Write the serialized return value into the response body; return 200 (OK).

The IHttpActionResult interface was introducted in Web API 2. Essentially, it defines an HttpResponseMessagefactory. Here are some advantages of using the IHttpActionResult interface:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates anHttpResponseMessage instance.

public interface IHttpActionResult

{

Task ExecuteAsync(CancellationToken cancellationToken);

}

  1. Web API OData

The Open Data Protocol (OData) is actually a web protocol for querying and updating data. ASP.NET Web API 2 has added support for $expand, $select, and $value options for OData. By using these options, we can control the representation that is returned from the server.

  • $expand: Normally, response doesn’t include related entities if we query an OData collection. By using $expand, we can get related entities inline in response.
  • $select: It’s used if we wanted to include subset of properites in response instead of all.
  • $value: It allows to return raw value of the property instead returning in OData format.

 

 

What is ASP.NET Web API 2 ?

What is ASP.NET Web API ?

ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework.
Using ASP.NET Web API we can create non-SOAP based services like plain XML or JSON strings etc. with many other advantages including 1)Create resource-oriented services using the full features of HTTP.2) Exposing services to a variety of clients easily like browsers or mobile devices.

What are the advantages of using ASP.NET Web API?

Using ASP.NET Web API has a number of advantages, but core of the advantages are:

  • It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE etc for all CRUD operations.
  • Complete support for routing.
  • Response generated in JSON or XML format using MediaTypeFormatter.
  • It has the ability to be hosted in IIS as well as self-host outside of IIS.
  • Supports Model binding and Validation.
  • Support for OData.

What new features are introduced in ASP.NET Web API 2.0?

More new features introduced in ASP.NET Web API framework v2.0 are as follows:

  • Attribute Routing
  • External Authentication
  • CORS (Cross-Origin Resource Sharing)
  • OWIN (Open Web Interface for .NET) Self Hosting
  • IHttpActionResult
  • Web API OData

How to restrict access to Web API method to specific HTTP Verb?

Attribute programming plays it’s role here. We can easily restrict access to an ASP.NET Web API method to be called using a specific HTTP method. For example, we may required in a scenario to restrict access to a Web API method through HTTP POST only as follows:

 [HttpPost]
public void UpdateStudent(Student aStudent)

 {
StudentRepository.AddStudent(aStudent);
}

How we can provide an alias name for ASP.NET Web API action?

We can provide an alias name for ASP.NET Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

[HttpPost]
[ActionName(“SaveStudentInfo”)]
public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent); 

 }

CHARINDEX function of MS sql server with examples.

Here I would like to explain CHARINDEX function of sql server with examples.
CHARINDEX is used to get starting position of the specified expression in a string.
Syntax of CHARINDEX Function :

CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] ) or

CHARINDEX (expression1 ,expression2 [ ,start_location ] )

expression1 is a sequence of characters to be found from expression2. It is of short character data type.

expression2 is a string from which expression1 is searched. It is of character string data type.

start_location is a position to start searching for expression1 in expression2. It is an optional field. If you don’t specify or specify 0 or negative number the search starts from beginning of expression2.

It returns an integer value.
Examples of CHARINDEX Function :

Example 1 : Use of CHARINDEX function in select clause

SELECT CHARINDEX(‘ax’,’Syntax-Example-Syntax’,0)
OR
SELECT CHARINDEX(‘ax’,’Syntax-Example-Syntax’)

Output
5

Above example returns position of starting index for characters ‘ax’ in specified string. It starts searching from beginning of the string. As it starts searching from beginning of the string, it returns position of 1st occurrence of ‘ax’ from expression2.
SELECT CHARINDEX(‘ax’,’Syntax-Example-Syntax’,6)
Output
20

Above example returns position of starting index for characters ‘ax’ in specified string, this time it starts searching after starting 6 characters. As it starts searching after 6 characters, it returns position of 2nd occurrence of ‘ax’ from expression2.
Example 2 : Use of CHARINDEX function to display field value of table

SELECT ContactName, CHARINDEX(‘an’,ContactName) AS ‘Index’
FROM Customers

Output
ContactName Index
Maria Anders 7
Ana Trujillo 1
Antonio Moreno 1
Thomas Hardy 0
Christina Berglund 0
Hanna Moos 2

Above example displays starting position of ‘an’ in all customer names from customers table.

Example 3 : Use of CHARINDEX function in where clause

SELECT ContactName
FROM Customers
WHERE CHARINDEX(‘an’,ContactName) > 0

Output
ContactName
Maria Anders
Ana Trujillo
Antonio Moreno
Hanna Moos

Above example displays all customer names having substring ‘an’ in customer name of customers table.

Dependency inversion in C#.Net

Introduction

In this article we will talk about the Dependency Inversion Principle, Inversion of Control and Dependency Injection. We will start by looking at the dependency inversion principle. We will then see how we can use inversion of control to implement dependency inversion principle and finally we will look at what dependency injection is and how can it be implemented.

Before we start talking about Dependency Injection(DI), we first need to understand the problem that DI solves. To understand the problem, we need to know two things. First dependency Inversion Principle(DIP) and second  Inversion of Controls(IoC). let us start our discussion with DIP, then we will talk about IoC. once we have discussed these two, we will be in a better position to understand Dependency Injection, so we will look at dependency injection in details. Then finally we will discuss see how can we implement Dependency injection.

Dependency Inversion Principle

Dependency inversion principle is a software design principle which provides us the guidelines to write loosely coupled classes. According to the definition of Dependency inversion principle:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions.

What does this definition mean? What is it trying to convey? let us try to understand the definition by looking at examples. A few years back I was involved in writing a windows service which was supposed to run on a Web server. The sole responsibility of this service was to log messages in event logs whenever there is some problem in the IIS application Pool. So what our team has done initially that we created two classes. One for monitoring the Application Pool and second to write the messages in the event log. Our classes looked like this:

class EventLogWriter

{

public void Write(string message)

{

//Write to event log here

}

}

 class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

EventLogWriter writer = null; 

// This function will be called when the app pool has problem

public void Notify(string message)

{

if (writer == null)

{

writer = new EventLogWriter();

}

writer.Write(message);

}

}

From the first look, the above class design seems to be sufficient. It looks perfectly good code. But there is a problem in the above design. This design violates the dependency inversion principle. i.e. the high level module AppPoolWatcher depends on EventLogWriter which is a concrete class and not an abstraction. How is it a problem? Well let me tell you the next requirement we received for this service and the problem will become very clearly visible.

The next requirement we received for this service was to send email to network administrator’s email ID for some specific set of error. Now, how will we do that? One idea is to create a class for sending emails and keeping its handle in the AppPoolWatcher but at any moment we will be using only one object either EventLogWriter or EmailSender.

The problem will get even worse when we have more actions to take selectively, like sending SMS. Then we will have to have one more class whose instance will be kept inside the AppPoolWatcher. The dependency inversion principle says that we need to decouple this system in such a way that the higher level modules i.e. the AppPoolWatcher in our case will depend on a simple abstraction and will use it. This abstraction will in turn will be mapped to some concrete class which will perform the actual operation. (Next we will see how this can be done)

 Inversion of Control 

Dependency inversion was a software design principle, it just states that how two modules should depend on each other. Now the question comes, how exactly we are going to do it? The answer is Inversion of control. Inversion of control is the actual mechanism using which we can make the higher level modules to depend on abstractions rather than concrete implementation of lower level modules.

So if I have to implement inversion of control in the above mentioned problem scenario, the first thing we need to do is to create an abstraction that the higher levels will depend on. So let us create an interface that will provide the abstraction to act on the notification received from AppPoolWacther.

 

public interface INofificationAction

{

public void ActOnNotification(string message);

}

Now let us change our higher level module i.e. the AppPoolWatcher to use this abstraction rather than the lower level concrete class.

class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

INofificationAction action = null;

 

// This function will be called when the app pool has problem

public void Notify(string message)

{

if (action == null)

{

// Here we will map the abstraction i.e. interface to concrete class

}

action.ActOnNotification(message);

}

}

So how will our lower level concrete class will change? how will this class conform to the abstraction i.e. we need to implement the above interface in this class:

class EventLogWriter : INofificationAction

{

public void ActOnNotification(string message)

{

// Write to event log here

}

}

So now if I need to have the concrete classes for sending email and sms, these classes will also implement the same interface.

class EmailSender : INofificationAction

{

public void ActOnNotification(string message)

{

// Send email from here

}

}

 

class SMSSender : INofificationAction

{

public void ActOnNotification(string message)

{

// Send SMS from here

}

}

So the final class design will look like:

So what we have done here is that, we have inverted the control to conform to dependency inversion principle. Now our high level modules are dependent only on abstractions and not the lower level concrete implementations, which is exactly what dependency inversion principle states.

But there is still one missing piece. When we look at the code of our AppPoolWatcher, we can see that it is using the abstraction i.e. interface but where exactly are we creating the concrete type and assigning it to this abstraction. To solve this problem, we can do something like:

class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

INofificationAction action = null;

 

// This function will be called when the app pool has problem

public void Notify(string message)

{

if (action == null)

{

// Here we will map the abstraction i.e. interface to concrete class

writer = new EventLogWriter();

}

action.ActOnNotification(message);

}

}

But we are again back to where we have started. The concrete class creation is still inside the higher level class. Can we not make it totally decoupled so that even if we add new classes derived from INotificationAction, we don’t have to change this class.

This is exactly where Dependency injection comes in picture. So its time to look at dependency injection in detail now.

Dependency Injection

Now that we know the dependency inversion principle and have seen the inversion of control methodology for implementing the dependency inversion principle, Dependency Injection is mainly for injecting the concrete implementation into a class that is using abstraction i.e. interface inside. The main idea of dependency injection is to reduce the coupling between classes and move the binding of abstraction and concrete implementation out of the dependent class.

Dependency injection can be done in three ways. 

  • Constructor injection
  • Method injection
  • Property injection
  • Constructor Injection

In this approach we pass the object of the concrete class into the constructor of the dependent class. So what we need to do to implement this is to have a constructor in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

 class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

INofificationAction action = null;

public AppPoolWatcher(INofificationAction concreteImplementation)

{

this.action = concreteImplementation;

// This function will be called when the app pool has problem

public void Notify(string message)

{

action.ActOnNotification(message);

}

}

In the above code, the constructor will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter’s concrete implementation into this class, all we need to do is

EventLogWriter writer = new EventLogWriter();

AppPoolWatcher watcher = new AppPoolWatcher(writer);

watcher.Notify(“Sample message to log”);

Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher’s constructor. This method is useful when we know that the instance of the dependent class will use the same concrete class for its entire lifetime.

Method Injection 

In constructor injection we saw that the dependent class will use the same concrete class for its entire lifetime. Now if we need to pass separate concrete class on each invocation of the method, we have to pass the dependency in the method only.

So in method injection approach we pass the object of the concrete class into the method the dependent class which is actually invoking the action. So what we need to do to implement this is to have the action function also accept an argument for the concrete class object and assign it to the interface handle this class is using and invoke the action. So if we need to implement this for our AppPoolWatcher class:

class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

INofificationAction action = null;

 

// This function will be called when the app pool has problem

public void Notify(INofificationAction concreteAction, string message)

{

this.action = concreteAction;

action.ActOnNotification(message);

}

}

In the above code the action method i.e. Notify will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter’s concrete implementation into this class, all we need to do is

 EventLogWriter writer = new EventLogWriter();

AppPoolWatcher watcher = new AppPoolWatcher();

watcher.Notify(writer, “Sample message to log”);

Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher’s invocation method i.e. Notify method in the above example.

Property Injection 

Now we have discussed two scenarios where in constructor injection we knew that the dependent class will use one concrete class for the entire lifetime. The second approach is to use the method injection where we can pass the concrete class object in the action method itself. But what if the responsibility of selection of concrete class and invocation of method are in separate places. In such cases we need property injection.

So in this approach we pass the object of the concrete class via a setter property that was exposed by the dependent class. So what we need to do to implement this is to have a Setter property or function in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

class AppPoolWatcher

{

// Handle to EventLog writer to write to the logs

INofificationAction action = null; 

public INofificationAction Action

{

get

{

return action;

}

set

{

action = value;

}

// This function will be called when the app pool has problem

public void Notify(string message)

{

action.ActOnNotification(message);

}

}

In the above code the setter of Action property will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter’s concrete implementation into this class, all we need to do is

EventLogWriter writer = new EventLogWriter();

AppPoolWatcher watcher = new AppPoolWatcher();

// This can be done in some class

watcher.Action = writer; 

// This can be done in some other class

watcher.Notify(“Sample message to log”);

Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the setter exposed by AppPoolWatcher class. This approach is useful when the responsibility of selecting the concrete implementation and invoking the action are done in separate places/modules.

In languages where properties are not supported, there is a separate function to set the dependency. This approach is also known as setter injection. The important thing to note in this approach is that there is a possibility that someone has created the dependent class but no one has set the concrete class dependency yet. If we try to invoke the action in such cases then we should have either some default dependency mapped to the dependent class or have some mechanism to ensure that application will behave properly.

A Note on IoC Containers 

Constructor injection is the mostly used approach when it comes to implementing the dependency injection. If we need to pass different dependencies on every method call then we use method injection. Property injection is used less frequently.

All the three approaches we have discussed for dependency injection are ok if we have only one level of dependency. But what if the concrete classes are also dependent of some other abstractions. So if we have chained and nested dependencies, implementing dependency injection will become quite complicated. That is where we can use IoC containers. IoC containers will help us to map the dependencies easily when we have chained or nested dependencies.

 

Cursor vs Merge in SQL SERVER 2008

Cursor vs Merge
 
Today we’ll have a look at Microsoft SQL Server programming and specifically the CURSOR and MERGE statements.
A cursor can be used to loop through a set of rows programmatically.  Their use is discouraged because they tend to perform poorly.  It’s usually faster to work with a set of records instead of ‘walking through’ a table, one row at a time.
Let’s have a look at the difference in performance between a cursor and the merge statement.
Imagine a table with stock prices (dbo.Securities) that is updated with new prices every day.
After each update, we want to move SecurityID, Price and PriceDate to the dbo.PriceHistory table.
We will need to check if the combination of SecurityID and PriceDate exists in the target table.  If it doesn’t then we will INSERT a new row.  If it does exist then we will have to UPDATE the existing record.
We could write a stored procedure that uses a cursor as follows:
CREATE PROCEDURE dbo.SP_InsertPriceHistory AS 
SET NOCOUNT ON;
DECLARE @MySecID int;
DECLARE @MyDate date;
DECLARE @MyPrice numeric(12,4);
 
DECLARE MyCur CURSOR FAST_FORWARD
  FOR SELECT Securityid, Price, PriceDate
  FROM dbo.Securities ORDER BY SecurityID;
OPEN MyCur;
FETCH NEXT FROM MyCur INTO @MySecID, @MyPrice, @MyDate;
WHILE @@FETCH_STATUS = 0
BEGIN
  –Check if record exists    
  IF EXISTS (SELECT * FROM dbo.PriceHistory 
             WHERE PriceDate = @MyDate and SecurityID = @MySecID)
    BEGIN
      –Record exists – Update
      UPDATE dbo.PriceHistory SET PriceDate = @MyPrice 
        WHERE (SecurityID = @MySecID AND PriceDate = @MyDate);
    END
  ELSE
    BEGIN        
      –Record does not exist – Insert
      INSERT INTO dbo.PriceHistory (SecurityID, PriceDate, Price)
        VALUES(@MySecID, @MyDate, @MyPrice);        
    END
  FETCH NEXT FROM MyCur INTO @MySecID, @MyPrice, @MyDate;
END
CLOSE MyCur;
DEALLOCATE MyCur;
We can achieve the same result using the Merge statement.  The stored procedure might look like this:
CREATE PROCEDURE dbo.SP_InsertPriceHistory AS 
SET NOCOUNT ON;
MERGE INTO dbo.PriceHistory AS TGT
  USING dbo.Securities AS SRC
  ON SRC.SecurityID = TGT.SecurityID AND 
    SRC.PriceDate = TGT.PriceDate
  WHEN MATCHED THEN
    UPDATE SET TGT.Price = SRC.Price;
  WHEN NOT MATCHED THEN 
    INSERT VALUES(SRC.SecurityID, SRC.PriceDate, SRC.Price);
SQL server will check for a match between the source and target table by comparing both the SecurityID and PriceDate columns.
If there is a match then it will run the code after WHEN MATCHED THEN
If there is no match then it means that no price is stored for this particular security on this date and it will run the code after WHEN NOT MATCHED THEN
Not only is this code easier to read, it is also much faster.  On a table with approx. 2500 records, the cursor took 124 milliseconds to finish.  The merge statement finished in 32 milliseconds.
For more details on Merge have a look at Merge on Microsoft technet.
PS we can slightly improve the performance of both stored procedures by checking if an update is really necessary.  We can do this by comparing the price of the source with the price of the target table.  If the price is the same then we can skip the update.