Wednesday, December 25

ASP.Net Identity and Profile Customization in Visual Studio 2013

Introduction: ASP.NET Identity is the new membership system for ASP.NET applications. In the existing ASP.net, the information about user and profile are stored in separate tables. The profile information about the user was handled by profile provider. This makes it hard to customize profile data and associate it with user and application data. ASP.net makes it easy to add profile data for user.

Steps:

Create a new ASP.Net Application with MVC Template : Open Visual Studio 2013 |New Project|ASP.Net Web Application |select MVC.

Run the existing Register Page: It takes username and password. We’ll add new fields such as ‘First Name’, ’Last name’, ’Email’, ’Language’, and ‘Country to store these additional information when a user registers.


Enable Entity Framework Code First Database Migration: Open Package Manager Console and run the command- "Enable-Migrations".




Add new properties to Model: In the solution explorer, open “Models” folder and then open “IdentiModels.cs” file. We’ll add the new fields as properties.


Add New Migration and update Database - execute the following commands in “Package Manager Console”. Use these two commands : Add-Migration "nameofyourprofile" and Update-Database.





Check the ASPNetUsers table and verify the new fields:


Update Model: Open RegisterViewModel from Models| AccountViewModels| RegisterViewModel  in the solution explorer.
The "Models" folder should like this:



Update View: Open Register.cshtml from Views |Account |Register.cshtml




Update Controller: Open Register from Controller |AccountController | Register





Run the project : Build and Run the project. 

After registering the user, you should see the user's information in the table. Browse as  View |Server Explorer |Tables |ASPNetUsers. Right click on "ASPNetUsers"  table and select "show table data".




Saturday, December 21

ASP.NET Scaffolding- Visual 2013

Introduction: ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects.Scaffolding helps to add code quickly that interacts with data.It reduces significant amount of time to develop standard data operations in project.

Steps:

Open Visual studio 2013 and create 2013 ASP.net Web application. Add a name and select a path to save this project.

Next select MVC template.



Database:

Add data : View- Server explorer. 


Right click “Data Connection” node ->select "Add Connection" and then enter your server name. Test connection and then click “ok”.



 It’ll create a database as your servername.master.db under “Data connection” node. 
 Right click on your database name and select “query” . It opens up sql window. Add the following query and press “ctrl+shift+E” to execute the query. It’ll create a “Book” table and add three records.



Model:
In solution explorer right click “Models” folder and then select “Add” and then “New Item”. It’ll open “Add New item” window. Select “data” and “Ado.net Entity Data Model” and click “Add”. 


Select  “Generate From Database” option from “Entity data Mode wizard” and hit “next”. 


Select data connection you created and save this connection and click “next”. Select “Tables” option in next screen and click “finish”.

The "Models" folder should look like this:


Controller:
 Right click “controllers” folder and then select “add” and then select “new scaffolded item”. Select “MVC5 controller with Views, using Entity Framework”


View:
Compile the project and  find your folder under the “views” folder in solution explorer. Right click on “index.cshtml” and select “view in browser”.


Output:

Saturday, December 14

Hot Spot Analysis (Gettis-OrdGi*)

Introduction: Spatial Statistics assess patterns, trends, distribution and relationships. We’ll use Spatial Autocorrelation tool to see if features are clustered or dispersed. The spatial Autocorrelation is based on Tobler’s First Law of Geography which says everything is related to everything-but nearby things are more related than things are far away. It’s the correlation of a variable with itself through space. The output gives Z scores for distance.
Hotspot analysis uses vectors to identify the locations of statistically significant hot spots and cold spots in data. Hotspot Analysis finds features with similar attribute values spatially cluster together. Hotspot analysis Getis ord GI* statistic can delineate clusters of features with values significantly higher or lower than the overall study areas mean/average.  It calculates Z score and P value for each feature. A high Z score and small P value for a feature indicates a significant hot spot. A low negative Z score and small P value indicates a significant cold spot. The higher (or lower) the Z score, the more intense the clustering. A Z score near zero means no spatial clustering.


The example shows distribution of social characteristics (Female householder) and Hospital readmission penalties for selected hospitals in Illinois. The penalty data was collected from Kaiser Health (kaiserhealthnews.org) and Female householder data was downloaded from American Community Survey. I built a thematic map from data of Female householder by ZIP and then layered it with penalty data. It looks like there is some relation between hospitals with high penalty rate and location where higher concentration of female householder reside. We’ll use hotspot analysis of Female householder data to see if the clusters are statistically significant.


Frequency Distribution of Penalties:


Frequency Distribution of Female Householder:
Hotspot Analysis of Female householder data:

We use Arc GIS tool to run Incremental Spatial Autocorrelation and hotspot analysis.






Output:





Monday, December 9

OData service in Visual studio LightSwitch

Introduction: Exposing data through the Web/Network is a very common business need. It is done by services that can be consumed by several clients.There are many APIs to expose and consume data. The OData (Open Data Protocol) provides a standardized way to expose, structure, query and update data, based on REST approach. OData also provides metadata about data, allowing computer to know more about the type system, relationships and structure of data. It is built upon web technologies such as HTTP, Atom publishing Protocol AND JSON and provides access to information from a variety of applications, services and stores.

Currently there are lot of public OData services that can be used. Few of them are:



In this demo, I'll consume data from http://services.odata.org/OData/OData.svc/  and display the data from advertisement entity.

 Steps:

  1. Open Visual Studio 2012.
  1. Go to "File" => "New" => "Project..."
  1. Select "LightSwitch" in installed templates.
  1. Select "LightSwitch Application (Visual C#)".
  1. Enter the Name and choose the location.
  1. Click "OK".

Sunday, December 8

ASP.Net Web API - Visual Studio 2012 (C#)

Introduction: Visual Studio 2012 and .Net 4.5 comes with a new web services framework called the ASP.NET Web API. It is designed to simplify the development and consumption of RESTful service.

This sample uses MVC 4 ASP.NET Web API to build a simple Book API application to display a list of books.

Steps:

Create a Web API Project

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project. In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project "bookAPI" and click OK.



In the New ASP.NET MVC 4 Project dialog, select the WebAPI” template.


 Add a Model

model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

We’ll create a simple model that represents a book.
If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class. Name the class "Book". Add the following properties to the Book class.

namespace bookApi.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public decimal Price { get; set; }


    }
}
Add a Controller
In Web API, a controller is an object that handles HTTP requests. The controller will display a list of books.
In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.
In the “Add Controller” dialog  select “Empty API Controller”. Click Add.

In the Add Controller dialog, name the controller "BookController". Click Add.

Open BookController.cs and replace the code with the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bookApi.Models;

namespace bookApi.Controllers
{
    public class BookController : ApiController
    {
        Book[] books = new Book[]
        {
            new Book { Id = 1, Title = "Dark Witch", Author = "Nora Roberts", Price = 9 } ,
            new Book { Id = 2, Title = "Fifty Shades Of Grey", Author = "E.L.James", Price = 8 },
            new Book { Id = 2, Title = "The Harbinger", Author = "Jonathan Cahn", Price = 10}
           
        };

        public IEnumerable<Book> GetAllBooks()
        {
            return books;
        }

      
        }

    }


Test the Output:
Press ctrl + f5 and then append api/book with your URL. It should look like http://localhost:yourportNumber/api/book.  It will ask if you want to open or save “book.Json” from localhost. Open and you should see the following output:
Output:
[{"Id":1,"Title":"Dark Witch","Author":"Nora Roberts","Price":9.0},{"Id":2,"Title":"Fifty Shades Of Grey","Author":"E.L.James","Price":8.0},{"Id":2,"Title":"The Harbinger","Author":"Jonathan Cahn","Price":10.0}]

Call the Web API with Javascript and jQuery
We'll add a HTML page that uses AJAX to call the web API.
In Solution Explorer, right-click the project and select Add, then select New Item.
In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "default.html".
Replace code with the following code:
--default,html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Product App</title>
</head>
<body>

  <div>
    <h2>All Books</h2>
    <ul id="books" />
  </div>
 

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
  <script>
      var uri = 'api/book';

      $(document).ready(function () {
          // Send an AJAX request
          $.getJSON(uri)
              .done(function (data) {
                  // On success, 'data' contains a list of books.
                  $.each(data, function (key, item) {
                      // Add a list item for the book.
                      $('<li>', { text: formatItem(item) }).appendTo($('#books'));
                  });
              });
      });

      function formatItem(item) {
          return "id:" + item.Id   +  "  Author : " + item.Author +  "   Title: " + item.Title +  "  Price: $"  + item.Price;
         

      }

     </script>
</body>
</html>

Run the Application

Press cntl+f5 and then append default.html  as http://localhost:portnumner/default.html and it should
look like the following :