Delete Duplicate Entries In A Sql Server Table

Couple days ago I wrote a quick post demonstrating how to find duplicate records in a SQL server table. A colleague of mine read the post and asked me to show how to delete the duplicates  from the table. Therefore, I thought it would make sense I put this post together on how to delete duplicate entries in a table.

What does it take to remove duplicates from a table?

  • First, we need to validate the data to see the duplicates we are deleting.
    WITH student_cte AS (
        SELECT 
            First_Name, 
    		Last_Name,
    		Phone, 
            ROW_NUMBER() OVER(
                PARTITION BY 
                    First_Name, 
                    Last_Name, 
                    Phone
                ORDER BY 
                    First_Name, 
                    Last_Name, 
                    Phone
            ) rn
         FROM dbo.Students
    )
    select * from student_cte;
    
  • The picture below shows the records that are duplicates with the row count.
  • Now, in order to delete these record, I am going to show the best way to handle using that same CTE query above with a slight modification. I have deleted any instance with rn > 1.
    WITH student_cte AS (
        SELECT 
            First_Name, 
    		Last_Name,
    		Phone, 
            ROW_NUMBER() OVER(
                PARTITION BY 
                    First_Name, 
                    Last_Name, 
                    Phone
                ORDER BY 
                    First_Name, 
                    Last_Name, 
                    Phone
            ) rn
         FROM dbo.Students
    )
    DELETE FROM student_cte WHERE rn >1;
    
  • After running the query above, the duplicated records are now gone.

In this post, I showed how you can get rid of duplicate rows from a table in SQL Server. I hope after reading this article you will be able to use these tips. If you have questions or feedback, please share it with me. I’d like to know what you’re thinking. Please post your feedback, question, or comments about this article.

How To Get Sendgrid API Key To Send E-mails

In Sendgrid there are 3 different types of API keys that you can generate to use in your application. Which one to use depends on your requirements need. Therefore, in this post I am going to show how to setup a simple restricted API key to be used on my next e-mail demo.

Types of API KEYS Available

  • Full Access which allows the API key to access GET, PATCH, PUT, DELETE and POST endpoints for all parts of your account, excluding billing and Email Address Validation.
  • Restricted Access, this is a customized type where you can set levels of access for all parts of your account, excluding billing and Email Address Validation.
  • Billing Access which allows the API key to access billing endpoints for the account.

Steps to create new Sendgrid API Key

  • First, you need to head over to Sendgrid.com and create an account. Once you log into the application, it will take you to the dashboard area. Click on Setting on the left pane to expand it.
  • Next, click on the “API KEY” as shown below. That will open the page to allow you to create a new API KEY.
  • Now, click on the “Create API Key” button at the top right corner, it will open the 3 types of API Key to select and the different options you need to setup.
  • For the purpose of this tutorial, I am going to set this key for sending email only.
  • Once you’re done you will get a key. The API KEY generated and displayed to you just once. So be sure to copy and save it somewhere. After that only the subset key is displayed.

Last, some notes to keep in mind.

Sendgrid only allows 100 keys per account.

Once you delete a key, it can no longer be used to access SendGrid’s services.

 

How to create a simple Todo list Using Jquery

Yes, you heard it, a simple doto list using Jquery. We all know the famous hello world applications when we’re first learning a language. Now, it’s the todo app. In this post I am going to create a simple web todo application using HTML5, CSS3 and Javascript(jQuery).
You can develop this todo application in any text editor and debug in any browser. I’m using Plunker to code this due to its simplicity. You can follow along with using this Plunker demo link

Todo list Using Jquery – Project Setup

