Saturday, January 28, 2017

How to upgrade your ASP.NET Core application from 1.0 to 1.1

TL;DR;

In this blog, We are going to learn how we can upgrade your ASP.NET Core application from 1.0 to 1.1.  Now Microsoft has release 1.1 before few months, So in this blog, we will see how you can upgrade your ASP.NET 1.0 application to ASP.NET 1.1 core application.

Where to download 1.1 SDK and Tooling for Visual Studio 2015:

You can download 1.1 SDK and Tools from the following link.

https://www.microsoft.com/net/download/core?tduid=(42c8fb30096a508e70a0e7f0d6bdaf55)(256380)(2459594)(TnL5HPStwNw-1.6L2HANlqPr5.uZiHJ1MQ)()#/current

where-to-download-tooling-and-sdk-for-core1.1

Here different tooling is also available for the Visual Studio 2015 and Visual Studio 2017. For this blog post, We are going to use Visual Studio 2015.

How to upgrade to ASP.NET core 1.0 to ASP.NET core 1.1:

So let’s get started. I’m going to create a new ASP.NET Core 1.1 application and then we will move it to ASP.NET 1.1. So let’s create an ASP.NET core 1.0 application and then let’s upgrade it to 1.1. I have created a new application like following.

creating-new-aspnet-core-app-to-upgrade-to-11

Once you click ok it will have a dialog selecting application type and I’m going to select web application.

web-application-aspnet-core-11

Once you click Ok, It will create an application like below and you can see that it’s an ASP.NET Core 1.0 application.

aspnet-core-1.0-app-in-solution-explorer

And here’s how it’s project.json looks like.
{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

And here’s how the global.JSON looks like.
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}
So the first thing we need to is to upgrade the global.json to latest version like below.
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-1-003177"
  }
}


So here in project.json, you can see that all packages belong to 1.0. Now there is multiple ways we can do upgrade either we can manually upgrade all packages via manually upgrading it or we can do it with Visual Studio tooling. I’m going to use Visual Studio tooling as that is the easiest way to do it. You can do this via Right Click your application and Select “Manage Nuget Packages for this solution”. It will load the following dialog. You need to goto Update tab of that dialog.

upgrade-nuget-package-to-1.1

You need to select upgrade all packages and update your application. Once you did with that there is once place where you need to manually upgrade it in project.json. GoTo following part of project.json.
"frameworks": {
  "netcoreapp1.0": {
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }
},
Now upgrade netcoreapp1.0 to 1.1 like below.
"frameworks": {
  "netcoreapp1.1": {
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }
},
Now once you do that and build your application. You might get the error like following.

error-for-runtime-application-net-core

That is because of windows runtime is not there for 1.1. So you need to add following in project.json.
"runtimes": {
  "win10-x64": {}
},
Now once you add that in project.json. It will restore the runtime for your operating system and it will start building your application.
And here’s how my project.json looks like after upgrading all stuff.
{
  "dependencies": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "BundlerMinifier.Core": "2.2.306",
    "Microsoft.Extensions.Logging": "1.1.0",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Microsoft.Extensions.Logging.Debug": "1.1.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
    "Microsoft.NETCore.App": "1.1.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0",
    "Microsoft.AspNetCore.Diagnostics": "1.1.0",
    "Microsoft.AspNetCore.Mvc": "1.1.1",
    "Microsoft.AspNetCore.Routing": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.1": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },


  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "runtimes": {
    "win10-x64": {}
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

And in solution explorer, you can see that now it’s targeting to 1.1.

targeting-11-upgrade-to-11-solutionexplorer

That’s it. It’s pretty easy to upgrade your application to latest build. Hope you like it. Stay tuned for more!!
Share:
Wednesday, January 25, 2017

How to upload file with Express,Pug and Multer in Node.js

TL;DR;

In this blog post, We are going to learn how to upload a file with Express, Pug, and Multer in Node.js. In this blog post, we will learn how we can upload file with multer middleware in express framework with node.js

Creating Express App, Multer and other common code:

So here in for the demo purpose, we are going to use express application. So here is our package.json for express framework node.js application. It is created via the express generator. I have added Multer and PUG NPM instead of Jade.
{
  "name": "nodejsfileupload",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.15.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.2.0",
    "express": "~4.14.0",
    "morgan": "~1.7.0",
    "multer": "^1.2.1",
    "pug": "2.0.0-beta6",
    "serve-favicon": "~2.3.0"
  }
}

Here in the above code, You can see that there are pug npm and multer npm. Once you do “NPM Install” it will install all the required NPM for the same. Now we are our standard express app ready and here’s how our structure looks in visual studio code.

node-js-structure-express-app-file-upload-node-js

What is Multer:

For those who don’t know what is Multer,

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
It is a middleware that will help you handle multipart/form-data requests and you can upload the file with that middleware with some configuration code.You can find more information about Multer at - https://github.com/expressjs/multer

Common code for Multer:

Now once we are done with Installing node module, It’s time to write some common code for Multer middleware. Here in the above code, we are going to use the index.js router which is a default router for the express app.  The index.js code looks like following.
var express = require('express');
var router = express.Router();

//multer object creation
var multer  = require('multer')
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
  }
})

