Seed Your Entity Framework Core Data at Startup with ASP.NET Core 2

If you’re developing large scale database designs using Entity Framework, especially with Code First Migrations, you’ve likely wanted to seed some data. Perhaps it’s some constant lookup values or test data used in your local dev environments for on-boarding new team members. It’s also nice to run migrations on startup for when you are deploying to different environments!

This blog post is just a simple set of tools I commonly use to allow for automatically running migrations and seeding some data with some examples.

Basically we’ll:

  • Design a Code First Database with EF Core
  • Add a migration
  • Build two different Seeder classes
  • Build an extension method to run Migrations and the Seeders when the application starts

This doesn’t care about how you actually setup your DbContext within your app, what database provider you use, etc.

Database Design

Let’s go with a simple example of a Blog website database design. Let’s first add some POCOs for out entities then create our DbContext.

Post.cs

public class Post
{
    public long Id { get; set; }
    public string Title { get; set;}
    public string Content { get; set; }
    public string PostTypeId { get; set; }
    public virtual PostType PostType { get; set; }
}

PostType.cs

public class PostType
{
    public long Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection Posts { get; set; }
}

BlogContext.cs

public class BlogContext : DbContext
{
    public DbSet Posts { get; set; }
    public DbSet PostTypes { get; set; }
}

Add Migration

Now that we have a DbContext and our tables, let’s create our migration!

In the Visual Studio Package Manager Console:

add-migration InitialCreate

or in the CLI:

dotnet ef migrations add InitialCreate

Building Seeder Classes

Now we have a database designed and a migration, so let’s create a seeder for creating some PostTypes that should be the same for every environment and then another TestDataSeeder to seed some examples for developers to use when running the app for the first time.

PostTypesSeeder

public class PostTypesSeeder
{
    private readonly BlogContext _context;
    public PostTypesSeeder(BlogContext context)
    {
        _context = context;
    }

    public void SeedData()
    {
        AddNewType(new PostType { Id = 0, Name = "Standard" });
        AddNewType(new PostType { Id = 1, Name = "Aside" });
        AddNewType(new PostType { Id = 2, Name = "Snippet" });
        _context.SaveChanges();
    }

    // since we run this seeder when the app starts
    // we should avoid adding duplicates, so check first
    // then add
    private void AddNewType(PostType postType)
    {
        var existingType = _context.PostTypes.FirstOrDefault(p => p.Name == postType.Name);
        if(existingType == null)
        {
            _context.PostTypes.Add(postType);
        }
    }
}

This seeder let’s us add 3 different PostTypes if they don’t already exist.

TestDataSeeder.cs

public class TestDataSeeder
{
    private readonly BlogContext _context;
    public TestDataSeeder(BlogContext context)
    {
        _context = context;
    }

    public void SeedData()
    {
        _context.Posts.Add(new Post
        {
            Name = "Test Post 1",
            Content = "This is my standard post for testing",
            PostTypeId = 0
        };
        _context.Posts.Add(new Post
        {
            Name = "Test Post 2",
            Content = "This is my aside post for testing",
            PostTypeId = 2
        };

        _context.SaveChanges();
    }
}

Building the WebHost Extension

Now that we have our seeders. Let’s build that extension method for running the migration and running this seeders.

WebHostExtensions.cs

public static class WebHostExtensions
{
    public static IWebHost SeedData(this IWebHost host)
    {
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var context = services.GetService();

            // now we have the DbContext. Run migrations
            context.Database.Migrate();

            // now that the database is up to date. Let's seed
            new PostTypesSeeder(context).SeedData();

#if DEBUG
            // if we are debugging, then let's run the test data seeder
            // alternatively, check against the environment to run this seeder
            new TestDataSeeder(context).SeedData();
#endif
        }

        return host;
    }
}

Implementing the Extension

Now that we have our database and entities, seeders, and an extension method – let’s just drop it in our Program class to run when we are creating the WebHost!

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().SeedData().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup();

}

Note: although this Program is in the ASP.NET Core 2.1 style, the same code works in the original 2.0 style. Just stick it after the Build() call wherever you run that.

And that’s it! Now we have always-up-to-date data whenever we run our ASP.NET Core app! 😀


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisement

Alexa.Tip – Build Intent Handlers in .NET

In this Alexa.Tip series, we explore some little bits of code that can make your life easier in developing Alexa Skills in many languages including C# + .NET, node.jS + TypeScript, Kotlin, etc. We look at concepts that developers might not be aware of, design patterns that and how they can be applied to voice application development, best practices, and more!

In this post, we explore some more best practices in developing Alexa Skills in C# whether you are using an ASP.NET Core API or an AWS Lambda. This time, we talk about abstracting our business logic out of either our Function or Controller and into separate Handler classes.

If you’ve done skill development in node.js or in .NET, you’ve probably noticed that a lot of docs, example apps, and real world apps are written with one BIG class or file. That’s pretty gross.

You may some C# examples look like this:

UglyFunction.cs

public class Function
{
    public async Task<SkillResponse> HandleRequest(SkillRequest input)
    {
        if(input.GetRequestType() == typeof(LaunchRequest))
        {
            return ResponseBuilder.Ask("Welcome to my skill written in one big function class with all my business logic in one place and no real testability! Ask me anything!", null);
        }

        if(input.GetRequestType() == typeof(IntentRequest))
        {
            var intentRequest = input.Request as IntentRequest;

            switch(intentRequest.Intent.Name)
            {
                case "MyIntent1":
                    // get slot values
                    // search database
                    // validate data
                    // build response 
                    // add card if it supports a screen
                    // return
                    break;
                case "Intent2":
                    // get slot values
                    // search third party api
                    // validate data
                    // build response 
                    // add card if it supports a screen
                    // return
                    break;
                case "Intent3":
                    // get slot values
                    // search database
                    // validate data
                    // build response 
                    // add card if it supports a screen
                    // return
                    break;
                case "Intent4":
                    // get slot values
                    // search third party api
                    // validate data
                    // build response 
                    // add card if it supports a screen
                    // return
                    break;
                case "Intent5":
                    // get slot values
                    // search database
                    // validate data
                    // build response 
                    // add card if it supports a screen
                    // return
                    break;

                // I think you get my point here...
            }
        }

        return ResponseBuilder.Tell("Something went wrong. Please try again later");
    }
}

So that’s pretty gross right? It’s untestable, difficult to update, and hard to read! But hey, we’re C# developers. So let’s build Alexa Skills like C# developers.

The proposal here is to abstract your intent logic into Handler classes. Then you can inject those either into your Function or your Controller if you’re using a RESTful API.

Here’s something that I hope can get you started:
– A generic IIntentHandler
– An inherited specific IIntentWhateverHandler
– An implementation of the IIntentWhateverHandler
– A testable and injectable version to be used in the function.

Let’s start.

IIntentHandler.cs

public interface IIntentHandler
{
    Task<SkillResponse> HandleIntent(IntentRequest input);
}

Now let’s get specific. In this simple case, this interface is empty but exists for registration – although you can add specific methods here as needed.

IMyIntentHandler.cs

public interface IMyIntentHandler : IIntentHandler
{
}

Now let’s create an example implementation of an intent handler that houses the business logic of the request.

MyIntentHandler.cs

public class MyIntentHandler : IMyIntentHandler
{
    private readonly MyDbContext _context;
    public MyIntentHandler(MyDbContext context)
    {
        // oh snap, we can inject db context
        _context = context;
    }

    public async Task<SkillResponse> HandleIntent(IntentRequest input)
    {
        var mySlot = input.Slots["MySlot"].Value; // assumes the slot is there from it being required in the interaction model
        var myMessage = await _context.Messages.FirstOrDefaultAsync(m => m.SomeValue == mySlot)

        if(myMessage == null)
        {
            return ResponseBuilder.Ask("I don't know that one. Try something else.");
        }

        return ResponseBuilder.Tell(myMessage.Content);
    }
}

Now let’s go about adding these handlers to our Function (the same thing can apply to our Controllers.

PrettyFunction.cs

public class Function
{
    private readonly IMyIntentHandler _myIntentHandler;

    private void Setup()
    {
        _myIntentHandler = new MyIntentHandler(...);
        // create the others - optionally implement a ServiceCollection
        // to handle proper dependency injection
    }
    public async Task<SkillResponse> HandleRequest(SkillRequest input)
    {
        if(input.GetRequestType() == typeof(LaunchRequest))
        {
            return ResponseBuilder.Ask("Welcome to my skill written in one big function class with all my business logic in one place and no real testability! Ask me anything!", null);
        }

        if(input.GetRequestType() == typeof(IntentRequest))
        {
            var intentRequest = input.Request as IntentRequest;

            switch(intentRequest.Intent.Name)
            {
                case "MyIntent1":
                    return await _myIntentHandler.HandleIntent(intentRequest);
                    break;
            }
        }

        return ResponseBuilder.Tell("Something went wrong. Please try again later");
    }
}

So now you can separately test your Handler classes, your Data classes, and your Function as a whole.

SO much better 🙂

Conclusion

We don’t have to follow how Amazon writes their node.js skills when we write them in C# – let’s use some proper OO design and testability to build some scalable and awesome skills!

In the next post, we’ll talk about taking this one step closer to avoid that gross switch statement and simply register our Handler implementations for certain intents or RequestTypes which is more similar to how the actual ASK SDK works.

Stay tuned!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile and AI developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.


voicify_logo
I’m the Director and Principal Architect over at Voicify. Learn how you can use the Voice Experience Platform to bring your brand into the world of voice on Alexa, Google Assistant, Cortana, chat bots, and more: https://voicify.com/


Adding a File Upload Field to Your Swagger UI With Swashbuckle

If you’re building ASP.NET Core Web APIs, then I hope you’ve heard of Swashbuckle – the tool to generate the Swagger UI automatically for all of your controllers to make manual testing your endpoints visual and simple.

Out of the box, the documentation helps you set up your UI, handle different ways to authenticate (which we will touch on in a later post), and have it all hooked up to your controllers. However, this only handles the most common cases of required requests with query string parameters and HTTP Body content.

In this post, we’ll look at a quick and easy way to also add File upload fields for your API endpoints that consume IFormFile properties to make testing file uploading even easier.

Basic Swagger Setup

First thing’s first, install that puppy:

Package Manager : Install-Package Swashbuckle.AspNetCore
CLI : dotnet add package Swashbuckle.AspNetCore

Let’s first look at a simple swagger setup as our baseline before we add everything for our HTTP Header Field.

Startup.cs

//...
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new Info { Title = "My API", Version = "V1" });
    });
    // ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
    app.UseMvc();

    app.UseSwagger();
    app.UseSwaggerUI(config =>
    {
        config.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
    });
    // ...
}
//...