First things first, we need to set up our project. Let’s add a new index.html file to our plunker project as shown below.

  
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link data-require="bootstrap@3.3.6" data-semver="4.1.3" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
    <script data-require="bootstrap@3.3.6" data-semver="4.1.3" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="3.2.1" src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div class="col-md-12">
      <h1>Simple Todo Demo!</h1>
      <p>Click on row to delete newly added entry.</p>
      <div data-role="content">
        <ul class="list-group" id="taskListSection">
          <li class="list-group-item active">Todos</li>
          <li class="list-group-item ">1. Example of Existing task</li>
          <li class="list-group-item ">2. Example of Existing task</li>
        </ul>
        <br />
        <fieldset class="ui-grid-a">
          <div class="ui-block-a">
            <textarea placeholder="Enter task" id="taskInputText" cols="50" maxlength="128"></textarea>
          </div>
          <div class="ui-block-b">
            <input type="button" class="btn btn-success" value="Submit" id="taskBtn" />
          </div>
        </fieldset>
      </div>
    </div>
  </body>

</html>
  

Nothing too fancy in that html code. We have a heading and paragraph to let user know to click newly created task. Next is an unordered list group from bootstrap 4 showing 2 items to start with. Think of those two items as existing data from a database. Next is a simple textarea to allow user to type new task entry to add to the list. Last, we have a button which will fire the add operation when user click on it.

Add script to handle add and delete tasks


// Add your javascript here
$(function(){
  $("h1").animate({
    "margin-left": "100px"
  }, "slow");
  

$('#taskBtn').click(function() {
  
    var newTask = $('#taskInputText').val();

    if(newTask !== '') {
      
        var count = $("#taskListSection").children().length;
        
        $('#taskListSection').append('<li class="list-group-item deletetask bg-success">' + count + '. '+ newTask + '</li>');
       
        $('#taskInputText').val('');
        
        deleteTasks();
        
        setTimeout(function(){
          $('#taskListSection li.bg-success').removeClass('bg-success');
        },1000); 
      
    } else {
        alert('Come on, you\'re better than that');   
    }
});  
});

function deleteTasks(){
 $('.deletetask').click(function(){
    $(this).remove();
}); 

}

Again, a simple javascript file containing animation for the heading of the page upon loading. Then, I have a click event listener for when user wants to add a new task to the list. A one second delay is added after the new entry is added to the list and row is highlighted. Then, it is unhighlited after the one second is expired.
A delete function is in there as well to remove the item from the list. Very basic.

Find Duplicate Entries In A Sql Server Table Using CTE

In my last post, I showed how to find duplicate entries in a sql server table using group by which was pretty simple to pull off. I thought it would be a good idea to find the list of all the duplicate rows using CTE for those that are fan of it. We will be using the same table from our previous post on finding duplicate rows which you can read and follow.

What is CTE

A CTE which is short for Common Table Expression, is a temporary result set that you can reference within another query statement. They are used to simplify large queries.

Find duplicate rows CTE

   WITH student_cte AS(
        SELECT  First_Name, 
                Last_Name,
                Phone,  
                COUNT(*) Occurrences
        FROM dbo.students
        GROUP BY
                First_Name, 
                Last_Name,
	        Phone
       HAVING COUNT(*) > 1
  )
  SELECT	st.Id,
		st.First_Name, 
		st.Last_Name,
		st.Phone  		
 FROM dbo.students st
 INNER JOIN student_cte 
  ON student_cte.First_Name = st.First_Name
  AND student_cte.Last_Name = st.Last_Name;

Find duplicate entries result

Find duplicate entries using cte as query

Quick Way To Find Duplicate Rows In A Sql Server Table

If you are dealing with duplicate rows in a SQL server database, and you’re not sure how to find them, don’t panic. I had to deal with a similar situation recently.
Two weeks ago, I was working on a project where I had to import some data from a legacy system into a whole new table. After the data had been loaded and a report was generated with that data, we’ve noticed there were some duplicate entries. Therefore, I had to quickly figure out how to put together a quick query to find duplicate rows and removed them from the table.

In this post I will show simple steps to take in case you are facing the same issue. In order to get this post, I am going to create a new table and populate it with some seed data.

Create Database

DROP TABLE IF EXISTS Students;
CREATE TABLE Students (
    Id INT IDENTITY(1, 1), 
    First_Name  nvarchar(100), 
    Last_Name  nvarchar(100), 
    Phone nvarchar(12),
    PRIMARY KEY(id)
);

Populate the table with data

Now that we have our table added, I will proceed to populate it with some data for our demonstration.

   INSERT INTO dbo.Students
        (first_name,last_name,phone) 
   VALUES
        ('Mary','Allan','407-455-1414'),
	('John','Doe','407-445-5414'),
        ('Chirac','Paul','407-455-1814'),
	('John','Doe','407-445-5414'),
        ('Mela','Jil','407-787-6767'),
	('John','Doe','407-445-5414'),
        ('Mary','Allan','407-455-1414'),
	('John','Doe','407-445-5414'),
        ('Mary','Allan','407-455-1414'),
	('Chris','Tai','407-555-7777'),
	('Albert','Allan','321-455-9977'),
	('Jean','Doe','407-445-5414');

Ensure the data was inserted properly

Okay, we have the data we need in the table, let’s run a quick query to see if it match our criteria, in order words have some duplicates. Let’s run a simple select statement to retrieve the full data-set in the the table.

   SELECT Id, First_Name, Last_Name,Phone 
   FROM dbo.students
   ORDER BY First_Name, Last_Name desc;

Query result to find duplicate rows in table

Find duplicate rows in the table

As a matter of fact, there are many ways to find and return the duplicates. I ended up using group by to get my result, If you end up using some other method, please share it in the comment below.

 SELECT  First_Name, 
          Last_Name,
          Phone,  
          COUNT(*) Occurrences
  FROM dbo.students
  GROUP BY
    First_Name, 
    Last_Name,
    Phone
  HAVING 
    COUNT(*) > 1;


Last, below you can see the result of the duplicated rows found and the number of time.
Find duplicate rows in sql server table

How To Send E-mail In ASP.Net Core Using Mailkit

Send E-mail In ASP.Net Core

I am working on this new project where I need to implement a way for us to send newsletters to users on a weekly basis which requires some sort of ways to sending html content in the email.
Well, I’ve always wanted to use this library called Mailkit, so I thought it would be a good opportunity to put a quick post together and sample application to try it first before implementing it in the project. Of course, if you don’t want to use MailKit, you could always make use of the .Net Core SMTP Client.

For simplicity, I’ll keep this post short and focus solely on how to send the e-mail in .NET Core using MailKit.

  • First, create a new ASP.NET Core application with the following name “SendEmailInAspNetCore”
    “File” –>”New” –>”Project”
  • A “New Project” dialog will open. Select “.NET Core” in the left panel inside the Visual C# menu.
    Create send email project to send E-mail In ASP.Net Core
  • Next, select the Web Application (Model-View-Controller) template as shown below.
    Select the right template for the project to send E-mail In ASP.Net Core
  • Once the project is created, make sure to build it and verify that there’s no error before you proceed further.
  • Now, that we know we have a working project to start with, let’s use NuGet to add the “Mailkit” library to the project.
  • Add a new class in the Model folder called “ContactViewModel.cs. In it, we’ll have the following properties to collect the email form data.
    using System.ComponentModel.DataAnnotations;
    
    namespace SendEmailInAspNetCore.Models
    {
        public class ContactViewModel
        {
            [Required]
            [StringLength(60, MinimumLength = 5)]
            public string Name { get; set; }
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Subject { get; set; }
            [Required]
            public string Message { get; set; }
        }
    }
    
    
  • To keep this simple, let’s update the contact view with a simple contact form as shown below.
    
    @model SendEmailInAspNetCore.Models.ContactViewModel
    @{
        ViewData["Title"] = "Contact";
    }
    <h3>Send E-mail In ASP.Net Core 2.1 Using MailKit</h3>
    
    <div class="has-error" col-md-12>
        <form method="post">
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Name">Name:</label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Email">Email:</label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Subject">Subject:</label>
                    <input asp-for="Subject" class="form-control" />
                    <span asp-validation-for="Subject" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-6">
                    <label asp-for="Message">Message:</label>
                    <textarea rows="8" cols="20" asp-for="Message" class="form-control"></textarea>
                    <span asp-validation-for="Message" class="text-muted"></span>
                </div>
            </div>
            <div>
                <button type="submit" class="btn btn-success">Send Message</button>
            </div>
        </form>
    </div>
    
    
  • Let’s update the controller to add a new action to post the contact form to.
     [HttpPost]
     public IActionResult Contact(ContactViewModel contactViewModel)
     {
       if (ModelState.IsValid)
       {
         try
            {
              //instantiate a new MimeMessage
              var message = new MimeMessage();
              //Setting the To e-mail address
              message.To.Add(new MailboxAddress("E-mail Recipient Name", "recipient@domail.com"));
              //Setting the From e-mail address
              message.From.Add(new MailboxAddress("E-mail From Name", "from@domain.com"));
              //E-mail subject 
              message.Subject = contactViewModel.Subject;
              //E-mail message body
              message.Body = new TextPart(TextFormat.Html)
              {
                Text = contactViewModel.Message + " Message was sent by: " + contactViewModel.Name + " E-mail: " + contactViewModel.Email
              };
    
              //Configure the e-mail
              using (var emailClient = new SmtpClient())
              {
                emailClient.Connect("smtp.gmail.com", 587, false);
                emailClient.Authenticate("emailaddress@gmail.com", "password");
                emailClient.Send(message);
                emailClient.Disconnect(true);
               }
            }
            catch (Exception ex)
            {
              ModelState.Clear();
              ViewBag.Message = $" Oops! We have a problem here {ex.Message}";
            }
        }
        return View();
     }
    
  • Let’s run the application now, click on the contact menu item
  • Below is an example error when trying to send the email with a bad credentials.
    Displaying the error message in E-mail In ASP.Net Core
  • Let’s try to send a valid email now. As you can see below the e-mail was received with no problem.
    Showing how message was successfully sent out in the project E-mail In ASP.Net Core

Source Code is available for download on GitHub

51 Business Listing Websites For Local Businesses

If you are a business owner, you should know and understand the importance of having your business listed in the top major search engines on the internet. With the competition being so fierce, those business owners who understand and take action will always win. Therefore, I have compiled a list of all the major platforms for you to list your business and start growing your fan base.

I come up with this list and started using it on some local businesses that I have worked with in the past. Since most of them provide free submission, I thought others would be interest in making use of them to bring more visibility to their business. Getting your business listed on as many online local directories as possible is the best and quickest way to make sure potential new customers find you when searching for products and services related to your business.

Before I start by sharing this list with you. I want you to know that this will not be an easy or quick task. It will require some effort and time on your part to go to each of those website and submit your business information.

Promote on search engines for Local Businesses

Basic checklist to follow when submitting your business those platform

  • NAP – Some of those platforms will on require the basic NAP for your business which is your business’s Name, Address & Phone number. Therefore, make sure that information is the same on all them.
  • Business Description – If you are allowed to submit a business description, take the time to make sure you write something meaningful about the services your business provide. DO NOT LEAVE IT BLANK. This is where you highlight your company’s history and services offered. BE CREATIVE!
  • Website Link – This one of the most important piece of information you MUST provide if your company has a website. This is a great way to drive more traffic to your website and help people who want to learn about your business discover what you have to offer.
  • Pictures And Videos – Majority of listing platforms allow businesses to post pictures and short videos about their services. Take on the opportunity and showcase your business best. Let the world know why they should care about your services or products.
  1. Upamile
  2. Google
  3. Bing
  4. Yelp
  5. Facebook
  6. Better Business Bureau
  7. Angie’s List
  8. Merchant Circle
  9. LinkedIn
  10. YP.com
  11. Whitepages
  12. Superpages.com
  13. Yellowbook
  14. CitySearch
  15. MapQuest/Yext
  16. Local.com
  17. Foursquare
  18. CitySlick
  19. USDirectory.com
  20. BizJournals.com
  21. TeleAtlas
  22. Discover Our Town
  23. EZ Local
  24. CityVoter
  25. Manta
  26. UsCity
  27. InfoUSA
  28. Infignos
  29. Get Fave
  30. My Huckleberry
  31. Yellowee
  32. Brownbook
  33. Magic Yellow
  34. CitySquares
  35. Map Creator
  36. Judy’s Book
  37. TripAdvisor
  38. Thumbtack
  39. YellowPagesGoesGreen.org
  40. Home Advisor
  41. ShowMeLocal
  42. ChamberofCommerce.com
  43. Yellowbot
  44. Hotfrog
  45. Brownbook
  46. InsiderPages
  47. Bizwiki
  48. Business Local Pages
  49. iBegin
  50. Opendi
  51. Sitejabber