var upload = multer({ storage: storage })

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/', upload.single('imageupload'),function(req, res) {
  res.send("File upload sucessfully.");
});

module.exports = router;

Here in the above code, you can see that first I’m creating a multer object with require syntax and then I have put some configuration with multer.diskstorage. Basically, It's said that we are going to store the uploaded files into public/uploads folder and the name of a file will be same which we uploaded. Then in post request, you can see that I have put “upload.single” which handle file upload with post request. And if it uploaded successfully, I’m sending a response back that file is upload successfully.

HTML/PUG code:

Following is an HTML code for the pug.
extends layout

block content
  h1= title
  p Welcome to #{title}
  form(method='post', enctype='multipart/form-data')
    input(type='file', name='imageupload')
    input(type='submit', name='uploadimage', value='Upload Image')

Here you can see I have a file upload control with multi-part data and form and submit button to make a post request.

Final Output:

Once you run this application in the browser it will look like following.

file-upload-node-js

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

You can find complete source code following example on Github at - https://github.com/dotnetjalps/NodeJsFileUpload
Share:
Sunday, January 22, 2017

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

TL;DR;

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.

open-folder-with-visual-studio-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.

npm-install-visual-studio-code-console

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 }));
app.use(bodyParser.json());

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

app.use('/api/employee', router);
app.listen(port);
Here you can see this code is pretty standard 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){
    if(!employee.Id){
        return false;
    }
    if(!employee.FirstName){
        return false;
    }
    if(!employee.LastName){
        return false;
    }
    if(!employee.Designation){
        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){
    res.json(employees);
});
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.

getall-with-nodejs-rest-api

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
router.get("/:Id",function(req,res){
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];

    if(currentEmployee){
        res.json(currentEmployee);
    }else{
        res.sendStatus(404);
    }
});
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.

specific-get-node-js-employee

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
router.post("/", function (req,res) {
    var employee = req.body;
    var isValid =isValidEmployee(employee);
    if(isValid){
        employees.push(employee);
        res.send(employee);
    } else{
        res.sendStatus(500);
    }
});
Here is how it look in postman.

add-employee-nodejs-api

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];
    if(currentEmployee){
        let employee = req.body;
        var isValid = isValidEmployee(employee);
        if(isValid){
            currentEmployee.FirstName = employee.FirstName;
            currentEmployee.LastName = employee.FirstName;
            currentEmployee.Designation = employee.Designation;
            res.sendStatus(204);
        }else{
            res.sendStatus(500);
        }
    }else{
        res.sendStatus(404);
    }
});
And when you run this in postman, It looks like following.

update-employee-nodejs-api

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];
    if(currentEmployee){
        employees = employees.filter(e=>e.Id!=employeeId);
        res.sendStatus(204);
    }else{
        res.sendStatus(404);
    }
});
Now when you run in postman. It will look like this.

delete-employee-nodejs-api

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- https://github.com/dotnetjalps/NodeJsRestAPI

You can run this API with the following command.

node api.js 
Share:
Thursday, January 19, 2017

My favorite Visual Studio code extension for Angular 2 Development

TL;DR;

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.

https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2



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.

https://marketplace.visualstudio.com/items?itemName=danwahlin.angular2-snippets

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.

https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense



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.

https://marketplace.visualstudio.com/items?itemName=steoates.autoimport



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.

https://marketplace.visualstudio.com/items?itemName=Zignd.html-css-class-completion



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!!
Share:
Tuesday, January 17, 2017

How to use NancyFx with ASP.NET Core Application

TL;DR;

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.

create-project-nancy-api

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.

project-json-nancyfx

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)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    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.

hello-world-from-nancy-module

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- https://github.com/dotnetjalps/CoreNancyAPI
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews