Sunday, December 3, 2017

Creating Rest API with Node.js,Express and MySQL Part-1

With Node.js and express creating a Rest API is a piece of cake. In this blog post, we are going to see how we can create a rest API with Node.js, Express, and MySQL as a database.

Creating Database with MySQL:

So let’s first with creating Database for our APIs. So todo that we need to create a new Schema from MySQL workbench like following.

database-creation-mysql

Here we are going to create a schema(database) called “employee”.  Then it’s time to create a Database Table and Let’s create a table like following.

create-table-mysql

and Here is the SQL Script for creating a table.

database-table-script-mysql

Here we have 4 column of the table EmployeeId(Primary Key), First Name, Last Name and Designation of employee details.

CREATE TABLE `employee` (
  `EmployeeId` int(11) NOT NULL,
  `FirstName` varchar(45) DEFAULT NULL,
  `LastName` varchar(45) DEFAULT NULL,
  `Designation` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`EmployeeId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I have entered some sample data like following.

table-sample-data

Express Node.js application to create Rest API:

Now we have our database ready for MySQL and It’s time to create a new Node.js Express application. We can start with creating Package.Json with NPM init and run that command in command line.

npm init
It will ask you several questions to create your node an application like below.

npm-init

Once your basic node.js application is ready It’s time to install express via the following command.

npm install express –save
It will install express like below.

express-installer

Now we have created a node.js and express application. I have also installed MySQL and BodParser package and here’s how the package.json looks like.

{
  "name": "nodejsmysql",
  "version": "1.0.0",
  "description": "A Rest API Example with Node.js and MySQL",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jalpesh",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mysql": "^2.15.0"
  }
}
As now we are done with creating and configuring our node.js application It’s time to write code. First I have written following code to create a route of our API which will be a map to our API URL.
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.por || 3000;
var router = express.Router();

app.use("/api/employee", router);
Here in the above code, you can see that I have created an express object as required and then I created a body-parse object which will be used for the posting/putting data into our API. Then I have created a port and get router of express and then created a route which will be our URL for API.
Now It’s time to write MySQL Connection code like below.
var mysql = require("mysql");

var con = mysql.createConnection({
    host: "youripformysql",
    user: "usrename",
    password: "password",
    database: "employee"
});
In the above code I have to get MySQL object via require and then I created a MySQL connection.  You need to pass the credentials there for your MySQL Credentials. Then I have written following code to get Employee table data with our get API.
router.get("/", function (req, res, next) {
    con.connect(function (err) {
        if (err) throw err;
        con.query("SELECT * FROM employee", function (err, result, fields) {
            if (err) throw err;
            res.send(JSON.stringify({
                "status": 200,
                "error": null,
                "response": result
            }));
        });
    });
});
Here in the above code, You can see that I have written Route.get method which will be used to get All Employees from the MySQL database and then I have written a Select Query to query data with “Employee” table. Then I have put result data as Json with the response object.
Now we have to start this application with app.use like the following code.
app.listen(port, function () {
    console.log("Express server running on port %d", port);
});
Now we can run the application with the following command.

node index.js
You can see same in above image.

node-run-express-application

Now in a client like postman you can see the output like below.

output-as-json
That’s it. In blog post series we will see that how we can add/update and delete it. Stay tuned for more!!.

You can find complete source code above blog post at following location on github- https://github.com/dotnetjalps/RestAPINodeMySQL
Share:
Saturday, November 25, 2017

Video: How to use IIS Express with Visual Studio Code

Visual Studio Code is a Great Editor by Microsoft being Developed Open Source on Github and It is gaining lots of popularity and lots of Developers are using for creating applications in various languages. Their lots of features that are there for Developers and Still lots of features is not been explored or lots of useful extensions are not being explored. So I am creating few videos for explaining it’s feature and this video is one of that features.

IIS Express is a built-in web server for C# applications with Visual Studio and lots of Developers are using this. This video explains how we can use IIS Express with Visual Studio code. Please have a look at it and let me know how it was.



The plugin used in this video can be found at following location.
https://marketplace.visualstudio.com/items?itemName=warren-buckley.iis-express

And If you don’t know what is Visual Studio code then you find more about it at following location.
https://code.visualstudio.com/

Stay tuned for more!!.
Share:
Sunday, July 9, 2017

Microsoft MVP for the 6th time! Thank you, Microsoft

First all, Sorry for the late post. I am very happy and proud to announce that I have been awarded Microsoft Most Valuable Professional for the 6th time in “Visual Studio and Development" Category.



On this occasion, I would to Thank Microsoft for again such a wonderful gesture. I would also like to thank my MVP Community lead Deepak Rajendran  & team for their constant support. I would like to thanks, Biplab Paul and Gadharv Rawat for doing same earlier. Without the support of these guys, it would not have been possible to achieve this.

Also, I would like to thank my family for their constant support for compromising their time to do the community work. Special thank to my wife Reena. Behind every men’s success, there is a woman and she is the woman responsible for my success. I would like to dedicate this award to my family this time especially my little champ who is the inspiration for me to staying strong in any condition.

Also, I would like to thank Ahmedabad User Group and Microsoft for providing awesome opportunity to speak at various events.

Last but not least, THANK YOU my dear blog readers without you. It was not possible.
Share:

Video: How to debug Node.js Application with Visual Studio Code

Visual Studio code is a Great Editor and I like it very much. It support’s a lot of cool features our of box. Node.js Application debugging is one of them. It provides great debugging with node.js just like Visual Studio. I have created a small video demonstrating the same. Please have a look.


Share:
Wednesday, June 21, 2017

Video: Visual Studio 2017 Features

Visual Studio 2017 got lots of new features and so that I’ve created a new video for demonstrating all the features of video. Please have a look at that video at below.



Let me know what kind of video you want to watch more!. Stay tuned for more!
Share:
Saturday, June 17, 2017

Code Navigation features in Visual Studio Code

Visual Studio Code is an open source, free, Cross-platform editor and I have been using it now more than the year. I just simply loved this editor. It’s a got lot of feature and there are some cool navigation features there. In this blog post, we are going to explore those navigation features.

Quick Open File Navigation Features(Ctrl+Tab):

If you press Ctrl + Tab then it will show all the open files in Visual Studio Code.

quick-file-navigation-feature

Go To Definition(F12):

If Language is supported in Visual Studio Code then you have that feature available just like have it in full Visual Studio IDE.  You can press F12 to go to definition and the same way you can also right click and select Go To Definition.

go-to-definition

Peek Definition(Alt + F12):

Peek Definition is working same as Go To Definition the only difference is it will load a windows inline and show. It is quite useful when you want to quickly see something. You can use this feature via pressing Alt+F12.

peek-definition

Open Symbol(Ctrl+T):

It also contains some Resharper like features you can go to any symbol via pressing Ctrl + T. Just type the first letter of a type you want to navigate to, regardless of which file.

open-symbol

Go To File(Ctrl + P):

You can also go to any file with Go To File feature of Visual Studio code via pressing Ctrl + P.   This quite useful when you have large code base.

go-to-file


There tons of other features available with Visual Studio code. So if you have not tried this editor I would highly recommend to try it. I’m sure you fall love in it. You can download Visual Studio code from the following location.

https://code.visualstudio.com/

Stay tuned for more!.
Share:
Saturday, May 13, 2017

My blog awarded top 60 Dot Net Blogs on Web from FeedSpot

It’s been a great year for me overall. It was a roller coaster ride for me. Recently I got an email from Anuj Founder of FeedSpot that My blog has been awarded as Top 60 DotNet Blog from FeedSpot.

Top60DotNetBlog

You can find complete list of Top 60 blog at following link.

http://blog.feedspot.com/dotnet_blogs/

My blog at 22 positions there.It’s great pleasure being part of Top 60 Dot Net Blog in Web. On this occasion I would like to thank my Family without there support it was not possible to bee there. Specially my wife Reena who sacrifies her time when I’m writing blog posts. Also I, would like to thank my entire audience and readers without them it was not possible to achieve such a great milestone.

Thank you very much everyone!!. Please keep reading my blog. Stay tuned!
Share:
Thursday, April 27, 2017

Global Azure Bootcamp 2017 by Ahmedabad User Group, Ahmedabad–A great event

The last Sunday on 22nd April 2017, We had great event 5th Annual Global Azure Bootcamp.

What is Global Azure Bootcamp:

If you have not heard about Global Azure Boot. It is the great event for learning and understanding Microsoft Cloud Platform Azure. There were more than 250 locations in the world where this event took place. Each user group or community has organized their own one day deep dive seminars on Azure to see how it can be useful to develop great applications.





You can find more about Particular event on the following location-
https://global.azurebootcamp.net/

About Global Azure Bootcamp 2017 Organized By Ahmedabad User Group:

First of all, I would like to thank our local sponsor Aptus who provided us the Venue for organizing the event. Thank you so much!

The Day was started by Keynote presentation from Mahesh Dhola by introducing what is Global Azure Bootcamp and how any developer can get benefited from this. He explained how great azure is and what is Agenda for this event.

IMG_20170422_102745

Then It’s my time to be on stage. I have taken session about Introduction to BOT Framework. It is the latest offering from Microsoft. I have explained all the bits of BOTS evolution and How easily we can create a great BOT in minutes. Even I have shown How we can make our BOT intelligent via adding LUIS which is a language understanding service from Microsoft.


IMG-20170424-WA0001
IMG-20170424-WA0002

Following is my presentation about events.


I had a great time presenting this topic and Audience was quite interested in this topic. We had some great question and answers.
IMG_20170422_105335
 IMG_20170422_105329

You can find source code that particular session at https://github.com/dotnetjalps/GAB2017
After that, There was a Session from Nirav Madariya. He has taken a session about Logic Apps and Azure Functions. Here he has explained how we can easily create logic apps. Then he has explained Azure functions. He explained how we can create a server-less architecture with Azure Functions.

IMG_20170422_120011_HDR
IMG_20170422_114220_HDR

After that, there was a session from Kalpesh Satasiya. He has taken session about Microsoft Cognitive Services. Where he explained various services provided by Microsoft Cognitive services i.e. Vision, Language, Knowledge, Speech, and Search.

IMG_20170422_123938_HDR
IMG_20170422_123957_HDR

And here you can find his presentation



After that there was a time for Lunch and we had great opportunity to have networked with each other.

IMG-20170424-WA0005
IMG-20170424-WA0008
IMG-20170424-WA0003
IMG_20170422_131614

We had great fun doing networking with each other. Also enjoyed lunch. Thank you, Microsoft for sponsoring it.

After that, there was a session from well known Microsoft Regional Director and MVP Prabjhot Baxi. He explained about Azure IOT suite. How we can add devices into Azure IOT hub. He also explained Azure IOT hub and stream analytics and how to store data in Azure Document DB.

IMG_20170422_133720_HDR

Then we had a great session from Kaushal Bhavsar about Log Analytics. It is not a popular feature of Azure But after attending his session I found it is quite useful. He explained about how we can enable various kind of logs with Logs analytics. Even he showcased a demo with adding agent in Linux server and seeing what logs are there.

IMG_20170422_143433
IMG_20170422_143430

After that Ahmedabad User Group president Mahesh Dhola. He had taken session about Open Source Technology at Microsoft, Azure Virtual Machines. He also showed a demo how we can host elastic search on Azure Linux Virtual machine.

IMG_20170422_153021
IMG_20170422_153030

Overall, It was a great event and Audience was also good.

IMG_20170422_114202
IMG_20170422_120021_HDR

It was one of the successful events we have. Thank your all the sponsors and Audience.
If you want to be part of such event or want to be a speaker at the event please contact me or AhemdabadUserGroup twitter handle.

https://twitter.com/AhmedabadUsrGrp

We are soon going to organize the Visual Studio community launch stay tuned for the same. #GlobalAzure
Share:
Sunday, April 2, 2017

Explicit loading in Entity Framework Core

In this blog post, We are going to learn about Entity Framework feature. Explicit loading means that related data is explicitly loaded from the database at a later time. As you might know, that lazy loading is still not possible with Entity Framework core but there is a way to explicit load related data in a transparent manner.  We are going explore how we can load data explicitly with entity framework in this blog post in detail.

How to do Explicit loading in Entity Framework Core?

To demonstrate how we can use explicit loading in Entity Framework core. We are going to create a console application with two entities Student and Department. A department can have multiple students. Here we are going to see how we can load students for each department explicitly.

So let’s create a console application like following.

new-console-app-entity-framework-core-explicit-loading

Now once you click “Ok” it will create a console application. Now let’s add nuget package for entity framework core in console application like following. You need to run following command in Package Manager Console.

Install-Package Microsoft.EntityFrameworkCore.SqlServer
entity-framework-core-nuget-package

Now it’s time to create our models for Student and Department like below.

Department:
using System.Collections.Generic;

namespace EFCoreExplicitLoading
{
    public class Department
    {
        public int DepartmentId { get; set; }
        public string Name { get; set; }
        public ICollection<Student> Students { get; set; }
    }
}
Student:
namespace EFCoreExplicitLoading
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int DepartMentId { get; set; }
        public Department Department { get; set; }
    }
}
Now let’s create an Entity Framework Core context like below.
using Microsoft.EntityFrameworkCore;

namespace EFCoreExplicitLoading
{
    public class StudentContext: DbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Department> Departments { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Data Source=SQLServerName;Initial Catalog=YourDatabase;User ID=UserName;Password=Password;MultipleActiveResultSets=true");
        }
    }
}
Here in the above code, you see that A department can have multiple students and A student can have only one department so there is one to many relationships between department and student.

Now let’s create a migration to create the database for the same. To enable migration we need to install following nuget package for entity framework core tools.
Install-Package Microsoft.EntityFrameworkCore.Tools
entity-framework-core-migration-console-application

Now let’s create a migration with the following command.
Add-Migration InitialDatabase
entity-framework-core-migration-initial-database

Now let’s create a database with “Update-database” in Package manager console. It will create a database.

Now we need some initial data to demonstrate the explicit loading feature so I’ve added following data into Departments table.

department-data-entityframework-core

Same way I have added data into Students table like following.

student-data-entity-framework-core

Now it’s time to write some code that demonstrates the explicit loading feature of entity framework core. Following is a code for the same.
using System;
using System.Linq;

namespace EFCoreExplicitLoading
{
    class Program
    {

        static void Main(string[] args)
        {
            using(StudentContext studentConext= new StudentContext())
            {
                var deaprtments = studentConext.Departments.ToList();
                foreach(var department in deaprtments)
                {
                    Console.WriteLine("Before explicit loading");
                    Console.WriteLine(department.Students==null);

                    //loading student explicitly
                    studentConext.Entry(department).Collection(s => s.Students).Load();

                    Console.WriteLine("After explicit loading");
                    Console.WriteLine(department.Students == null);
                    Console.WriteLine(department.Students.Count);
                    Console.WriteLine("------------------------------------------------");

                }
                Console.ReadLine();
            }
        }
    }
}
Here in the above code, you can see I have created student context object and then I have got all the databases. After that, I have checked that whether each department is having students or not. In the next statement, I have loaded the students explicitly with the student with collection load method and then again I checking whether it got students and also printing count of a student.

Now let’s run this application and here is the output as expected.

out-put-entity-framework-core-explicit-loading

So it is loading student data after the department is loaded with the help of explicitly. That’s it. Hope you like it. There are so many scenarios where this explicit loading can be quite useful. Stay tuned for the more!!.

The complete source code of this sample application is available on github at - https://github.com/dotnetjalps/EFCodeExplicitLoading
Share:

How to integrate HangFire with ASP.NET Core 1.1

Hangfire is one of the easiest ways to perform background processing in.NET and.NET Core Applications. In this application we are going to learn how we are can integrate Hangfire with ASP.NET Core application.

About Hangfire:

Hangfire allows you to create background task in.NET applications. It’s extremely easy to integrate. It allows you to kick off method calls outside of the request processing pipeline in very easy but reliable way. You can store those jobs in on premise SQL Server, SQL Azure, Redis, MSMQ or Redis.

You can find more information Hangfire on the following link.
http://hangfire.io/

Hangfire also contains one of very maintained documentation at the following link.
http://docs.hangfire.io/en/latest/

Integrating HangFire with ASP.NET Core 1.1:

To demonstrate how we can integrate with ASP.NET core, I’m going to create a new ASP.NET Core application in Visual Studio 2017 like below.

new-aspnet-core-application-hangfire

Once click on it will ask for the selection of Application task we are going to select Web Application like below.

aspnet-core-hang-fire-web-application

As our application is not ready, We are going to install Hangfire nuget package in the application.

install-hangfire-nuget-package

Now we are done with adding Hangfire to our asp.net core application. We need to create a SQL Server database for Hangfire application. Here I’m going to use SQL Server for Job storage but there are various Job Storage options available as mentioned above.

hangfire-sample-database

Now we need to have ConnectionString for the database. Let’s put it on appsetting.json like below.
{
  "ConnectionStrings": {
    "HangFireConnectionString": "Data Source=SQLServer;Initial Catalog=HangFireSample;User ID=YourUserName;Password=YourPassword;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Now in Startup.cs file configure services method we need to integrate hangfire like below. Here I’ve added hangfire to our application and also indicated that we are going to use SQL Server for Job storage and provided connection string for the same.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddHangfire(config=>config.UseSqlServerStorage(Configuration.GetConnectionString("HangFireConnectionString")));
}
Now Hangfire integration is easy to use. When you run it will automatically create tables related to Hangfire configuration and storage as below.


hangfire-tables-sql-server

Now you can easily add background task like below at any place.
  BackgroundJob.Enqueue(() => Console.WriteLine("BackGroundJob"));
Even you can add recurring job which will run at a specific time like below.
 RecurringJob.AddOrUpdate(() => Console.WriteLine("RecurringJob"), Cron.Daily);
That’s it. You can see it’s very easy to use and You can integrate Hangfire very easily. Hope you like it. Stay tuned for more!.
You can find complete source code of this application at following on github.com : https://github.com/dotnetjalps/ASPNetCoreHangFire
Share:
Wednesday, March 29, 2017

New Features–Out Variables in C# 7.0

Prior to C# 7.0,  For out keyword, we need to define that variable earlier and then we were able to pass that variable as out reference arguments. But now with C# 7.0, You don’t need to declare the variable but you can use the variable which you have used in arguments.

Following is a code showing both ways passing out variables.

In the above code, You can see that I have created get employee static method which put some values in this out variables. First I have shown the old way of doing this. Where I explicitly defined the variables and then passed it to function while in the new way of doing you don’t need to explicitly define variable. You can write this as an argument and then, later on, you can use the same variable in next statements.  Now when you run the application, the new and old way both produce the same output.


csharp7-out-varibles-example

You can find complete source code of this examples at following location on Github at- https://github.com/dotnetjalps/CSharp7NewFeatures
Share:

Visual Studio 2017 New Features Series

Visual Studio 2017 is recently launched by Microsoft and it is one of great IDE I have ever seen. It contains lots of features and this blog post contains the link to all features post that I have written for Visual Studio 2017.

A new start page for Visual Studio 2017
Code Navigation features in Visual Studio 2017 



Share:

Code Navigation features in Visual Studio 2017

This blog post is a part of Visual Studio 2017 New feature Series

TL;DR:

With Visual Studio 2017 there are lots of new Code Navigation features introduced. We are going to look all the options available in Visual Studio 2017.

Navigation your code with Visual studio 2017:

Visual Studio 2017 have newly refreshed code navigation features which help you moving from point A to B easily and fewer distractions. There are mainly four new features available.

Go to Implementation(Ctrl+F12):

It helps you navigate from any base type to implementation of the concrete type.

GotoImplementation

Go To Line(Ctrl+G):

It helps moves cursor from current line to specified line number.

go-to-line-visual-studio-2017

Go To All(Ctrl+T):

It helps you navigate directly to any file/type/symbol/member. You can move from any files to anywhere with this feature easily.

go-to-all-visual-studio-2017

Go To File(Ctrl+ 1, Ctrl + F):

You can easily navigate between files with this feature.

go-to-file-visual-studio-2017

Go To Type(Ctrl+1, Ctrl + F):

You can move to any type with this feature. It searches classes/interfaces/enums and delegates and moves your current cursor selected type.

go-to-type-visual-studio-2017

Go To Member(Ctrl+ 1, Ctrl + M):

You can move between members for a particular class. It searches Global Variables and Global Functions, Class Member variables and member functions, Constants, Enum items, Properties, and events.

go-to-member-visual-studio-2017

Go to Symbol(Ctrl + 1, Ctrl + S):

You can move to any symbols, search result includes Go to Type and Go to Member.

go-to-symbol-visual-studio-2017

Find All References(Shift + F12):

In the earlier version of Visual Studio Find All References was the plain list without any syntax highlighting and coloring. Now with Visual Studio 2017 it has got coloring and splits all the information into their respective columns. This column can be also customized so you will only see what you want to see in Find All References Window.

find-all-references-visual-studio-2017

So Visual Studio 2017 now got lots of features and that will make code navigation very easy. It will definitely increase developer productivity and made life easy.
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