Category Archives: Asp.Net Core 2

Creating a Basic Web Site from an Asp.Net Core Empty Project

I recently wanted to do a very quick proof of concept, regarding the use of setInterval versus setTimeout after reading that setTimeout was referable if you were calling the same function very rapidly. I thought I’d note down my journey from File -> New Project to having the POC running so that next time, I don’t have to re-lookup the various parts.

File -> New Project

If you create a brand new Asp.Net Core 2.1 project, select empty project, and then run the generated code, you’ll see this:

This is generated by a line in Startup.cs:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

The target here is to get to a situation where the blank app is serving an HTML page with some attached Javascript as fast as possible. Here, I’ve got exactly three steps.

Step 1 – Create the HTML File

The application can only serve static files (HTML is considered a static file) from the wwwroot folder. The internal structure of this folder doesn’t matter, but that’s where your file must go:

The contents of this file are as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p>test</p>
</body>
</html>

This won’t actually do anything yet, because by default, Asp.Net Core does not serve static files, nor does it know the enormous significance of naming something “Index”.

Step 2 – Configure Asp.Net

Startup.cs is where all the magic happens; this is what it looks like out of the box:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        
    }
 
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
 
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

The `context.Response.WriteAsync` goes, and instead we tell Asp.Net Core to serve static files, and the call to `UseDefaultFiles` means that it will search for Index or Default files. It’s also worth pointing out that the order of these matters:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
            
    app.UseDefaultFiles();
    app.UseStaticFiles();                                    
}

Now it loads the Index.html. So technically it was only two steps – although we haven’t referenced any Javascript yet.

Step 3 – Adding the javascript… and let’s do something funky

Change the HTML to give the paragraph an ID and an absolute position. Also, reference the file site.js:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="site.js"></script>
</head>
<body>
    <p id="testElement" style="position:absolute">test</p>
</body>
</html>

Obviously, without adding site.js, nothing will happen (it also needs to be in wwwroot):

The Javascript code for that new file is here:

var divxPos = 0;
 
window.onload = function () {
    runCode();
};
 
function runCode() {
    var test = document.getElementById("testElement");    
    test.style.left = divxPos++ + 'px';    
 
    setTimeout(() => runCode(), 50);
};

If you run it, you’ll find the text running away with itself!

.Net Client Side Libraries

In this post, I introduced (to me) a new method of installing client side Javascript libraries for a .Net Web Application.

In this follow-up, I’m going to cover how this can be used in conjunction with npm in order to simply move the files into the correct location. Note that this is a new tool in Visual Studio, and you’ll need VS 15.8.0 or higher for it to work. Let’s start by creating an empty .Net Core Web App. Once you’ve done so, you’re app probably looks like this:

Now you’ll need to launch a bash or powershell console:

npm init
npm install jquery

Refresh your project and show all files:

As you can see, you now have a node_modules directory. The problem is that the files need to be under wwwroot. Obviously, you could copy it, but let’s try the client side manager:

In the resultant dialog, select File System; navigate to the JQuery directory and select the files that you want:

Now refresh the project again and let’s see what we have:

This actually translates to a JSON file; libman.json looks like this:

{
  "version": "1.0",
  "defaultProvider": "filesystem",
  "libraries": [
    {
      "library": "node_modules\\jquery\\dist\\",
      "destination": "wwwroot/lib/dist/",
      "files": [
        "jquery.min.js"
      ]
    }
  ]
}

Abusing the system

Okay – so that’s very nice; but now that we have a system that will copy files from wherever into wherever (the rule is that you have to go deeper in the files structure – so you couldn’t copy that file back again) then we, presumably, could use this for other things. For example, have you ever had a file (an image or something) that you need to include in your project:

Obviously, c:\tmp above could just as easily be \\shareddrive\images.

To be clear, I’m unsure whether this is abusing the system, or it was meant for this exact thing. It is possible that this type of usage may become unsupported in future (so you’ve been warned).

Adding ReactJS to an existing Asp.Net Core 2 Application

I’ve recently been playing around with writing an Asp.Net Core 2 app from scratch. If you’re interested, you can view my exploits here.

I came across an interesting issue, which was that I wanted to search an in memory set of data, and I wanted the screen to update as I searched. React sounds like the perfect tool for this; and this article describes how to integrate a React view (JSX file) into an MVC view.

(Note that it doesn’t cover implementing the search function – that will be the subject of a later post when and if I work out how to do it.)

Set-up

After you’ve created your Asp.Net Core 2 application, the first step is to install React; which is a NuGet package:

Install-Package React.AspNet -Source nuget.org

There are some code tweaks that are needed; the first is in startup.cs (which basically tells Asp to use React, and how to do so):

services.AddTransient< …
 
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddReact();
 
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
app.UseReact(config =>
{
    
});
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

You’ll need to slightly change the signature of ConfigureServices, too:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
. . . 
    return services.BuildServiceProvider();
}

The next thing is to make React available to your views; in ViewImports.cshtml:

@using UsefulSites.Web
@using UsefulSites.Web.Models
@using UsefulSites.Web.ViewModels
@using React.AspNet
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

React Code

Next step is to create the ReactJs file:

class SearchBox extends React.Component {
    render() {
        return (
            <div className="search-container">
                <textarea>
                    Search Text
                </textarea>    
            </div>
        );
    }
}
 
ReactDOM.render(
    <SearchBox />,
    document.getElementById('content')
);

Then change the HTML file:

<div class="row">
    <div class="jumbotron">
        <div id="content"></div>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.development.js"></script>
        <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.development.js"></script>
        <script src="@Url.Content("~/js/search.jsx")"></script>
    </div>

As you can see, the React script references the div named “content” specifically.

References

https://reactjs.net/getting-started/aspnetcore.html

https://reactjs.net/getting-started/download.html

Separating Data Access in Asp.Net Core 2

In Asp.Net Core 2, like in previous incarnations of Asp.Net there is a wizard that gives you a head-start with a a simple user log-in / registration system:

If you set-up a new project using the wizard to create an individual user account, you may notice in the generated project, the lack of seemingly any code to achieve this. The reason being that all the code for the identity system is tucked away inside the razor pages. I see this as mainly a good thing, but with one exception*: I don’t like having the DB access code inside the main web project; it makes DI very difficult. So this is the story of how you can extricate the DB Access portion of this into a separate project.

Context

The crux of this is to move the context into a separate project; so let’s start with a new project:

If you just want the identity access, then you’ll only need to move the
ApplicationIdentityDbContext, however, in real life, you’re probably going to end up with two contexts:

The contexts themselves need to be separate because the identity context inherits from IdentityDbContext**:

public class ApplicationIdentityDbContext : IdentityDbContext
{
    
    public ApplicationIdentityDbContext(DbContextOptions<ApplicationIdentityDbContext> options)
        : base(options)
    {
    }
}

Your second context should just inherit from DbContext.

NuGet

There’s a couple of gotcha’s with this; but the libraries that you need in the DataAccess project are:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.Entensions.Identity.Stores

Startup.cs

Finally, you’ll need to change the DI to register both contexts:

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireNonAlphanumeric = false;                
});
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<ApplicationIdentityDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
 
services                
    .AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationIdentityDbContext>();

I’m using SqlServer here, so if you’re not then you’ll obviously need to change the bits around that. You’ll notice that I switched the requirement to have your password have a non-alphanumeric character – especially for development, this can be annoying. I also don’t necessarily accept that it increases security for the site***.

Migrations

Now that you have multiple contexts, when you add a migration, you’ll need to specify the context to use; for example:

Add-Migration "InitialUserSetup" -context ApplicationIdentityDbContext

The same is true for Update-Database:

Update-Database -context ApplicationIdentityDbContext

Footnotes

* Okay – there may be other pitfalls; but if this works for 60% of the authentication cases, why not have it all inside a magic black box? When you need something more customised, you can always rip this out and replace it with your own.

** There’s nothing stopping you having the main DbContext inherit from IdentityDbContext, or just using IdentityDbContext as the main context.

*** Obviously, it does improve security for the site if everyone is using a 20 digit code and they start using non-alpha-numeric characters in that code; however, if they’re using a password manager, they probably are already generating such a code, and if not then you’ll just force “Password123” to “!Password123”, so you probably don’t gain much!

References

https://github.com/aspnet/EntityFrameworkCore/issues/7891

An excellent intro to Asp.Net Core 2 default structure

Asp.Net Core 2.0 – Passing data into a Model Using DI