This setup gives us all we need for our basic UI and wireup to our controllers!
Running this gives us our basic swagger at /swagger:
Swagger no header

Adding a File Upload Field

What we have to do now is add an OperationFilter to our swagger generation. These OperationFilters can do a whole lot and enable us to customize the swagger document created which is what drives the fields and info on the UI.

Let’s start by creating our FormFileSwaggerFilter class.

FormFileSwaggerFilter.cs

/// <summary>
/// Filter to enable handling file upload in swagger
/// </summary>
public class FormFileSwaggerFilter : IOperationFilter
{
    private const string formDataMimeType = "multipart/form-data";
    private static readonly string[] formFilePropertyNames =
        typeof(IFormFile).GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToArray();

    public void Apply(Operation operation, OperationFilterContext context)
    {
        var parameters = operation.Parameters;
        if (parameters == null || parameters.Count == 0) return;

        var formFileParameterNames = new List<string>();
        var formFileSubParameterNames = new List<string>();

        foreach (var actionParameter in context.ApiDescription.ActionDescriptor.Parameters)
        {
            var properties =
                actionParameter.ParameterType.GetProperties()
                    .Where(p => p.PropertyType == typeof(IFormFile))
                    .Select(p => p.Name)
                    .ToArray();

            if (properties.Length != 0)
            {
                formFileParameterNames.AddRange(properties);
                formFileSubParameterNames.AddRange(properties);
                continue;
            }

            if (actionParameter.ParameterType != typeof(IFormFile)) continue;
            formFileParameterNames.Add(actionParameter.Name);
        }

        if (!formFileParameterNames.Any()) return;

        var consumes = operation.Consumes;
        consumes.Clear();
        consumes.Add(formDataMimeType);

        foreach (var parameter in parameters.ToArray())
        {
            if (!(parameter is NonBodyParameter) || parameter.In != "formData") continue;

            if (formFileSubParameterNames.Any(p => parameter.Name.StartsWith(p + "."))
                || formFilePropertyNames.Contains(parameter.Name))
                parameters.Remove(parameter);
        }

        foreach (var formFileParameter in formFileParameterNames)
        {
            parameters.Add(new NonBodyParameter()
            {
                Name = formFileParameter,
                Type = "file",
                In = "formData"
            });
        }
    }
}

This operation filter takes the operation parameters, then uses reflection to find the type of the field. If the field is an IFormFile, then we add a new file field from the formData section to our parameters. This in turn will update our swagger definition json file, and when rendered adds the field to our UI.

This even works great with endpoints that take a separate HTTP Body, query parameters, and files!

Now we need to reference it in our Startup when we initialize swagger:

Startup.cs

//...
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new Info { Title = "My API", Version = "V1" });

        config.OperationFilter<FormFileSwaggerFilter>();
    });
    // ...
}

Here’s an example controller with an endpoint that uses the file upload:

FileUploadController

[Route("api/[controller]")]
public class FileUploadController : Controller
{
    [HttpPost]
    public async Task<IActionResult> CreateMediaItem(string name, [FromForm]IFormFile file)
    {
        // Do something with the file
        return Ok();
    }
}

This controller ends up rendering in our Swagger UI as:
Fileupload_swagger

And using this, we can now submit our request with an uploaded file and all our other parameters!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Adding a Required HTTP Header to Your Swagger UI With Swashbuckle

