Sunday, January 22, 2017

Building Node.js CRUD Rest APIs with Express and Visual studio code


In this blog post, we are going to learn how we can create a basic Rest API with Node.js and Express using Visual Studio code editor.  Our API will contain four operations CREATE, READ, EDIT and DELETE.

Creating Basic Node Express application and common code for REST APIs:

The first thing we need to create an empty folder called NodeJSRestPI folder and then right click and select open with code.


Once you open visual studio code create a file called package.JSON and put following JSON content on that.
    "name": "node-api",
    "main": "api.js",
    "dependencies": {
        "express": "4.14.0",
        "body-parser": "1.16.0"
Here you can see that we are going to use express and body parser npm.  Express is framework for creating Rest APIs and body-parser is to parse body values in JSON. Now once we are done with package.json we need to install node js module via “npm install”. With Visual Studio code, You can directory open command line via clicking on Ctrl + ` Shortcut and then you can run any commands there like following.


Now let’s create a file called API.js and put following JavaScript code into that.
var express = require("express");
var app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: true }));

var port = process.env.port || 3000;
var router = express.Router();

app.use('/api/employee', router);
Here you can see this code is pretty stand code for any express application. Here we  are creating express object with require syntax and then use that app object to create a router and then we have created a port and our app is listening on that port. So our basic application is ready. Now let’s add some common JavaScript code which we are going to use through out whole application.
Since this application is for demo purpose only we are not going to use any database for that and we are going to use a static JavaScript object for our CRUD operations. Following is code for our employee's object. Here you can see it is an array of JavaScript objects of employees. Basically, it contains an array of employee objects. By default, I have put one record there.
var employees= [
        Id: 1,
        FirstName: "Jalpesh",
        LastName: "Vadgama",
        Designation: "Technical Architect"
Another common JavaScript function we are going to use for validation of employee object. Basically, it checks object properties of Employee object. It returns true if the object has all the valid properties otherwise, it will return false. Following is code for the same.
//validation for employee
function isValidEmployee(employee){
        return false;
        return false;
        return false;
        return false;
    return true;
Now we are done with all the code. It’s time to write some code for creating actual operations.

ReadAll/GetAll Operation:

Here we are going to return all the employees available. In our case, we are going to return current employees JavaScript Object. Following is code for the same.
// Get all employees
router.get("/",function (req,res){
Here in the above code, you can see that we use GET HTTP verb returning all the employees available. and Created a get HTTP operation. Now when you run it in postman it will return like following.


Read specific/Get single operation:

In this specific operation, we are going to pass employee id in URL and it will return an employee object available. Following is a code for that.
//get specific employee based on Id
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];

Here in the above code, you can see that we have created get operation, First, we are getting employee id and based on that we are filtering our employees object and getting a current specific employee. If an employee is there we are returning that employee object as JSON else we are sending 404 statuses not found.

Once you run with the postman. It will look like following.


Add/CREATE Employee:

In this operation, We are going to create a POST operation with express and we are going to have employee object as Request body. We are going to validate the employee object with our common validation function. Based on validation function result if all  required properties are available then we are going to add to our exiting employees collection object or else we are going return internal server status. Following is code for that.
/// Add employee"/", function (req,res) {
    var employee = req.body;
    var isValid =isValidEmployee(employee);
    } else{
Here is how it look in postman.


Update/Edit operation:

Here for an update operation, We are going to use PUT HTTP verb.  In this function, we are going to check that whether this employee exists or not. If exist we will update the properties of particular specific employee object and send code 204 which says operations completed successfully.  If the employee does not exist then it will return 404-Not found. Following is code for that.
router.put("/:Id",function (req,res) {  
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
        let employee = req.body;
        var isValid = isValidEmployee(employee);
            currentEmployee.FirstName = employee.FirstName;
            currentEmployee.LastName = employee.FirstName;
            currentEmployee.Designation = employee.Designation;
And when you run this in postman, It looks like following.


Delete operation:

In this operation, We are going to use DELETE HTTP verb. We are going to check that whether this employee id passed exist or not. If exists, we will delete that employee from our collection object and return 204 statuses. If not found then we are going to have 404 statuses. Following is code for the same.
//delete employee
router.delete("/:Id", function(req,res){
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
        employees = employees.filter(e=>e.Id!=employeeId);
Now when you run in postman. It will look like this.


That’s it. Hope you like it. In this next post, we are going to see how we handle validation in the better way with Node.js APIs.

Complete source code of this blog post is available on Github at following location-
Thursday, January 19, 2017

My favorite Visual Studio code extension for Angular 2 Development


I have been using Visual Studio Code for quite a good amount time and I am loving it as a code editor. Recently I have started using it as my development editor for Angular 2 as it has recommended by the Angular 2 development team also. There are quite a few good extensions available in market place for the same. In this blog post, we are going to talk about my favorite extensions of Visual Studio Code for Angular 2 development.

My favorite extensions for Visual Studio Code for Angular 2 development:

Here is list of my favorite extension of Angular 2 Development.

Angular 2 TypeScript Snippets by John Papa:
When It’s come to Angular 2 development how we can forget John Papa. There is also a snippets extension created by him. You can find that at the following location.

There are plenty of snippets available from where you can create boilerplate code for Angular 2 like for example, You can create Angular 2 Component with ng2-component.

Angular VS Code TypeScript and HTML Snippets by Dah Wahlin:
This is also a code snippets extensions but here you get lot many code snippets available. You can find more about that extension at the following link.

With this extension, you will get TypeScript extension as well as some of HTML snippets for binding of Angular 2  as well as some of the ngform and other snippets.

angular2-snippet for dahwahlin

Path Intellisense from Christian Kohler:
It is the plugin that autocompletes the path and provides Intellisense for the paths and it is a great extension and comes quite handy when you put different JavaScript and CSS files. You can find more about it at the following location.

Auto Import by Steoates:
It is an auto import extension for everything. It finds, parses and provide code actions and code completion for all available imports. It works great with TypeScript and even for TSX  which used for react.js with TypeScript. You can find more information about that extension at the following link.

It helps so much when you want to import services and other files into components with Angular2. This is my most favorite extension for Angular 2 Development.

HTML CSS Class Completion by Zingd:
It is a great extension for applying CSS class name for HTML class attribute based on your CSS files available in the project. You can find more about that on the following location.

That’s it. This all extensions are my favorite extension for Angular2.What are your favorite extensions that make your life easy? Please put your favorites in this blog post comments. Hope you like it. Stay tuned for more!!
Tuesday, January 17, 2017

How to use NancyFx with ASP.NET Core Application


In this blog post, we are going to learn how we can use Nancy framework with ASP.NET Core Application.

NancyFx Introduction:

NancyFx is a lightweight, low-ceremony framework for building HTTP based services on .NET and Mono. It is inspired by Sintara Framework for Ruby and hence Nancy was named after the daughter of Frank Sintara. Nancy Framework is a great alternative to ASP.NET APIs. It follows “Super duper happy path” phrase. It has following goals.
  • It just works – You should just use it without learning so much thing from it. Create a Nancy module and that’s it.
  • Easily Customizable – There are tons of customization available and then you can easily customize it.
  • Low-ceremony- With the minimal code you will able to run NancyFx.
  • No Configuration Required – There is no configuration required and very easy to setup.
  • Host-agnostic and Runs anywhere-  It will run on any server, self-hosted etc.
  • Low Friction- When you build software with NancyFx APIs it will help you where you want to go rather than coming in your way. 

How we can use NancyFx in ASP.NET Core:

So let’s see how we can use NancyFx in ASP.NET Core, Let’s create  ASP.NET Core API Application via File –> New project in visual studio.


Once you are done with creating an ASP.NET Core API application delete the controller folder and add following nuget packages.
    • Microsoft.AspNetCore.Owin: “1.0.0”
    • Nancy: “2.0.0-barneyrubble”
You can directly put  in project.json like following.


Now once we are done with adding packages, We need to make sure our application uses NancyFx and handles requests instead of ASP.NET MVC. So remove “app.UseMVC” in the startup.cs file and add following code in configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

    app.UseOwin(n => n.UseNancy());
Now we need to create a new Nancy module that will handle request. For this blog post, we are going to create a Home Nancy module like following.
using Nancy;

namespace NancyCoreAPI.Module
    public class HomeModule : NancyModule
        public HomeModule()
            Get("/", args => "Hello world from nancy module.");
Here in the above code, You can see that it is a standard Nancy module where you just need to write methods in the constructor and it will return text or HTML based on requirement. In our case here it will return “Hello World from nancy module” text. Once you run application browser it will look like following.


That’s it. You can see that Even with ASP.NET Core it is very easy to use and almost no configuration required at all.

You can find complete source code of this blog post at following location on GitHub-
Thursday, December 22, 2016

ASP.NET Core Application continuous integration with visual and git

Previously I have written couple posts for continuous integration series and this post is also part of it. Recently Microsoft has released ASP.NET Core 1.0. So in this post, we are going to see how we can do the continuous integration for ASP.NET Core application. I am going to use as our source control repository and git as our version controlling system. So Let’s get started.

The first thing we need to is to create a Project into like following.


Once you click on create the project it will create a project with GIT as version controlling system.


Now our project is ready. Once you click on navigate to project it will load project dashboard like below.


Now go-to “Build & Release” section of the project. It will load the page like below.


Now to enable continuous integration for this project we need to create a new build definition for that click on Plus green icon on left side. It will load a wizard to create a build definition. The first screen presented with default templates like below.


We are going to select ASP.NET Core build which there in preview mode and click next will load source control step like below.


Her we are using so we are not going to change anything but we are going select continuous integration check like below to enable continuous integration like below.


Click on create will create build definition like below.


Click on save button to save build definition. It will open up a dialog like below.


Click on ok will save build definition.  Now we are done with the configuration of continuous integration and now its time to add code to check whether this configuration is working or not. To add code click on the code menu on it will load the following screen.


Now to configure the repository in visual studio we need to click on the clone in visual studio. It will open Visual Studio IDE.


Clicking on clone will clone repository in local and then we need to create an core application for that repository.


Clicking on open will create an core web application. Once you are done with creating the application, we need to push our code to master branch so that we can see whether our continuous integration is working or not. To push the changes, Goto team explorer it will load screen like below.


Click on changes will show the changes that are made for git repository like below. Put commit message and click on commit all.


It will commit changes local like below.


Now click on sync. It will load Synchronization screen like below.


Now click on push button to the push committed changes to the remote git repository.


It will push changes to the master branch. Now to check continuous integration go to build definition section of A build should be queued up for the changes we have made like below.


After some time if your commit changes are fine it will complete the build.


So you can see that our continuous integration is working fine. It’s pretty easy to setup. Hope you like it. Stay tuned for more.
Tuesday, December 20, 2016

How to enable remote desktop on Azure Linux VM

In Windows Azure Linux VM there is no direct way to remote desktop Azure VM. So in this blog post, We are going to learn how we can enable the remote desktop on Azure Linux VM.  If you don’t know how to create a Linux VM then there is a ton of articles available that how you can create a Linux VM.  Following a Microsoft, Docs links for creating an Azure Linux VM.

After creating a new Linux VM, the first thing you need to have SSH Client to connect the Azure VM. I have windows machine and Putty is one of most well known SSH client for the windows. So If you don’t have SSH Client download Putty from the following link.

Once you create a VM you will get any public IP like following.


So copy that public IP and then open Putty and paste the public IP like following.


Now once you are done with it click on open button. It will ask for your username/password. The key thing to remember here when you create Linux VM you have selected username and password. If you have a public key then you need to supply that key to Putty.


Once we got connected, We need to enable the gnome desktop in our Ubuntu Server first we need to get the latest update of it and for that, we need the following command.

sudo apt-get update
Once the update is done.  Now It’s time to run install ubuntu-desktop command.

sudo apt-get install ubuntu-desktop
It will enable the Remote Desktop and Desktop UI to Ubuntu Server VM.

Note: Here I have created a Ubuntu server in Azure Linux VM. But you can use any flavour of  Linux available in Azure VM. There will be different command for each flavour you can find the complete list at following location-
Once you run the command it will take some time for running and installing desktop for the server.


Now its time to install remote desktop in the server for that you need to run the following command.

sudo apt-get install xrdp
Once done with that try to remote login with Windows Remote Client.


Note: Sometime you  now allow the remote connection that is because with Azure VM default port is not allowed for remote desktop. So for that goto the following page and do as said to allow remote tcp ip port-
And I am able to login to my Azure Linux VM.

Saturday, October 22, 2016

Some of the important shortcuts for Visual Studio Code

Visual studio code is a Great editor for the web development. I have started using it and I’m loving it more and more. For any editor shortcut keys are important you can do lots more without moving to mouse with a shortcut. In this blog post, we are going to learn about shortcuts for Visual Studio Code.

Ctrl + P:  Goto File, You can move to any file of open solution/folder in Visual Studio code.
Ctrl + Shift + O : Goto Symbol, You can move to any function, variable or symbol of the current file.
F12 : Goto Definition – You can move to the definition of symbol or function with this command
Ctrl + G : Goto line, You can move to particular line number
Alt + Left: Navigate  between files goes to the left side of files
Alt+ Right: Navigate between files goes to the right side of files
Alt + F12: Peek definition, You can see preview of code for a function
Ctrl + Shift + D: Debug folder or file.
Ctrl + Shift + F: Search in all files.
Ctrl + Shift + H: Replace in all the files
Ctrl + T: Go to symbol in all files
Ctrl + B : Toggle Slider Bar
Ctrl + 1: Focus Left Editor
Ctrl+ 2: Focus Right Editor
F2: Rename symbol and function
Ctrl + Shift + X : Goto Extension Window
Ctrl + J: Toggle Panels
Ctrl + ` : Open terminal in VSCode
Ctrl + Shift + U: Show output Window
Ctrl + Shift + M : Show problems, Where you can see all the problems related to code and warnings.

You can find all the shortcuts of Visual Studio code from the following link.

That’s it. Hope you like it. Stay tuned for more!!

Opening ASP.NET Core Visual studio solution in Visual Studio code

In this blog post, We are going to see how we can open an ASP.NET Core solution in visual studio code.  So what we are waiting for. First, we are going to create an ASP.NET Core web application like below.


Then select web application like below.


Now once you created Ok it will create an ASP.NET Core Web Application like below.


Now let’s run that application to make sure that its work fine.


Open ASP.NET Core Solution in Visual Studio Code:

For those who don’t know What is Visual Studio code is here is the definition from the Wikipedia.

Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring
It is a cross-platform open source editor for writing code from Microsoft. You can find more information about that from the following links.

Now we are going to see how we can open the same application with Visual Studio code. But before doing that we need to make sure that the computer have .NET Core installed on your machine and Also make sure that Visual Studio Code C# support is there in Visual Studio code. You can find more about that from the following link.

Since Visual Studio Code is not a full fledge IDE(Integrated Development Environment) like Visual Studio. We need to open the folder which contains the solution and source code. You can do that from Visual Studio Code.


Then select the src folder of your application like below.


Once you click on “Select Folder” it will open source code like below.


Now when you open any CSharp file on the right bottom you will see a text like installing OmniSharp.  OmniSharp is a set of tooling and editor integrations and Libraries that together creates great IntelliSense and  other tooling support for popular editors like Code, Sublime Text, Brackets, Atom,Emacs and Vim etc. You can find more information about that on the following link.

Once you click on that text you can also see the progress of installation of Omnisharp libraries in output windows like below.


Once it installed it will automatically select the project which you have in solution. If you have multiple projects then you can click on that and it will ask you to select the project for which you need all IntelliSense .


That’s it. Now you have most of the experience that you got in Full Visual Studio and full fledge IntelliSense to all the .NET Features.


Disclaimer: I have tested it on the windows machine and its works perfectly fine. For macOS and Linux I would expect the same. For further information, you can follow a GitHub Issue which is already created by the community. You can find that GitHub issue at the following link.

That’s it. It’s very easy to use light weight Visual Studio Code for same development experience like Full Fledge Visual Studio.
Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews