Thursday, 21 January 2016

Simple way to Develop , Build and Deploy your windows AZURE Cloud Service

AZURE Cloud Service



In this article, we are going to walk through how to create  and deploy your Windows AZURE Cloud Service.
It also provides a good introduction on how to quickly  create and set up your Windows AZURE Cloud Service for deployment.
 

Cloud Computing

The "cloud" in cloud computing can be defined as the set of hardware, networks, storage, services, and interfaces (I.T Infrastructure) that combine to deliver aspects of computing as a service. Cloud services can be software, infrastructure, and storage over the Internet (either as separate components or a complete platform) based on user demand.
It can also be defined next stage in the Internets evolution, providing the means by which everything — from computing power to computing infrastructure, applications and business processes can be delivered to you as a service wherever and whenever you need and will be charged on basis of usage like we use electricity and pay on basis of monthly usage..

Some businesses, such as Google and Amazon, already have most of their IT resources in the cloud. They have found that it can eliminate many of the complex constraints from the traditional computing environment, including space, time, power, and cost.
Now coming to Microsoft they have also setup cloud computing for their customers known as AZURE.

AZURE

Microsoft way of cloud computing :) Windows Azure is Microsoft's application platform for the public cloud. You can use this platform in many different ways. For instance, you can use Windows Azure to build a web application that runs and stores its data in Windows Azure data centers. You can use Windows Azure just to store data, with the applications that use this data running on-premises (that is, outside the public cloud). You can use Windows Azure to create virtual machines for development and test or to run SharePoint and other applications. You can use Windows Azure to build massively scalable applications with lots and lots of users. Because the platform offers a wide range of services, all of these things-and more-are possible.
 

Develop,Build and Deploy your windows AZURE Cloud Service in Steps



STEP 1. CREATE AN ACCOUNT
If you already have an account, connect by clicking on PORTAL

STEP2: CREATE A SERVICE CLOUD

  • Click on CLOUD SERVICE tab and  Click New (+ New)
Here it is possible to create a Quick Cloud Service and configure it again later or create a custom cloud service by chosing configuration.
  • So lets create a Quick Cloud Service and fill parameters such as URL, REGION OR AFFINITY GROUP , SUBSCRIPTION. Next click on link Create Cloud Service


  • Service created screen
        
Our Cloud Service is now created Quickly or Customized, lets get Azure SDK Tools so as to code our service logic.
  • Click on OurCustomersService and click on link install a Windows AZURE SDK, and our Visual Studio Version and Install it.
STEP 3: CREATE A CLOUD SERVICE PROJECT
Here we are going to create a WCF Service and deploy it on our cloud Service.
  • So, create a new Project ,chose Windows Azure Cloud Service template and WCF Service Web Role.
A web role provides an environment for running web sites or applications as supported by Internet Information Services (IIS) 7.0


  • WCF web Service (OurCustomersService.svc) looks like as shown below:

  • To test this service locally first just create console application ,windows or web what ever you are comfort with .just fallow below steps
 
  1.   I will create windows console application to test this service
 



OUTPUT FROM THIS SERVICE IS:-



 Now Deployment

STEP 4 : DEPLOY A CLOUD SERVICE PROJECT
  • To deploy our Cloud Service, we have to Create a Package : chose our Service Configuration and Build Configuration and note the output directory or remove files to our custom directory.
  • Next , Go back again to our Portal, click on OurCustomersService,  and click on link New production deployment
  • Next  chose a deployment name and our Package and configuration files
  • Now reference our Cloud Service and test It

Hope this help..


Shabir

Sunday, 10 January 2016

How to retrieve a visitor's IP address,Region and other details

BRIEF INTRODUCTION:-

Every visitor i mean any user coming to your website/web application has an IP address. If  you want to keep track of user ip address along with other details. I
The issue  is when they're behind a proxy . So, here are the code snippets in ASP and .Net that first check for an IP addresses that's forwarded from behind a proxy, and if there's none then just get the IP address.


And here's the IP retriever with proxy detection in .Net (C#)

public string IpAddress()
{
    string strIpAddress;
    strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (strIpAddress == null)
    {
       strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
    }
    return strIpAddress;
}
And here's the same IP retriever with proxy detection in .Net, but in VB.Net (CODE BEHIND FILE OR FUNCTIONS)

Public Function IpAddress()
    Dim strIpAddress As String
    strIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If strIpAddress = "" Then
       strIpAddress = Request.ServerVariables("REMOTE_ADDR")
    End If
    IpAddress = strIpAddress
End Function
Now question is how you retieve all the details like counry,region,region code ,latitite and logitute
Here is the complate code for getting all details about user 
 private string GetVisitor()
{
//client connecting to a web server through an HTTP proxy or load balancer
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;}
private DataTable GetLocation(string strIPAddress)
{
WebRequest rssReq = WebRequest.Create("http://freegeoip.net/xml/" + 
strIPAddress);
WebProxy px = new WebProxy("http://freegeoip.net/xml/" + strIPAddress, true);
rssReq.Proxy = px;
rssReq.Timeout = 2000;
try
{
WebResponse rep = rssReq.GetResponse();
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
DataSet ds = new DataSet();
ds.ReadXml(xtr);
return ds.Tables[0];
 }
catch
{return null;}
}
protected void btnGetIpaddress_Click(object sender, EventArgs e){
try{
DataTable dt = new DataTable();
dt = GetLocation(GetVisitor());
if (dt.Rows.Count > 0)
{
dvIpaddressdetail.DataSource = dt;
dvIpaddressdetail.DataBind();
}
string ipaddress= dt.Rows[0].Field<string>(0);
}
catch (Exception ex)
{
throw ex;
}
}


ASPX PAGE
 <div class="middle-form" >
<form name="form" autocomplete="off" runat="server">
<div class="row">
<h3 style="margin-left:20%;"> Lookup IP address and Domain location now with our 
free IP Locator.</h3>
</div>

<div class="row"> 
<asp:TextBox ID="txtipaddress" runat="server" Text="182.68.166.132" 
CssClass="text-holder"></asp:TextBox
</div>
<div class="row"> 
<asp:Button ID="btnGetIpaddress" runat="server" Text="Lookup IP Address With IP 
Lookup" OnClick="btnGetIpaddress_Click" CssClass="btn btn-blue"/> </div>

<div class="row" style="margin-top:15px!important;"><br />
<asp:DetailsView ID="dvIpaddressdetail" runat="server" Width="100%" 
CellPadding="4" ForeColor="#333333" GridLines="None" HeaderText="IP ADDRESS 
DETAIL" BorderColor="#EEEEEE" BorderStyle="Solid">
<AlternatingRowStyle BackColor="White" />

<CommandRowStyle BackColor="#F9F9F9" Font-Bold="True" />

<FieldHeaderStyle BackColor="#F2F2F2" Font-Bold="True" />

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#0099FF" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
</asp:DetailsView>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
ControlToValidate="txtipaddress" ErrorMessage="*"></asp:RequiredFieldValidator>

<asp:HiddenField ID="txtlat" runat="server" ClientIDMode="Static" />

<asp:HiddenField ID="txtlon" runat="server" ClientIDMode="Static" />

</div>
</form>
</div>


See live demo of this http://shabirhakim.net/Tools/GetMyIPAddress.aspx

Tuesday, 22 December 2015

WEBAPI FOR BEGINERS OR FRESHERS

ASP.NET Web API

Introduction

A web API is just an application programming interface (API) over the web (that is, HTTP). When the resources of an application can be manipulated over HTTP using the standard HTTP methods of GET, POST, PUT, and DELETE, you can say that the application supports a web API for other applications to use. Because HTTP is platform-agnostic, HTTP services can be consumed by disparate devices across different platforms.
 A central concept of HTTP services is the existence of resources that can be identified through a uniform resource identifier (URI). If you equate resources to nouns, then actions on a resource can be equated to verbs and are represented by the HTTP methods such as GET, POST, PUT, and DELETE. For an application that deals with the Users of an organization, each User is a resource the application deals with.
 Let us see how an User’s details can be retrieved with an HTTP service. The URI is http://server<port>/API/Users/1000. It includes the User ID and serves as an identifier to the resource, which is an User in this case. Actions on this resource are accomplished through the HTTP verbs. To get the details of an User, you will perform an HTTP GET on the URIhttp://server<port>/API/Users/1000. To update this User, the request will be an HTTP PUT on the same URI. Similarly, to delete this User, the request will be an HTTP DELETE request, again on the same URI. To create a new User, the request will be an HTTP POST to the URI without any identifier (http://server<port>/API/Users).

LET US CREATE WEBAPI

Let us do something practical here. you will create a simple web API that basically exposes an in-memory List<User> over HTTP, for a client application to manipulate the list members. I know this is just limited or small concept but i am sure this will give you clear concept about what webAPI is and how to use it or will give you  understanding how to use the ASP.NET Web API framework to build your web API.

  1. Run Visual Studio and create a new project like shown below Give the project a name of Users and click OK, as shown in Figure 1-1.
  2. Select the ASP.NET Web template and click OK. You will see lots of option, as shown in Figure 1-2.



  3. Choose the Controllers folder in the Solution Explorer of Visual Studio. Select Add ➤ Controller and give a name of UsersController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click Add, as shown in Figure 1-3. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework.
  4. Right-click the Models folder in the Solution Explorer of Visual Studio. Select Add ➤ Class to add a new class with a name of User
  5. Add the code shown in Listing 1-3 to the User class. Listing 1-3. The User Class
    public class User
    {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    }
    
  6. Create a new static field at the controller level, as shown in Listing 1-4. This will be the list that our web API exposes over HTTP. Figure 1-3. Adding a controller
    Listing 1-4. The List of Users
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using Users.Models;
    namespace Users.Controllers
    {
    public class UsersController : ApiController
    {
    private static IList<User> list = new List<User>()
    {
    new User()
    {Id = 1000, FirstName = "Shabir", LastName = "Hakim" },
    new User()
    {Id = 1001, FirstName = "Raja", LastName = "Public"},
    new User()
    {Id = 1002, FirstName = "Rani", LastName = "Private"},
    new User()
    {Id = 1003, FirstName = "Shabir", LastName = "Robert" }
    };
    // Action Get methods go here
    // GET api/Users
    public IEnumerable<User> Get()
    {return list;}
    // GET api/Users/1000
    public User Get(int id)
    {return list.First(e => e.Id == id);}
    }
    }
    
    Note Note: Since you used the User class, which is in a different namespace than HelloWebApi.Models in the controller class, you will need to add a using directive. In Visual Studio, the User references in the preceding code will have a wavy underline in red; right-click any of them and select Resolve ➤ using HelloWebApi.Models. This will add the necessary directive. This is a standard procedure and I will not repeat this step in later exercises, for the sake of brevity.
  7. Add five action methods, as shown in Listing 1-5. It is important to use the name as shown in the listing. You will learn more about why you must follow this naming convention in the next exercise. Listing 1-5. The Action Methods to Get, Post, Put, and Delete Users
    // GET api/Users
    public IEnumerable&ltUser> Get()
    {
    return list;
    }
    // GET api/Users/1000
    public User Get(int id)
    {
    return list.First(e => e.Id == id);
    }
    
    // POST api/Users
    public void Post(User User)
    {
    int maxId = list.Max(e => e.Id);
    User.Id = maxId + 1;
    list.Add(User);
    }
    // PUT api/Users/1000
    public void Put(int id, User User)
    {
    int index = list.ToList().FindIndex(e => e.Id == id);
    list[index] = User;
    }
    // DELETE api/Users/1000
    public void Delete(int id)
    {
    User User = Get(id);
    list.Remove(User);
    }
    
  8. Build the Visual Studio solution and run it by pressing F5. Internet Explorer, which is the default browser associated with Visual Studio, shows the home page with a URL of http://localhost:55778/. (My ASP.NET Web API project uses port 55778. Your project will use a different one and based on that, Internet Explorer will display a different port in the URL.)
  9. In the address bar type http://localhost:<port>/api/Users Replace <port> with the actual port your application runs on.
    NoteNote:As you work through the exercises in this book, you will create several new projects, and the port will change every time you create a new ASP.NET MVC project. Remember to replace the port specified in the example code with your application’s actual port.
  10. When Internet Explorer asks if you want to open or save, click Open and choose Notepad as the program to open the file. Notepad will display JSON as shown in Listing 1-6. I have formatted the output for your reading pleasure.

  11. You can also get the details of a specific User by performing an HTTP GET on http://localhost:63482/Api/Users/1000. In this case, you get the JSON output shown in Listing 1-7.

  12. If you see the preceding two JSON outputs, you have just created your first web API and exposed the in-memory list of Users to the outside world over HTTP! Currently, we have tested only the HTTP GET but we will test the other methods in the upcoming exercises.
     

Saturday, 12 September 2015

What is MongoDB and how it differs from RDMS ? USING MongoDB with Visual studio and C#

ASSUMPTION:You have basic knowledge of Sql and c# and you have created already user table(collection ) in mongodb.
2. You have downloaded mongodb driver . I choose N-Get package manager. here is screen shot of how to refer mongodb driver


3.Set references to your visual studio project like shown below

INTRODUCTION:Let us just recall how our traditional RDBM looks like, It is just based on tables made of rows and columns.Similarly  mongoDB are based on collection of documents, with each of these documents consisting of key/value attributes(JSON format).  A single document can be thought of as the equivalent of a row in a table, with each key being similar to a column name and each key’s value being similar to the respective row’s value.
Here is the view of database collection where four rows(documents) are saved





The exact difference being that a document is not constrained to a certain schema or columns within a table.  Two documents can share similar elements, like an ID field, as well as having completely different elements.   Data representation in both look like shown below

RDBMS NOSQL
.
.

just to recap, MongoDB is made up of databases which contain collections. A collection in turn is made up of documents.Each document is made up of fields. Collections can be indexed, which improves lookup and sorting performance.  The core difference is that relational databases define columns at the table level whereas a document-oriented database defines its fields at the document level. 
In MongoDB, the data structure and hierarchy are like:
Databases
   Collections
      Documents
         Fields
A field is a key-value pair. A key is a name (string). A value is a basic type like string, integer, float, time-stamp, binary, etc., or a document, or an array of values.
Conclusively you can say, collections are made of JSON-like documents. This is the main difference from traditional RDBM.
Note: The  BSON  is a binary-encoded serialization of J SON-like documents.It is just lightweight, traversable, and efficient.

Why MongoDB

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling what else you need if your business data is huge or growing fast ?

IMPORTANT CONCEPTS

  • A database can have zero or more collections. A collection shares enough in common with a traditional table that you can safely think of the two as the same thing.
  • Collections are made up of zero or more documents. Again, a document can safely be thought of as a row.
  • a lot like columns.
  • Indexes in MongoDB function mostly like their RDBMS(oracle sql server,sybase) counterparts.

The Benefits of NoSQL

  • Large volumes of structured, semi-structured, and unstructured data
  • Agile sprints, quick iteration, and frequent code pushes
  • Object-oriented programming that is easy to use and flexible
  • Efficient, scale-out architecture instead of expensive, monolithic architecture

Windows Platform Support

Starting from MongoDB version 2.2, MongoDB doesn’t support Windows XP. So if you are on Windows XP, either upgrade it or use the lower versions of MongoDB. This tutorial is intended to help you in installing MongoDB on Windows latest versions i.e Windows 7 and Windows 8, 8.1 etc.

Installation of MongoDB on Windows

Follow below steps to perform the installation of MongoDB into your windows system.
  1. Consider specific MongoDB build type which you need actually Three build types of MongoDB for Windows are available.
MongoDB for Windows Server 2008 R2 series: This build type runs only on 2008R2, Windows 7 64-bit, Windows 8, and latest versions of Windows.
MongoDB for Windows 64-bit: This build type of MongoDB runs on any 64-bit version of Windows latest than Windows XP, involve Windows Server 2008 R2 and Windows 7 64-bit.
MongoDB for Windows 32-bit: MongoDB runs on any 32-bit version of Windows latest than Windows XP, 32-bit version of MongoDB are only designed for older system and use for testing and developing systems. Windows 32-bit versions of MongoDB support only database smaller than 2GB.



  • Download MongoDB for Windows
  • download the latest version release from the MongoDB Download page. Make sure you download the latest version of MongoDB for your Windows. Note that 64-bit versions of MongoDB do not run with 32-bit Windows.
  • MongoDB installation folder move to another location (Optional) Sometimes we want to move the installation to another directory, we can use move command for this. This command needs to be run as administrator. For example, to move the folder to C:\MongoDB follow the steps shown in below images.
  • MongoDB does not depend at any other system because it is self contained. You can execute MongoDB from the folder of your choice and can install it in any folder (for, me it is programFiles folder like C:\Program Files\MongoDB\Server\3.0\bin)

    Running MongoDB Server

    We need to create a directory where MongoDB server will store all it’s data. The MongoDB default data directory path is \data\db. Make this folder using the following commands from Command Prompt. Note that if the directory doesn’t exists, MongoDB will try to create it. But it’s good to create it before hand.
    Microsoft Windows [Version 6.3.9600]
    (c) 2013 Microsoft Corporation. All rights reserved.
    C:\>md \data\db

    To start MongoDB server, we need to run mongod.exe just fallow below listed commands





    Note: I am setting path just to run mongodb from c drive every time rather than going to installation folder every time
    This MongoDB starts the main databases process. The waiting for connection message in the console results determines that the mongod.exe process is complete.

    you will see below







    You can use a different path for data files using the –dbpath option to mongod.exe, for example:

    Getting Started with MongoDB and C#

    So, let’s get started!

    EXAMPLE:

    In the MongoDB world, the Document class is the center of it’s universe. Because the very concept of the database is built upon the concept of this document, this is what you’ll find yourself using most. You use them to insert data, update data, delete data, query data. You will find it easy
    Here’s where I’m going to write code it do some database related operations like INSERT UPDATE SELECT..
    Here you see
    Please note that i am not fallowing coding best practice just for the sake of making code more understandable.
    CODE BEHIND FILE

    using MongoDB.Bson;
    using MongoDB.Bson.IO;
    using MongoDB.Bson.Serialization;
    using MongoDB.Bson.Serialization.Serializers;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace AspAppwithMongoDb
    {
    public partial class _Default : Page
    { 
    protected void Page_Load(object sender, EventArgs e)
    { 
    
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName); 
    //get mongodb collection
    var collection = myUser.GetCollection<User>("User");
    //document just like record/row in rdbms
    BsonDocument doc = new BsonDocument();
    doc["FirstName"] = txtFirstName.Text;
    doc["lastname"] = txtLastName.Text;
    collection.Insert(doc);
    lblSuccess.Text = "Saved Successfully";
    }
    
    protected void btnView_Click(object sender, EventArgs e)
    {
    
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName); 
    MongoCollection<User> Users =
    myUser.GetCollection<User>("User");
    nameLabel.Text = nameLabel.Text + "<table class='table'><thead><th>First Name</th><th>Last Name</th></thead>";
    foreach (User usr in Users.FindAll())
    {
    nameLabel.Text = nameLabel.Text + "<tr>";
    nameLabel.Text = nameLabel.Text + "<td>" + usr.FirstName + "</td>";
    nameLabel.Text = nameLabel.Text + "<td>" + usr.lastname + "</td>";
    nameLabel.Text = nameLabel.Text + "</tr>";
    }
    nameLabel.Text = nameLabel.Text + "</table>"; 
    }
    
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName);
    var collection = myUser.GetCollection<User>("User");
    var update = new UpdateDocument { 
    { "$set", new BsonDocument("lastname",txtLastName.Text) } };
    
    var query = new QueryDocument { {"lastname", "" } };
    collection.Update(query, update);
    
    lblSuccess.Text = "Updated Successfully";
    }
    
    }
    public class User
    {
    public ObjectId _id { get; set; }
    public string FirstName { get; set; }
    public string lastname { get; set; }
    } 
    }

    ASPX PAGE


    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="AspAppwithMongoDb._default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <style>
    table{
    width:50%;
    border:1px solid #f2f2f2;
    padding:5px;
    }
    
    </style>
    <asp:Literal ID="nameLabel" runat="server"></asp:Literal>
    <br />
    
    <table>
    <tr><td class="auto-style1">
    <asp:Button ID="btnView" runat="server" Text="View Records" OnClick="btnView_Click" />
    </td><td class="auto-style1" colspan="2">&nbsp;</td></tr>
    <tr><td>FirstName</td><td colspan="2"> <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td></tr>
    <tr><td>LastName</td><td colspan="2"> <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td></tr>
    <tr><td>&nbsp;</td><td colspan="2"> 
    <asp:Label ID="lblSuccess" runat="server" ForeColor="#33CC33"></asp:Label>
    </td></tr>
    <tr><td>&nbsp;</td><td colspan="2"> <asp:Button ID="btnSave" runat="server" Text="Save Record" OnClick="btnSave_Click" /> 
    </td></tr>
    <tr><td>
    First Name Update</td><td>
    <asp:TextBox ID="txtupdatefirstname" runat="server"></asp:TextBox>
    &nbsp;New FirsName</td><td>
    <asp:TextBox ID="txtupdatefirstnameto" runat="server"></asp:TextBox>
    </td></tr>
    
    <tr><td>
    &nbsp;</td><td>
    &nbsp;</td><td>
    <asp:Button ID="btnUpdate" runat="server" Text="Update Record" OnClick="btnUpdate_Click" />
    </td></tr>
    
    </table>
    </div>
    </form>
    </body>
    </html>
    
    WEBCIONFIG.XML




    Using MongoVUE Is just like SQL Management tool which help you to handle database operation using GUI

    A nice GUI makes it easy. Fortunately  for us MongoVUE exists and provides a very pleasant SQL Management Studio like experience over MongoDB
    First download and install MongoVUE.

    Next, run MongoVUE and connect to the default “local” connection. Once connected you should see a User . If you double click the Club node a table view will be rendered, expand the first document to see its data:






    Or click Text View to see the raw document.if you are interested in learning more of its features, read through its tutorials.

    Hope this helps

    Shabir Hakim

    Saturday, 29 August 2015

    Start Working With NodeJS And SqlLite On Windows using Visual Studio


    Assumptions

    This article expects that you have at least a minimal understanding of .NET development and object-oriented programming concepts. With a heavy focus on web development,this article also assumes that you have a basic understanding of ASP.NET, including the core concepts of web development contained in ASP.NET, such as clients and servers,HTML, CSS, JavaScript, and HTTP post/get.
    The article also assumes that you have an IDE in which to work, specifically a fairly recent version of Visual Studio.

    Source code:


    Introduction

    Well, I believe the first thing which comes in mind here is what is nodeJs and why nodeJS?
    If you have working knowledge of JavaScript and some other server side technology like ASP.NET,PHP or JSP then definitely you will understand why nodeJS?

    What is NodeJS

    Till now we had a concept like javascript is meant for client side scripting only but 'NO'. JavaScript has server side version called nodeJS which behaves or is like other server side technologies like asp.net,php,jsp .Node.js  but allows you to run JavaScript code in the back end, outside a browser. In order to execute the JavaScript you intend to run in the back end, it needs to be interpreted and, well, executed. This is what Node.js does, by making use of Google's V8 VM, the same run-time environment for JavaScript that Google Chrome uses.

    Why NodeJS

    Simple, Node.js has great capability when implementing real-time web applications using push technology over web-sockets. What is great about it? It is almost after 2 decades we have worked with stateless of web application, we finally have web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely. This is in contrast to the typical web response pattern , where the client always initiates communication. Apart, it’s all based on the open web stack (HTML, CSS and JS) running over the standard port 80.all free :)
    Plus, Node.js ships with a lot of useful modules, so you don't have to write everything from scratch, like for example something that outputs a string on the console.
    If javascript runs on server side the question arises here is how to install environment to start with  nodeJS .Here are the ways you can setup or install nodeJS
    So you can say nodeJS technology is all about real-time applications

    Features of Node.js

    Following are some of the important features that make Node.js the first choice of software architects.
    • Asynchronous and Event Driven All APIs of Node.js library are asynchronous that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
    • Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
    • Single Threaded but Highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
    • No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.
    • License - Node.js is released under the MIT license

    Install Node.js Tools for Visual Studio

    Available Releases
    • NTVS 1.1 Beta includes support for Visual Studio 2012, 2013, and 2015 RC
    • NTVS 1.0 includes support for Visual Studio 2012 and 2013
    • Dev Builds include the most recent changes and bugfixes (available for Visual Studio 2012, 2013, and 2015)
    • Older NTVS releases are also available.

    Installation Steps:

    STEP1 download windows installer on basis of your visual studio version you have from above location .once downloaded you will find below installer like shown below


    STEP2
    Click on above windows installer, you will see below screen. Accept terms and click Next



    STEP3 NTVS requires a Node.js interpreter to be installed. You can use a global installation of Node.js or you can specify the path to a local interpreter in each of your Node.js projects.
    Node.js is built for 32-bit and 64-bit architectures. NTVS supports both. Only one is required and the Node.js installer only supports one being installed at a time. NTVS works with Node.js v0.10.20 or later.


    Package management

    npm is the pre-installed package manager for the Node.js server platform exactly like Nget Package Manager for .Net IDE environment. It is used to install Node.js programs from the npm registry. By organizing the installation and management of third-party Node.js programs, it helps developers build faster. The packages found in the npm registry can range from simple helper libraries like Underscore.js to task runners like Grunt.
    Below is the screen shot of NPM

    Start a new Node.js project in Visual Studio

    Starting a new Node.js project like shown below
    1. Start Visual Studio.On the File menu, click New, and then click Project like other type of projects.
    2. In the New Project window, expand the Installed menu selection, expand Templates, and click JavaScript. In the main window, select Blank Node.js Web Application. Now your choice of choosing a path and name for your project, and then click OK.

    3. You will be presented with the following screen. You will SEE server.js file in the Solution Explorer .You will see sample or default "Hello world" application  like shown below
    4. You can now debug your node.js web application in your preferred browser like shown below.

    5. OUTPUT will be like

    LET US ANALYZE A DEFAULT  "Hello World" app in Node.js

    Here’s the code used in the server.js file

    The generated code example or sample program shows you how to output "Hello World" in the browser. Let me explain how the generated code in server.js works line by line. 

    Line 1

    var http = require('http');
    Node.js has a simple module and dependencies loading system. You simply call the function "require" with the path of the file or directory containing the module you would like to load at which point a variable is returned containing all the exported functions of that module.

    Line 2

    var port = process.env.port || 1337;
    On this line, we want to determine on which port the HTTP server serving the HTML should run. If a port number is specified in the environment variables, we will use that one or we will simply use 1337.

    Line 3

    http.createServer(function (req, res) {
    We want to create a server to handle HTTP requests. We will also pass the createServer function a function callback containing two parameters to a handle each individual request and return a response.   if you’ve never encountered callback functions in JavaScript. The request received is passed in the req parameter and the response is expected to written to the res parameter.

    Line 4

    res.writeHead(200, { '
    Content-Type’: '
    text/plain’ });
    Any HTTP response requires a status-line and headers, . In this case, we want to return 200 OK as the status response and to specify the content-type as plain text. We specify this by calling the writeHead function on the response object.

    Line 5

    res.end('
    Hello World\n’);
    Once we are done writing the response we want to call the end function. We can also pass the final content through the end function, in this case we want to send the string "Hello World" in plain text.

    Line 6

    }).listen(port);
    We close off the callback and call the function listen at the port we defined earlier, this will start the server and start accepting requests sent to the defined port.
    To see the result, you can start debugging by pressing on the button shown in the previous screenshot. You can see "Hello World" in the browser.



     You have now successfully run a Node.js app on Windows 8.1 using Visual Studio 2013.

    INTERACTING WITH DATABASE:

    For Simplicity I am going to use SQLLite database . you can use any database here is the explanation Database Drivers
    SQLite is transaction database engine, it means you can run DDL and DML queries of SQL. DDL queries deal with creation of database, tables, view etc where as DML queries are responsible for CRUD operation (insert,delete,update) etc. Here is a code to create SQLite database and performing SQL operations.

    GET SQLLITE PACKAGE FOR NODEJS

    Go to nodejs console and run


    Modify existing sample code with below line

    Just Click on Debug/Run in visual studio and the output will be like shown below

    To run and analyse the code, you can simply use breakpoints in visual studio and see whether it creates Employee_Master table  and add two columns[EmployeeId,EmployeeName) with some 10  numbers of rows. You can view number of rows from  console because console.log is displaying all the rows from created table
    OR
    if you will open sqllite database using admin tool you will see below screen with table name Emplyee_Master

    1.  

      More learning for Node on Azure

      For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.

    How to Build a Full-Stack Web App with Blazor

      Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...