Saturday, June 18, 2016

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations:

Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.

creating-project-core-migration

Once we select asp.net core application it will appear the following dialog.

web-application-aspnet-core

Now when you create a sample application. It will basically create a boilerplate code for the asp.net identity and as a part of that it is going to create entity framework migration files under Data –> Migrations folder.

default-migration-entity-framework-core

Here you can find that sample code in GitHub repository given at the bottom.  Now we already asp.net identity migration code ready. So Let’s have those migrations applied with the following command from NuGet package manager console.

update-database
core-migration-aspnet-identity

Now let’s add a new model “Employee” like following.
namespace CoreMigration.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
As we have employee class, We need to add migration for that. I’m going to create a migration for employee class via the following command.

add-migration AddEmployee
add-employee-migration

It will create “AddEmployee” migration class in Data->Migrations folder.

employee-migration-in-solution-explorer

And here is the code for the migration for the same.
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;

namespace CoreMigration.Data.Migrations
{
    public partial class AddEmployee : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    EmployeeId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    FirstName = table.Column<string>(nullable: true),
                    LastName = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Employees", x => x.EmployeeId);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");
        }
    }
}

Now we have our migration class ready so I am going to run the update-database command as following.

update-database-employee-migration-entity-framework-core

Now let’s check the database again and You can see employee table is there.

database-after-employee-migration

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

You can find complete source code of this application at following location on Github - https://github.com/dotnetjalps/EntityFrameworkCoreMigration
Share:
Tuesday, June 14, 2016

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.

creating-aspnet-core-project

Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.

creating-aspnet-core-api-project

Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace CoreWebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Here you can see that there is a WebHostBuilder class which hosts the application and there is some configuration for using this application on IIS and Kestrel which is  a cross-platform server from Microsoft.

Now let’s create our model class first. I have created an Employee model class like following.
namespace CoreWebApi.Model
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Designation { get; set; }
    }
}
Since now our model is ready, It’s time to create the controller. You can create web API controller via add new item like following.

creating-aspnet-core-api-controller-class

And here the code for our get Method.
using System.Collections.Generic;
using CoreWebApi.Model;
using Microsoft.AspNetCore.Mvc;

namespace CoreWebApi.Controllers
{
    [Route("api/[controller]")]
    public class EmployeeController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<Employee> Get()
        {
           var employees = new List<Employee>
           {
               new Employee {EmployeeId = 1,FirstName = "Jalpesh",LastName = "Vadgama",Designation = "Technical Architect"},
               new Employee {EmployeeId = 2,FirstName = "Vishal",LastName = "Vadgama",Designation = "Technical Lead"}
           };
            return employees;
        }
    }
}

Here you can see that I have created a get method that returns a List of Employee. Now Let’s run this in our browser and it will work like following.

aspnet-core-api-browser-sample
You can find complete source code of this blog post at following location on Github-https://github.com/dotnetjalps/ASPNetCoreWebAPI
That’s it. Hope you like it. Stay tuned for more!
Share:
Monday, June 13, 2016

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command

How to solve : gulp is not recognized as internal or external command

To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.

environment-variable-node-modules

Go to Advance System Settings and it will open system properties windows like below.

system-properties-environment-variable

Click on Environment Variables it will open an environment and system variables windows like below.

environement-variables-node-modules-gulp

Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.

new-variable-for-gulp-not-found

Click on Ok. That’s it. Now run again the command for gulp and it will work. It’s very easy. Stay tuned for more!!.
Share:
Sunday, April 24, 2016

Cascading dropdown with ASP.NET Web Forms and Entity framework

This post may be pretty basic for many people. But I have been getting this request over and over so I thought it will be a good idea to write a blog post about it.

In this blog post, We are going to learn how we can create the cascading dropdown with ASP.NET Web forms and Entity framework. To create an application first we need to create web application like following.

new-project-visual-studio

After creating a web application like following. It’s time to create model classes for our application. Here to illustrate the example, We are going to use Standard and Student models. Multiple students can be there in a standard. So we are going to have two dropdowns Standard and Student. Once you change select standard based on that student dropdown will be filled.

Here is code for Standard Student Model class:
using System.Collections.Generic;

namespace CascadingDropdownEF.Models
{
    public class Standard
    {
        public int StandardId { get; set; }
        public string Name { get; set; }

        public virtual  ICollection<Student> Students { get; set; }
    }
}
And following is the code for the Student model.
using System.ComponentModel.DataAnnotations.Schema;

namespace CascadingDropdownEF.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int StandardId { get; set; }
        [ForeignKey("StandardId")]
        public Standard Standard { get; set; }
    }
}
Now once we have our model ready it’s time to create our Entity framework context class. We are going to use Entity code first model here . So here is the code for the Entity framework context.
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace CascadingDropdownEF.Models
{
    public class StudentContext : DbContext
    {
        public StudentContext() : base("name=StudentConnectionString")
        {
            
        }
        public DbSet<Standard> Standards { get; set; }
        public DbSet<Student> Students { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
Here I have created two DbSet for students and standards. Also in model creating event I have removed plural names so when entity framework create tables when we run this application it will remove plural names from the table.

Creating Web Forms and using Entity framework for cascading dropdowns:


Now we have our database layer or operation ready. it’s time to create a new Web Form which will have Standard and Student drop-down.

adding-cascading-dropdown-page

After creating Web Form I have written following HTML code in aspx file.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDrodownDemo.aspx.cs" Inherits="CascadingDropdownEF.CascadingDrodownDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Cascading dropwon demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList runat="server" ID="ddlStandard" CssClass="dropdown" AutoPostBack="true" OnSelectedIndexChanged="ddlStandard_OnSelectedIndexChanged"/>
        </div>
        <br/>
        <div>
            <asp:DropDownList runat="server" ID="ddlStudent" CssClass="dropdown"/>
        </div>
    </form>
</body>
</html>

You can see that I have created two ASP.NET dropdowns Standard and Student and Also for Standard dropdown I have autopostback=”true” and selected index change event.
On the aspx.cs file i have written the following code.
using System;
using System.Linq;
using CascadingDropdownEF.Models;

namespace CascadingDropdownEF
{
    public partial class CascadingDrodownDemo : System.Web.UI.Page
    {
        private readonly StudentContext _studentContext;

        public CascadingDrodownDemo()
        {
            _studentContext = new StudentContext();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindStandards();
                BindStudents();
            }
           
        }

        private void BindStudents(int? standardId=null)
        {
            ddlStudent.Items.Clear();
            if (standardId != null)
            {
                var students = from student in _studentContext.Students
                    where student.StandardId == standardId.Value
                    select new
                    {
                        StudentId = student.StudentId,
                        Name = student.FirstName + " " + student.LastName
                    };

                ddlStudent.DataSource = students.ToList();
                ddlStudent.DataTextField = "Name";
                ddlStudent.DataValueField = "StudentId";
                ddlStudent.DataBind();
            }

            ddlStudent.Items.Insert(0,"--Select Student--");
        }

        private void BindStandards()
        {
            ddlStudent.Items.Clear();
            var standards = _studentContext.Standards.ToList();
            ddlStandard.DataSource = standards;
            ddlStandard.DataTextField = "Name";
            ddlStandard.DataValueField = "StandardId";
            ddlStandard.DataBind();

            ddlStandard.Items.Insert(0,"--Select Standard--");
        }

        protected void ddlStandard_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            BindStudents(Convert.ToInt32(ddlStandard.SelectedValue));
        }
    }
}
Here You can see that I have created two method BindStudent and BindStarnds. In Bindstandards it fetches all the standards and bind it to Standard dropdown . In BindStudents method, I have used a nullable parameter standardId which will be null by default. So If standard id is not provided as you can see it will only insert default item.  Now in page load method, I have called this two methods. Also, you can see that I have written Standard event dropdown selected index change event which will pass standard value.

Now everything is ready. I have inserted following data in Standard and Student table.

Standard-Cascading-dropdown-data-entity-framework

And student table like following.

student-cascading-dropdown-entity-framework

Now when you run the application. It will look like following.

sample-application

That’s it. Hope you like it. Stay tuned for more.
You can find complete source code of this application at following location on github- https://github.com/dotnetjalps/CascadingDropdownEF
Share:
Friday, April 22, 2016

DocumentDB data in Visual Studio with cloud explorer

Recently, During Global Azure Boot camp presentation , One offline question was asked that how we can see and browse the data from DocumentDB. So I thought there will be lots of developers who might have the same question that where I can see data from DocumentDB in visual studio.

Yes you can see your DocumentDB data into visual studio. There is an extension called Cloud explorer from where you can browse all the services of Azure. With Visual Studio community edition its comes inbuilt But If you have not that installed then you can install via following steps.

How to install Cloud explorer in Visual Studio:

Open visual studio and go to Extensions and updates like below.

ToolsAndExtensionsinVisualStudio

Once you click on that it open a window loading all the extensions select online and type cloud in the search box and you will able to see cloud explorer like below.

cloud-explorer-preview

I have Cloud explorer installed in my Visual studio that’s its showing Green tick otherwise it will show download button there and you can download and install it.

You can also download manually from the following link.

For Visual Studio 2015:
https://visualstudiogallery.msdn.microsoft.com/84e83a7c-9606-4f9f-83dd-0f6182f13add

For Visual Studio 2013:
https://visualstudiogallery.msdn.microsoft.com/d3896fc2-109b-4420-9c38-b6ab1cfa9fe5

How to use Cloud explorer to see data of DocumentDB:

One you are done with installing Cloud explorer, You can load that from View Menu-> Cloud explorer in Visual Studio. It will load like below.

cloud-explorer-visual-studio-2015

Here I have already given my Azure Credentials If you have not given that it will ask for credentials and then will load this screen.

Here it will show the list of all services available for storage. To see what is there in our DocumentDB account click on DocumentDB Account.  It will show your account name lie below.

documnetdb-database-azure-cloud-explorer

One you click on the database name it will show all the collection and record below.

database-documentdb-cloud-explorer

One you select records(JSON documents) and right click. It asks for you to open in the editor like below.

record-in-cloud-explorer

Once you click on open editor, It will ask open that JSON document like below.

json-documnet-cloud-explorer-documentdb

So you can see that it's very easy to browse data of DocumentDB in cloud explorer in Visual Studio itself. Hope you like it. Stay tuned for more!.
Share:
Wednesday, April 20, 2016

Visual Studio code 1.0 Released

Microsoft has released visual studio code on 1.0 version 14th April 2016. Those who have not used Visual Studio code, Visual studio code a is cross platform open source editor from Microsoft. It supports the variety of languages and you can do almost everything that you can do in an IDE. It also provides support for the debugging few languages.

In blog of Visual Studio Code, Microsoft says
Since our initial launch one year ago, 2 million developers have installed VS Code,” the Visual Studio Code team revealed. “Today, we’re excited to report that more than 500,000 developers actively use VS Code each month.
2016_04_14_header
Image source: Visual Studio code blog.

There is some important milestone that Visual studio code is received like following.
  • Visual studio code is now fully localizable and supports 9 languages
  • Visual studio supports extensions and community has built more than 1000 extensions in such a sort span
  • It now supports syntax highlighting and few more features for more than 100 languages.
  • It got more than 300+ pull request on Github.
It will be interesting to see how Visual Studio Code move ahead. I have used it for many times and I am quite happy with it.

You can find more information about it at the following link.

https://code.visualstudio.com/blogs
https://www.thurrott.com/dev/66355/microsoft-delivers-visual-studio-code-1-0

If you have not used it then I recommend you to download this and try it from the following location.
https://code.visualstudio.com/Download

That’s it. Hope you like it. Stay tuned for more!
Share:
Sunday, April 17, 2016

Global Azure Bootcamp 2016 Ahmedabad–Awesome event recap

Yesterday, Ahmedabad User group has organized the Global Azure Bootcamp 2016 event. It was a fun to be there. The event was very well received and attended by the group of people excited about Azure cloud platform.  Thanks for hosting is Ahmedabad User Group.

AUGLogo3

Event Recap:

In the morning, Event is started around 10:00 am. Mahesh had made all attendees comfortable and given some insights about Azure platform.

DSCN5888

After that, It was my time to present some. I have shared my knowledge about DocumentDB with my presentation about Introduction to DocumentDB.

DSCN5893
DSCN5891

There well lots of interest in the audience and we had lots of conversation about it. Here is the presentation link for the same.

Here was the agenda for my presentation.

  • What is document databases?
  • What is DocumentDB?
  • Why we should use DocumentDB?
  • How we can use DocumentDB?
You can also find demo code for the presentation at the following location.
https://github.com/dotnetjalps/gab16augdemo

Due to the huge interest in people, We promise them to have some advanced level sessions about DocumentDB in forthcoming months.

After that Jagdish has taken over the stage and had presented about Azure mobile services. He presented how we can leverage Azure mobile services with Windows Phone Application and some other cool insights for Azure mobiles services.

DSCN5894

Then we had lunch and we had some great interaction and conversation about cloud technologies during lunch.

DSCN5897DSCN5895DSCN5905DSCN5896

After lunch, there was post lunch session. It was time for Sanket Shah to rock the stage. He has presented about Architecting Modern solution on Azure.  He had some cool demo and audience was amazed about his demo.

DSCN5900
DSCN5901

After that, we had another back to back session from Kaushal Bhavsar. He had presented about how we can create a secure two factors authentications with  Azure technologies. He had some given some cool demo using Azure Active directory and Office 365 account authentication about it.

DSCN5906
DSCN5907

After that we had tea and It’s time for Ahmedabad User group president Mahesh Dhola to rock the stage. Instead of giving demo he chooses to use WhiteBoard and given presentation DevOps and Microsoft Azure. It was fun watching is him presenting the topic that we all love.

DSCN5912
DSCN5914

After the presentation, it was the time where everybody wants to get some prize. We had the lucky draw and almost everybody gets price.

DSCN5917DSCN5924
DSCN5925DSCN5921
DSCN5926DSCN5927

And this guy was an inspiration for all us.

DSCN5919

Then we has some photos of all the speakers. We missed Jagdish here as he needs to go home for some personal work.

DSCN5933

Overall, It was a fun event. We had some much fun hacking and learning something new. Thank you, Microsoft and Ahmedabad user group for hosting such a nice event.

Keep rocking!.
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