Having Website Traffic Drop After Switching To HTTPS? Don’t Panic

Things to keep in mind if you are working on a website and have your traffic drop after switching to HTTPS

Before I continue I want to make sure I address two points to make sure we’re on the same page.
First, by switching to HTTPS/SSL security on your website, you will sometimes experience a drop in the amount of indexed urls you had.
Secondly, You should always consider implementing SSL on your website. As a matter of fact the earlier the better. While, it’s true that not all websites will need to have SSL implemented, but for those that are housing personal information such as a user login data, and e-mail MUST absolutely consider using SSL.

About a few months ago I started working on optimizing the traffic to one of my website and things started to turn around. People started to find and visit the website on a daily basis. I was getting pretty good amount of traffic for a brand new site.

Use Google Search Console

Using Google search console, I setup the site, and submitted my links regularly. Gradually over time I could see most of the links submitted were being indexed. Well, I have this feature that requires payment to be accepted on the site, therefore, I had to make sure the site was secured.

The traffic drop after switching to HTTPS in no time

After I switched the paid feature and switch on to HTTPS, I started noticing a drop in the organic traffic to the site.
So, I went straight to the Google Search Console to analyse the traffic, and indeed, when I check the coverage tab, It was reported that my website search results essentially dropped to almost zero with only 30 valid urls and 420 excluded.
[Add pic here]Google Search Console coverage report

I was curious to learn more about those 420 excluded links, when I drilled down more into this, I noticed about 307 of pages were being excluded due to “Page with redirect”.
Google search displaying coverage report of total links excluded from index

I researched the web about possible cause of that issue knowing that I recently updated the site from HTTP to HTTPS and I have never setup any 301 redirects on these urls.

Google search displaying coverage report of links that are no longer indexed

Start Tracking the correct domain

If you find yourself in the same situation don’t panic. The issue simple and easy fix. What happened was that Google was tracking the regular links on the site and a user lands on those pages, they are being redirected to the secured links. Therefore, those regular links are dropped from being indexed. However, Google still tracking the secured links. In order to view the report on them, all you have to do is add the secured url to Google search console. It should show the correct stats about your indexes.
Right after the update on the Google Search Console, I was able to re-index and track the https://domain and I could see that site is indeed still showing up in the searches.
Google search displaying coverage report of click and links indexed

How To Quickly Create A New Database Using EntityFramework Core On ASP.Net Core

Last post I’ve gone over how to disable a specific user in ASP.NET Core Identity 2.0, so in this post here, we’ll take a look at how we can leverage Entity Framework to quickly create new databases in no time. Therefore, I will be creating an employee manager using ASP.NET Core 2.1 and Entity Framework (EF) core Code First approach. This employee manager tracks all employees and their respective department.

Prerequisites

Install .NET Core 2.1 SDK from here
Install the latest version of Visual Studio 2017 from here
SQL Server 2008 or above
Source Code
Before proceeding, I recommend you get the source code from GitHub.
Quick read & Credit to: Entity Framework Core on ASP.NET Core

Create the ASP.NET Core project

Open Visual Studio and select “File” > “New” > “Project”.

After selecting the project, a “New Project” dialog will open. Select “.NET Core” in the left panel inside the Visual C# menu.

Then, select “ASP.NET Core Web Application” from the available project types. Put the name of the project as “EmployeeManagerWithEFCore” and press “OK” to create the ASP.NET Core Project.

A new dialog box will open asking you to select the template to be used for the project. So, make sure to select the following:

  • Make sure that .NET Core and ASP.NET Core 2.1 are selected in the drop-down lists
  • Select the Web Application (Model-View-Controller) project template
  • Make sure that Authentication is set to No Authentication
  • Click OK