Imagine you have an Asp.Net Core web page, and you would like to edit some data in a form, but you’d like to default that data to something (maybe initially specified in the Web.Config).

I’m sure there’s dozens of ways to achieve this; but this is one.

Let’s start with a bog standard MVC web app:

Step one is to define a model in which to hold your data; here’s mine:

public class CurrentAppData
{
    public string DataField1 { get; set; }
}

Let’s register that in the IoC container:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
 
 
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 
    services.AddTransient<CurrentAppData, CurrentAppData>(
        a => new CurrentAppData()
        {
            DataField1 = "test value"
        });

Next thing we’ll need is a View, and a corresponding view model to edit our data; here’s the view:

@model EditDataViewModel
@{
    ViewData["Title"] = "Edit Data";
}
 
<h2>@ViewData["Title"]</h2>
 
<div>
    <label>Change data here:</label>
    <input type="text" asp-for="EditData.DataField1" />
 
</div>

And now the view model (that is, the model that is bound to the view):

public class EditDataViewModel
{
    public EditDataViewModel(CurrentAppData editData)
    {
        EditData = editData;
    }
    public CurrentAppData EditData { get; set; }
}

The final step here is to adapt the controller so that the CurrentAppData object is passed through the controller:

public class EditDataController : Controller
{
    private readonly CurrentAppData _currentAppData;
 
    public EditDataController(CurrentAppData currentAppData)
    {
        _currentAppData = currentAppData;
    }
 
    public IActionResult EditData()
    {
        return View(new EditDataViewModel(_currentAppData));
 
 
    }
}

That works as far as it goes, and we now have the data displayed on the screen:

The next step is to post the edited data back to the controller; let’s change the HTML slightly:

<form asp-action="UpdateData" asp-controller="EditData" method="post" enctype="multipart/form-data">
    <label>Change data here:</label>
    <input type="text" asp-for="EditData.DataField1" />
    <br />
    <button type="submit" class="btn-default">Submit Changes</button>
</form>

We’ve added a submit button, which should cause the surrounding form element to execute whichever “method” it’s been told to (in this case, POST). It will look for an action on the controller called UpdateData, so we should create one:

public IActionResult UpdateData(EditDataViewModel editDataViewModel)
{
    System.Diagnostics.Debug.WriteLine(editDataViewModel.EditData.DataField1);
    return View("EditData", editDataViewModel);
}

Here, we’re accepting the EditDataViewModel from the view. However; when we run this, we get the following error:

Error:

InvalidOperationException: Could not create an instance of type ‘WebApplication14.Models.EditDataViewModel’. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the ‘editDataViewModel’ parameter a non-null default value.

Let’s first implement a fix for this, and then go into the whys and wherefores. The fix is actually quite straightforward; simply give the view model a parameterless constructor:

public class EditDataViewModel
{
    public EditDataViewModel()
    {
        
    }
 
    public EditDataViewModel(CurrentAppData editData)
    {
        EditData = editData;
    }
    public CurrentAppData EditData { get; set; }
}

The problem that we had here is that the `EditDataViewModel` that is returned to UpdateData is a new instance of the model. We can prove this by changing our code slightly:

Here, we’ve added a field called TestField1 to the model, and populated it just before we pass the model to the view; and on the post back, it’s gone. I’m not completely sure why the view model can’t be created by the middleware in the same way that the controller is; but that’s the subject of another post.

Finally, show the value back to the screen

To wrap up, we’ll just show the same value back to the screen; we’ll add an extra value to the model:

public class CurrentAppData
{
    public string DataField1 { get; set; }
 
    public string DisplayField1 { get; set; }
}

And we’ll just display it in the view:

<form asp-action="UpdateData" asp-controller="EditData" method="post" enctype="multipart/form-data">
    <label>Change data here:</label>
    <input type="text" asp-for="EditData.DataField1" />
    <br />
    <button type="submit" class="btn-default">Submit Changes</button>
    <br />
    <label>@Model.EditData.DisplayField1</label>
    <br />
</form>

Finally, we’ll copy that value inside the controller (obviously, this is simulating something meaningful happening), and then display the result:

public IActionResult UpdateData(EditDataViewModel editDataViewModel)
{
    editDataViewModel.EditData.DisplayField1 = editDataViewModel.EditData.DataField1;
    return View("EditData", editDataViewModel);
}

Let’s see what that looks like: