Method not found: Void Microsoft.EntityFrameworkCore.Design. Internal.DbContextOperations

I was working on this asp.net Core application and got this error below while trying to scaffold a new controller as seen below. I suspected the issue happened because I had updated a few packages in the project.
Scaffolding new controller asp.net core Microsoft.EntityFrameworkCore.Design

Error message

Method not found: 'Void Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations..ctor
(Microsoft.EntityFrameworkCore.Design.Internal.IOperationReporter, System.Reflection.Assembly, System.Reflection.Assembly)'.
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

Solution

After a quick searching and reading a few post online, I stumbled upon this one post on Stackoverflow where someone had similar issue. So, below you will find exactly what I did to resolve that issue which was very simple.

  • I unload the project, Right click the project -> Unload Project
  • Next, Right click the unloaded project name and Edit the .csproj file
  • Find the ItemGroup section in the .csproj file as seen below and update the following
    
     <ItemGroup>
      <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
      <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.7" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.3" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.3" PrivateAssets="All" />
      <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.3" PrivateAssets="All" />
     </ItemGroup>
    
    
  • Once done updating the versions, right click the project name and reload it. Then, clean the solution and build the project afterwards. If this doesn’t work for you then downgrade to a lower version until you get it to work.

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!!!

How To Use In-Memory Cache In An ASP.NET Core Web API

Before we can dive into the In-Memory Cache implementation, first, What is caching and when you should consider using it?

Well, caching is basically a technique of storing frequently used data in a temporary storage. Caching can significantly improve the performance and scalability of any application by reducing the time and resources required to load fresh contents. Using that technique will definitely make the end user much happier to use the app.

Types of Caching supported by ASP.Net Core

As you might already know ASP.NET Core supports different types of caching such as In-Memory Cache, Distributed Cache and Response Cache. However, in this post I will take the opportunity to introduce you to how to use In-Memory Cache in an ASP.Net Core Web API app.

How data is stored

When using the In-Memory Cache feature, the data is stored in the memory of Web Server where a web application is being hosted at. It’s good to remember that an application can be hosted on single Server or multiple Servers in a Server Farm. For those of you that have a single server, you should be just fine using In-Memory Cache with no issues because it doesn’t require much to get running, however, if those running on multiple servers on a server farm MUST ensure that the sessions are sticky.

Setting cache expiration time

When adding an item to the cache you set an expiration, this can be an absolute time, a sliding window or the combination of both. Choosing which one to use depends on your scenario.

Example of how to implement In-Memory Cache

To keep thing simple and easy to follow I am going to implement a quick sample API to retrieve the states name using state abbreviation as code. In order to get start simple create a new blank WEB API project in Visual Studio and follow the steps below to fill in the required pieces or you can download the full sample code from github here.

Injecting the dependency from the startup.cs.

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMemoryCache();
      services.AddMvc();
    }

Now that the In-Memory Cache service has been added, I can access the cache from inside the controllers by simply injecting an IMemoryCache parameter in the constructors.

    private readonly IMemoryCache _cache;

    public StatesController(IMemoryCache memoryCache)
    {
      _cache = memoryCache;
    }

Get Method setup

Next, I need to set my cache inside the get action method which is used to get the name of the state that matches the search criteria.

   [HttpGet("{stateCode}")]
   public async Task Get(string stateCode)
   {
      string state = string.Empty;
      if (!_cache.TryGetValue("CashedStatesList", out Dictionary states))
      {
       Console.WriteLine("Loading from database or json file into cache");

        states =
           JsonConvert.DeserializeObject>(
           await System.IO.File.ReadAllTextAsync("StatesList.json"));

        MemoryCacheEntryOptions options = new MemoryCacheEntryOptions
        {
         AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300), // cache will expire in 300 seconds or 5 minutes
         SlidingExpiration = TimeSpan.FromSeconds(60) // cache will expire if inactive for 60 seconds
        };

        if (states != null)
        _cache.Set("CashedStatesList", states, options);
      }
      else
      {
         Console.WriteLine("***Data Found in Cache...***");
      }

      if (states != null)
      {
         state = states.GetValueOrDefault(stateCode);

         if (string.IsNullOrEmpty(state))
         {
           state = "Not found, please try again.";
         }

      }

      if (string.IsNullOrEmpty(state))
      {
         return NoContent();
      }
      return Ok(state);
  }

Reading from data source