Selecting the correct project template

By default the “No Authentication” option will be selected, however, if you are required to add login, you can change that in the change authentication button and select Individual User Accounts . Since this tutorial is simply to show how to get started with EntityFramework Core, we’ll keep things simple and not required user to login in in order to add new employees.

To make sure the project is created correctly, let’s run it and make sure there’s no errors before we start adding the models.
Load asp.net net project to ensure it's working

Adding the necessary Models

  • Employee
  • Department

Now, that we know we have a working application, let’s add the models.
Right-click on the Models folder and select Add > Class.

Enter Employee.cs as the name and click OK as seen in the image below.

Replace the contents of the file with the following code:

using System.ComponentModel.DataAnnotations;

namespace EmployeeManagerWithEFCore.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [MaxLength(60)]
        public string FirstName { get; set; }
        [MaxLength(60)]
        public string LastName { get; set; }
        [Required]
        public int Salary { get; set; }
        [Required]
        [MaxLength(20)]
        public string Title { get; set; }
    }
}

Next, right-click on the Models folder and select Add > Class.

Enter Department.cs as the name and click OK.

Replace the contents of the file with the following code:

using System;
using System.Collections.Generic;

namespace EmployeeManagerWithEFCore.Models
{
    public class Department
    {
        public Department()
        {
            Employees = new List();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string MapIcon { get; set; }
        public bool Deleted { get; set; }
        public DateTime UpdatedAt { get; set; }
        public DateTime CreatedAt { get; set; }
        public virtual ICollection Employees { get; set; }
    }
}

Add ConnectionString

Now, let’s add a new connectionstring in the appSettings.json file to be use for the database as followed.

Add the DbContext

Right-click on the Models folder and select Add > Class.

Enter ApplicationDbContext.cs as the name and click OK.

Replace the contents of the file with the following code:

using Microsoft.EntityFrameworkCore;

namespace EmployeeManagerWithEFCore.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options)
            : base(options)
        { }

        public DbSet Employees { get; set; }
        public DbSet Departments { get; set; }

    }
}

Some key notes about the above code snippet:

The class ApplicationDbContext is derived from DbContext which is a class that manages the database connection.
The DbSet properties are used to map with the database tables.

Register the db context

Now, we can register the context via the service configuration in the startup.cs file as shown below.

We have everything we need in the project to build it and make sure there’s no error. Once done, we can start creating the database.

Add Database

Tools > NuGet Package Manager > Package Manager Console

Run the following commands:
In order to generate the database and add the necessary tables, we need to run migration commands from the package manager console.

In Visual Studio select Tools > NuGet Package Manager > Package Manager Console.
Run the following commands:

 Add-Migration InitialDatabaseCreation
 Update-Database

In case you run into some error as I did during in this step, simply close Visual Studio and re-open the project. Then, re-run add-migration again.

Voila, after closing and re-open Visual Studio, I was able to successfully run Migration as expected.