If you’re building ASP.NET Core Web APIs, then I hope you’ve heard of Swashbuckle – the tool to generate the Swagger UI automatically for all of your controllers to make manual testing your endpoints visual and simple.

Out of the box, the documentation helps you set up your UI, handle different ways to authenticate (which we will touch on in a later post), and have it all hooked up to your controllers. However, this only handles the most common cases of required requests with query string parameters and HTTP Body content.

In this post, we’ll look at a quick and easy way to also add fields for your custom HTTP Request Headers so you can fill them out while testing without having to do some funky stuff in the console.

Basic Swagger Setup

First thing’s first, install that puppy:

Package Manager : Install-Package Swashbuckle.AspNetCore
CLI : dotnet add package Swashbuckle.AspNetCore

Let’s first look at a simple swagger setup as our baseline before we add everything for our HTTP Header Field.

Startup.cs

//...
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new Info { Title = "My API", Version = "V1" });
    });
    // ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
    app.UseMvc();

    app.UseSwagger();
    app.UseSwaggerUI(config =>
    {
        config.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
    });
    // ...
}
//...

This setup gives us all we need for our basic UI and wireup to our controllers!
Running this gives us our basic swagger at /swagger:
Swagger no header

Adding Custom Headers

What we have to do now is add an OperationFilter to our swagger generation. These OperationFilters can do a whole lot and enable us to customize the swagger document created which is what drives the fields and info on the UI.

Let’s create a MyHeaderFilter and then add it to the AddSwaggerGen call.

MyHeaderFilter.cs

/// <summary>
/// Operation filter to add the requirement of the custom header
/// </summary>
public class MyHeaderFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            operation.Parameters = new List<IParameter>();

        operation.Parameters.Add(new NonBodyParameter
        {
            Name = "MY-HEADER",
            In = "header",
            Type = "string",
            Required = true // set to false if this is optional
        });
    }
}

And now we need to update our Startup class:

Startup.cs

//...
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new Info { Title = "My API", Version = "V1" });

        config.OperationFilter<MyHeaderFilter>();
    });
    // ...
}

Now when we run and navigate to our /swagger url, we can see:
Swagger with header

When we fill out that field, we can now pull the value off the request header in our controller!

ContentController.cs

[Route("api/[controller]")]
public class ContentController : Controller
{
    public void Search([FromBody]InputModel model)
    {
        Console.WriteLine(Request.Headers["MY-HEADER"]);        
    }
}

In further posts, we’ll talk about adding Bearer Authentication, XML Comments, and More 🙂


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Add Model Validation to Your ASP.NET Core Web API

If you’re used to creating traditional Web APIs in ASP.NET, you’ve probably become accustom to using System.ComponentModel.DataAnnotations such as the [Required] or [StringLength] data attributes. Using these in your models that are parameters to your API project would return the proper 400 response code when the input didn’t match the requirement.

In ASP.NET Core 2.0, this is no longer built in right out of the box, but setting it up is super easy! So if you don’t want to abstract your model validation in your business logic layer and want to get it out of the way right away when the request comes in, check this out.

There are only two steps to doing this:

  • Create an implementation of `IActionFilter`
  • Register this Filter class in your startup

Let’s start by creating a ValidatorActionFilter class:

ValidatorActionFilter.cs

/// <summary>
/// Filter for returning a result if the given model to a controller does not pass validation
/// </summary>
public class ValidatorActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.ModelState.IsValid)
        {
            filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }
}

What this does is check the current HttpContext.ModelState to make sure it is valid. This allows us to ensure we don’t have to make this check in each endpoint. Note, we don’t have to add anything in the OnActionExecuted method since this filter is used exclusively before the action is called.

In the OnActionExecuting call, if the model state is NOT valid, we need to return the 400 – Bad Request response as the result.

Now, let’s register this in our startup. We do this by applying it in the ConfigureServices call and specifically in the options of the AddMvc call:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ValidatorActionFilter));
    });
}

And that’s it! So now your endpoints will return the proper response such as:

MyInputModel.cs

public class MyInputModel
{
    [Required]
    public string SomeRequiredValue { get; set; }
    public string SomeNotRequiredValue { get; set; }
}

MyController.cs

public class MyController : Controller
{
    public ActionResult DoSomeAction([FromBody]MyInputModel input)
    {
         return Ok("You did it"!)
    }
}

The request of:

{
    "someNotRequiredValue": "Hey"
}

Will return 400 - Bad Request - "The SomeRequiredValue field is required"

And the request of:

{
    "someRequiredValue": "Yo"
    "someNotRequiredValue": "Hey"
}

Will return 200 - Ok - "You did it!"

So go forth and validate those input models with ease!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.