In the code snippet above as you can see the very first if condition is checking against the cache dictionary object to load the states list if exist, otherwise, it will continue and load the states from the json file. To be clear here’s the snippet of code that reads the json file and load the states list.

  states =
           JsonConvert.DeserializeObject>(
           await System.IO.File.ReadAllTextAsync("StatesList.json"));

Set cache expiration

Then, once the data was cached, I set some times to when it will expire which is 5 minutes and if no activity they will expire in 60 seconds. You can set these values according to your requirements.

   MemoryCacheEntryOptions options = new MemoryCacheEntryOptions
   {
     AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300), // cache will expire in 300 seconds or 5 minutes
     SlidingExpiration = TimeSpan.FromSeconds(60) // cache will expire if inactive for 60 seconds
   };

Then, if you continue reading the code above you will notice where the cache is being set as expected.
Last, as you can see from this simple example, the In-Memory cache is can be very beneficial when hosting an application on a single Server. It stores data on Server and improves application performance. Don’t forget to test your app to not depend solely on cached data.
In case you would like to read more about In-Memory cache, please visit these links below.
Cache in-memory in ASP.NET Core

WordPress Installed in Sub Directory on Windows Server Not Loading

Experience with WordPress windows-server

Setting up and running a WordPress content management system on a Windows Server isn’t always as simple as its Unix counterpart. There’s always something that could go wrong and course I had a pretty interesting experience setting a blog on one of the website I am working on.
Well, I have been working on an ASP.Net Core web application, I wanted to install WordPress in a sub directory to add a blog to the site. At first I thought it would be simple to do so, but I ran into issues after I had installed and setup the whole blog.

WordPress windows-server Error

Well, the problem I was having was that when navigating to the folder which WordPress was installed, I was getting a 404 error as shown below.

This www.example.com page can’t be found No webpage was found for the web address: https://www.example.com/blog
HTTP ERROR 404

Solution

In order to resolve this issue I have read a few post describing the possible cause which was related to the .htaccess file that could be missing on the server. Well, since this was a Windows box, there was a web.config file instead.

I then updated the web.config file on the server with the following content and voila it works. Simply replace “yourdomainname” text with your actual domain.


<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
	 <rule name="WordPress: http://yourdomainname.com/blog" patternSyntax="Wildcard">
	   <match url="*"/>
		<conditions>
		  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
		  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
		</conditions>
		<action type="Rewrite" url="index.php"/>
	   </rule></rules>
    </rewrite>
    <handlers>
      <remove name="aspNetCore"/>
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\yourdomainname.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout"/>
  </system.webServer>
</configuration>

Quick and Easy Way To Set Authorization Header of HttpClient

Earlier today I was working on this application which requires me to make a few calls to a REST API to get some products back in XML format. In order to accomplish this task, I have instantiated an HttpClient object which to make the call. However, I was getting this security error below saying “Required OAuth credentials not provided”.

 

  900902
  Missing Credentials
  Required OAuth credentials not provided

Solution

Of course the error message is self explanatory, I was missing the authorization token in the header.

string url = "https://api.web.com/search/1.0" + ";
using (var client = new HttpClient())
{
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "my_authorization_token"); ;
  HttpResponseMessage response = client.GetAsync(new System.Uri(url)).Result;
  string responseBody = response.Content.ReadAsStringAsync().Result;
}

RichTextBox Example using Free TinyMCE Editor In ASP.Net Core

In this post, I’d like to take the opportunity to explain briefly how to use the TinyMCE plugin to add Rich TextBox feature to your .Net application. For this specific example I am currently using .Net Core 2.0. Don’t worry if you’re on an earlier .Net version because the implementation is about the same.

First of all, we need a project to be created. I’ll call it TinyMCEDemo which is available on github if you would like to download.
tinymce demo project
Once the project is created, run it and make sure there’s no issues.
For this project I am adding a new Model object called “Book” and a new controller called BooksController. We’ll use the create view to add the book form.

namespace TinyMCEDemo.Models
{
    public class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public string Description { get; set; }
    }
}

After adding the new books controller, run the project and you should see the following book form as shown below.

Now, to install the plugin the simplest way to do so is to reference the CDN endpoint at this location below by adding it to the layout.cshtml file before the site.js reference file.

 
  
  <script src='https://cloud.tinymce.com/stable/tinymce.min.js'></script>
 

Next update the site.js file with the following scripts below.

Since TinyMCE lets you identify replaceable elements via a CSS selector, all you need to do is pass an object that contains a selector to tinymce.init().