PM> Add-Migration
cmdlet Add-Migration at command pipeline position 1
Supply values for the following parameters:
Name: InitialDatabaseCreation
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.1.0-preview2-30571 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
To undo this action, use Remove-Migration.
PM> Update-Database
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.1.0-preview2-30571 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (447ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      CREATE DATABASE [EmployeeManagerWithEFCoreDB];
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (61ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
      IF SERVERPROPERTY('EngineEdition') <> 5
      BEGIN
          ALTER DATABASE [EmployeeManagerWithEFCoreDB] SET READ_COMMITTED_SNAPSHOT ON;
      END;
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [__EFMigrationsHistory] (
          [MigrationId] nvarchar(150) NOT NULL,
          [ProductVersion] nvarchar(32) NOT NULL,
          CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
      );
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (33ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT OBJECT_ID(N'[__EFMigrationsHistory]');
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT [MigrationId], [ProductVersion]
      FROM [__EFMigrationsHistory]
      ORDER BY [MigrationId];
Microsoft.EntityFrameworkCore.Migrations[20402]
      Applying migration '20190114032255_InitialDatabaseCreation'.
Applying migration '20190114032255_InitialDatabaseCreation'.
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [Departments] (
          [Id] int NOT NULL IDENTITY,
          [Name] nvarchar(max) NULL,
          [Description] nvarchar(max) NULL,
          [MapIcon] nvarchar(max) NULL,
          [Deleted] bit NOT NULL,
          [UpdatedAt] datetime2 NOT NULL,
          [CreatedAt] datetime2 NOT NULL,
          CONSTRAINT [PK_Departments] PRIMARY KEY ([Id])
      );
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE [Employees] (
          [Id] int NOT NULL IDENTITY,
          [FirstName] nvarchar(60) NOT NULL,
          [LastName] nvarchar(60) NULL,
          [Salary] int NOT NULL,
          [Title] nvarchar(20) NOT NULL,
          [DepartmentId] int NULL,
          CONSTRAINT [PK_Employees] PRIMARY KEY ([Id]),
          CONSTRAINT [FK_Employees_Departments_DepartmentId] FOREIGN KEY ([DepartmentId]) REFERENCES [Departments] ([Id]) ON DELETE NO ACTION
      );
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX [IX_Employees_DepartmentId] ON [Employees] ([DepartmentId]);
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
      VALUES (N'20190114032255_InitialDatabaseCreation', N'2.1.0-preview2-30571');
Done.
PM> 

To conclude, if you check in sql server management and load your local databases, we should be seeing the new database created.

Add Department and Employee controller as shown below.

Controller.
Select MVC Controller with views, using Entity Framework and click Add.
Set Model class to respective to the controller being created and Data context class to ApplicationDbContext.
Make sure to select the “_Layout.cshtml”
Click Add.

Once those controllers are created you should notice two files “DepartmentsController.cs”,”EmployeesController.cs” in the controller folder and the view folder for each of those controllers with with the necessary view pages with (.cshtml).

Let’s run the application and see what we get and start populating the database.

Example of the department creation page:

For simplicity, I have hard-coded the department to get the employees added to the department we have created. For production, you might want to add a dropdown list for user to select the department while creating the employee.

Disable A Specific User in ASP.NET Core Identity 2.0

I am writing this post simply to document a used case I had a few days ago. I basically wanted to disable a user instead of deleting the meta data from the system.
Since the project was built with regular ASP.Net Core Identity, It didn’t take too long for me to figure this out.

What’s ASP.Net Core Identity?

It is a simple membership system that add login capability to any asp.net Core applications. ASP.Net Core Identity supports external login providers such as Facebook, Twitter, Microsoft, and Google.
In case you would like to learn more about it, feel free to read this post on identity.

Implementation In ASP.NET Core Identity 2.0

I had to add a new property called “IsActive” as shown in the code snippet below to the “ApplicationUser.cs” class to disable the user in the system.

namespace UserApp.Models
{
 //Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsActive { get; set; }
    }
}

Next, I run migration to add the new column to the AspNetUsers table.

Now that I have the new column added to the table, I need to set the IsActive flag during registration.

Where do you update the IsActive flag by default?
Find the action method called RegisterAsync in the “AccountController.cs” and

 public async Task RegisterAsync(RegisterViewModel model, string returnUrl = null)
 {
   ViewData["ReturnUrl"] = returnUrl;
   if (ModelState.IsValid)
   {
        var user = new ApplicationUser
        {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    IsActive = true
         };
         var result = await _userManager.CreateAsync(user, model.Password);
         if (result.Succeeded)
         {
           _logger.LogInformation("User created a new account with password.");

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
            await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
            logger.LogInformation("User created a new account with password.");
            return RedirectToAction(nameof(ConfirmRegistration));
         }
         AddErrors(result);
     }

     // If we got this far, something failed, redisplay form
     return View(model);
 }

Finally, after running the application and register a brand new user I was able to verify the data in the database. In case you need already have some existing users, you’ll simply need to run an update query to set their flag to active. That’s it!!!