In this example, let’s replace all ‘textarea(s)’ with a TinyMCE editor instance by passing the selector ‘textarea’ to tinymce.init() which will enable tinymce to all all textarea in the application.


(function ($) {
    "use strict";
    $(document).ready(function () {
        tinymce.init({
            selector: 'textarea'
        });

    });
})(this.jQuery);

Run the project now and the description should now render the Rich Text format as shown below. If you have any issues please let me know and I’ll try my best to help.

Download TinyMCEDemo Project Here

The current CSharpHelper cannot scaffold literals of type ‘Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding’. Configure your services to use one that can

I am working on a .Net Core 2 application today and tried to apply Add-Migration after I had rollback to an earlier version. Something I’ve done many times with no issues and all the sudden I started seeing this error message below. After researching it for a few minutes, I was able to resolve it pretty quickly. Below are the error message and what was done to rectify it.

Microsoft.EntityFrameworkCore.Migrations[20405]
      No migrations were applied. The database is already up to date.
System.InvalidOperationException: The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.
   at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.UnknownLiteral(Object value)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.GenerateAnnotation(IAnnotation annotation, IndentedStringBuilder stringBuilder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.GenerateEntityTypeAnnotations(String builderName, IEntityType entityType, IndentedStringBuilder stringBuilder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.GenerateEntityType(String builderName, IEntityType entityType, IndentedStringBuilder stringBuilder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.GenerateEntityTypes(String builderName, IReadOnlyList`1 entityTypes, IndentedStringBuilder stringBuilder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.Generate(String builderName, IModel model, IndentedStringBuilder stringBuilder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGenerator.GenerateMetadata(String migrationNamespace, Type contextType, String migrationName, String migrationId, IModel targetModel)
   at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.

Below is the solution which I have applied. Simply install this package below

Install-Package Microsoft.EntityFrameworkCore.Design

Once done, I was able to run add-migration with no problem as seen below.

Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.1.4-rtm-31024 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT OBJECT_ID(N'__EFMigrationsHistory');
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT OBJECT_ID(N'__EFMigrationsHistory');
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT [MigrationId], [ProductVersion]
      FROM [__EFMigrationsHistory]
      ORDER BY [MigrationId];
Microsoft.EntityFrameworkCore.Migrations[20405]
      No migrations were applied. The database is already up to date.
To undo this action, use Remove-Migration.
PM> 

Microsoft Azure: Services Still Down, What’s Going On?

I woke up today to check one of my websites hosted on Microsoft Azure to see a blank page staring at me. I did some preliminary check to make sure I did not break the site over night. Then, I turned to Twitter to see if there’s anything trending about Azure, of course there I found all production services and websites hosted on Azure in the South Central US were down. I tried to access the Azure portal that did not work either, so I could try out anything to remedy the problem.

Below are the updates on the progress for the issue:

Microsoft Azure – Impacted service(s)

Network Infrastructure; Azure Active Directory; SQL Database; Storage; App Service
Impacted region(s)
South Central US; Global
Last update (59 min ago)
CUSTOMER IMPACT: There are currently three identified impact workstreams:

1) Customers with resources in South Central US may experience difficulties connecting to resources hosted in this region. A complete list of impacted services can be found below.
2) Customers using non-regional services, such as Azure Active Directory, may experience intermittent authentication failures in any region.
3) Customers may encounter errors when provisioning new subscriptions.

PRELIMINARY ROOT CAUSE:

1) A severe weather event, including lightning strikes, occurred near one of the South Central US datacenters. This resulted in a power voltage increase that impacted cooling systems. Automated datacenter procedures to ensure data and hardware integrity went into effect and critical hardware entered a structured power down process.
2) As a result, non-regional services, such as Azure Active Directory, encountered an operational threshold for processing requests through the South Central US datacenter. Initial attempts to fail over into other datacenters resulted in temporary traffic congestion for those regions.

ENGINEERING STATUS: Engineers continue to implement the necessary mitigation steps. They have outlined a tentative mitigation workflow:

1) Restore power to the South Central US datacenter (COMPLETED)
2) Recover software load balancers for Azure Storage scale units in South Central US (COMPLETED)
3) Recover impacted Azure Storage scale units in South Central US (In Progress)
4) Recover the remaining Storage-dependent services in South Central US (In Progress)

This mitigation workflow is tentative and subject to change as events develop.

NEXT UPDATE: The next update will be provided by 02:00 UTC 05 Sep 2018 or as events warrant.

Last, I thought I’d share this tweet sent by someone who is also affected by this outage.