Posted on Leave a comment

Exploring Azure App Service – Web Apps and SQL Azure

There is a good chance that your web app uses a database. In my previous post introducing Azure App Service, I showed some of the benefits of hosting apps in Azure App Service, and how easy it is to get a basic site running in a few clicks. In this post I’ll show how to set up a SQL Azure database along with an App Service Web App from Visual Studio, and apply Entity Framework automatically as part of publish.

Let’s get going

To get started, you’ll first need:

  • Visual Studio 2017 with the ASP.NET and web development workload installed (download now)
  • An Azure account:
  • Any ASP.NET or ASP.NET Core app that uses a SQL Database. For the purposes of this post, I’ll create a new ASP.NET Core app with Individual Authentication:
    • On the “New ASP.NET Core Web Application” dialog, click the “Change Authentication” button.
      clip_image002
  • Then select the “Individual User Accounts” radio button and click “OK”.
  • Click OK.

I can now run my project locally (F5) and create user accounts which will be stored in a SQL Server Express Local DB on my machine.

Publishing to App Service with a Database

Let’s publish our application to Azure. To do this, I’ll right click my project in Solution Explorer and choose “Publish”

clip_image003

This brings up the Visual Studio publish target dialog, which will default to the Azure App Service pane with the “Create new” radio button selected. To continue click “Publish”.

This brings up the “Create App Service” dialog (see the “Key App Service Concepts” section of my previous post for an explanation of the fields). To create a SQL Database for our app to use, click the “Create a SQL Database” link in the top right section of the dialog.

clip_image005

This will bring up the “Configure SQL Database” dialog.

  • Note: If you are using a Visual Studio Enterprise subscription, many regions will not let you create a SQL Azure database so I recommend choosing “East US” or “West US 2” depending on where you are located (we are adding logic in in the Visual Studio 2017 15.8 update to remove those regions if that’s the case, but for now you’ll need to choose an appropriate region). To do this, click the “New…” button next to your “Hosting Plan Dropdown” and pick the appropriate region (“East US” or “West US 2”).
  • Since I don’t have an existing SQL Server, the first thing I need to do is create a server to host the database, so I’ll click the “New…” button next to the “SQL Server” dropdown,
  • Choose a location for the database.
  • Provide an administrator user name and password for the server
  • Click “OK”
    clip_image007
  • Make sure the connection string name field matches the name of the connection string your application uses to access the database (if using a new project, it is “DefaultConnection” which will be prepopulated for you).
    clip_image009
  • Click OK
  • Then click the “Create” button on the “Create App Service” dialog

It should take ~2-3 minutes to create all of the resources in Azure, then your application will publish and a browser will open to your home page.

Configuring EF Migrations

At this point there is a database for your app to use in the cloud, but EF migrations have not been applied, so any functionality that relies on the database (e.g. Registering for a user account) will result in an error.

To apply EF migrations to the database:

  • Click the “Configure…” button on the publish summary page
    clip_image011
  • Navigate to the “Settings” tab
  • When it finishes discovering data contexts, expand the “Entity Framework Migrations” section, and check the “Apply this migration on publish” for all of the contexts it finds
    clip_image013
  • Click “Save”
  • Click Publish again, in the output window you should see “Generating Entity framework SQL Scripts” and then “Generating Entity framework SQL Scripts completed successfully”
    clip_image015

That’s it, your web app and SQL Azure database are both configured and running in the cloud.

Conclusion

Hopefully, this post showed you how easy it is to try App Service and SQL Azure. We believe that for most people, App Service is the easiest place to get started with cloud development, even if you need to move to other services in the future for further capabilities (compare hosting options). As always, let us know if you run into any issues, or have any questions below or via Twitter.

Posted on Leave a comment

ASP.NET Core 2.1.0-rc1 now available

Today we’re happy to announce the first release candidate of ASP.NET Core 2.1! This release should be very close to the final stable release of ASP.NET Core 2.1 and includes primarily bug fixes and polish for the features that we shipped in earlier previews. This is a “go live” release that can be used in production with the understanding that you will need to update to the final stable release once it is available.

Also, be sure to read about .NET Core 2.1.0-rc1 and Entity Framework Core 2.1.0-rc1.

Get started

To get started with ASP.NET Core 2.1.0-rc1 download the .NET Core 2.1.0-rc1 SDK

Customers using Visual Studio should also install Visual Studio 2017 Update 7 or Visual Studio for Mac 7.5.

Migrating an ASP.NET Core 2.0.x project to 2.1.0-rc1

To migrate an existing ASP.NET Core 2.0.x project to 2.1.0-rc1:

  1. Open the project’s .csproj file and change the value of the <TargetFramework> element to netcoreapp2.1
    • Projects targeting .NET Framework rather than .NET Core, e.g. net471, don’t need to do this
  2. In the same file, update the versions of the various <PackageReference> elements for any Microsoft.AspNetCore, Microsoft.Extensions, and Microsoft.EntityFrameworkCore packages to 2.1.0-rc1-final
  3. In the same file, remove any references to <DotNetCliToolReference> elements for any Microsoft.AspNetCore, Microsoft.VisualStudio, and Microsoft.EntityFrameworkCore packages. These tools are now deprecated and are replaced by global tools.

That should be enough to get the project building and running against 2.1.0-preview2. The following steps will change your project to use new code-based idioms that are recommended in 2.1

  1. Open the Program.cs file
  2. Rename the BuildWebHost method to CreateWebHostBuilder, change its return type to IWebHostBuilder, and remove the call to .Build() in its body
  3. Update the call in Main to call the renamed CreateWebHostBuilder method like so: CreateWebHostBuilder(args).Build().Run();
  4. Open the Startup.cs file
  5. In the ConfigureServices method, change the call to add MVC services to set the compatibility version to 2.1 like so: services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  6. In the Configure method, add a call to add the HSTS middleware after the exception handler middleware: app.UseHsts();
  7. Staying in the Configure method, add a call to add the HTTPS redirection middleware before the static files middleware: app.UseHttpsRedirection();
  8. Open the project property pages (right-mouse click on project in Visual Studio Solution Explorer and select “Properties”)
  9. Open the “Debug” tab and in the IIS Express profile, check the “Enable SSL” checkbox and save the changes
  10. In you project file change any package reference to Microsoft.AspNetCore.All package to Microsoft.AspNetCore.App and add additional packages as needed to restore the your required dependency graph

Note that some projects might require more steps depending on the options selected when the project was created and modifications made to the project.

Deploying to Azure

Azure App Service will start deploying .NET Core 2.1.0-rc1 with the next week or so. In the meantime you can still deploy apps using ASP.NET Core 2.1.0-rc1 by deploying as stand-alone applications.

New features and enhancements

This release primarily contains refinements and bug fixes to the features we shipped in earlier previews, but there are a couple of new features and enhancements worth calling out. You can find a complete list of the features and enhancements in this release in the release notes.

New Razor UI Class Library template

The new Razor Class Library project template makes it easy to build reusable Razor UI class libraries. Razor class library projects are already setup with the Razor SDK to enable building Razor files (.cshtml) like MVC views and Razor Pages.

To create a new Razor class library project from the command-line:

dotnet new razorclasslib -o RazorClassLib1

You can also create Razor class library projects in Visual Studio from the “New ASP.NET Core Web Application” dialog.

Razor class library project template

Improvements to MVC test infrastructure

You can now derive from WebApplicationFactory to create a custom factory that configures the HttpClient by overriding ConfigureClient. This enables testing scenarios that requrie specific HttpClient configuration, like adding specific HTTP headers.

We also update the default environment setup by the WebApplicationFactory to be development to simplify scenarios like accessing user secrets and other development resources.

SignalR updates

  • The MessagePack protocol library for SignalR was renamed to Microsoft.AspNetCore.SignalR.Protocols.MessagePack
  • The JavaScript/TypeScript client Hub connection API changed to use the HubConnectionBuilder (similar to the C# client)
  • Sticky sessions are now required when using the WebSockets transport unless the skipNegotiation flag is set to true:

    var connection = new signalR.HubConnectionBuilder()
 .withUrl("/chat", { skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets })
 .build();
    

Summary

Thank you for trying out ASP.NET Core 2.1.0-rc1! Assuming everything goes smoothly with this release we should have a stable release of ASP.NET Core 2.1 shortly. If you have any questions or find any issues with this release please let us know by filing issues on GitHub.

Posted on Leave a comment

Exploring Azure App Service – Introduction

Have you ever needed to quickly stand up a web site, or web API app that was publicly available? Is your team or organization thinking about moving to the cloud but aren’t sure the best place to start? One of the first places you should look is Azure App Service Web Apps. In this post we’ll look at how easy it is to get started, and a quick overview of key concepts.

App Service offers the following benefits:

  • A fully managed platform, meaning Azure automatically updates the operating system and runtime as security and stability fixes are released.
  • 10 free plans to every subscriber, so it won’t cost you money or credits to try your app in Azure.
  • First class support in Visual Studio, meaning that you can go from your app running on your local machine to running in App Service in less than 2 minutes.
  • If offers deployment slots, which enable you to stage multiple versions of your app, and route varying amounts of traffic to the various versions (i.e. do A/B testing, or a ringed release model).
  • Scale up and down quickly and automatically based on load
  • For a more see Why use Web Apps?

In this blog post, I’ll provide an overview of App Service’s key features and concepts by walking through using Visual Studio to publish an ASP.NET application to Azure App Service.

Let’s get going

To get started, you’ll first need:

  • Visual Studio 2017 with the ASP.NET and web development workload installed (download now)
  • An Azure account:
  • Any ASP.NET or ASP.NET Core app, for the purposes of this post, I’ll use a basic ASP.NET Core app

To start I’ll right click my project in Solution Explorer and choose “Publish”

clip_image001

This brings up the Visual Studio publish target dialog, which will default to the Azure App Service pane. The “Create new” radio button is already selected to, so I’ll click the “Publish” button on the bottom right.

This will open the Create App Service dialog in Visual Studio.

Key App Service Concepts

The dialog has four fields that represent key concepts of creating an App Service:

  1. App Name: Will be the default public facing URL in Azure (it will be of the form https://<App_Name>.azurewebsites.net –you can configure domain names later if needed).
  2. Subscription: The Azure Subscription to create the resources in if you have more than one
  3. Resource Group: Groups your application and any dependent resources (SQL Databases, Storage Accounts, etc., see resource group design to learn more). To edit the name, click “New…”.
  4. Hosting Plan: The hosting plan is a set of reserved resources for your app. You can choose to host multiple apps in a single hosting plan (we’ll explore this further in a minute).

clip_image003

One concept that can be confusing is the relationship between the “Hosting Plan” (or App Service plan”) and the “App Service”:

  • The Hosting/App Service plan is the virtual machine resources you are reserving in Azure to host your application. This is what you are paying or using credits for.
  • The App Service is your app and associated settings that run inside of the plan. You can run multiple apps (App Services) in the same plan (virtual machine) with the same implications as sharing any other server or VM between apps.

To explore the App Service plan further, click the “New…” button next to the Hosting Plan dropdown to open the “Configure Hosting Plan” dialog that has three fields:

  1. App Service Plan: A non-public facing name for the plan.
  2. Location: Is the region your app will run in. You generally want to pick a region that is close to customers that will be accessing the site.
  3. Size: The size of the virtual machine you want to reserve for your application and the capabilities you want (e.g. deployment slots require a Standard or Premium plan).
    Note: Free and Shared plans run in the same VM as other App Service apps and are intended for development and testing, see App Service plan overview for more details

Publishing the app

At this point I’m ready to publish my app to App Service. The bottom right panel of the Create App Service dialog will show me all the resources I’m going to create in Azure (in this case a Hosting Plan and App Service). Everything looks good, so I just need to click “Create”:

clip_image005

Visual Studio will create all the resources on my behalf, publish my application, and open my default browser to the URL of the published application.

Conclusion

Hopefully, this overview of App Service concepts has been helpful and inspired you to give App Service a try. We believe that for many people, App Service is the easiest place to get started with cloud development, even if you need to move to other services in the future for further capabilities (compare hosting options to see additional choices). As always, let us know if you run into any issues, or have any questions below or via Twitter.  If you’re interested in exploring more, see the next post in our series introducing how to setup and use SQL Server with App Service

Posted on Leave a comment

Blazor 0.3.0 experimental release now available

Blazor 0.3.0 is now available! This release includes important bug fixes and many new feature enhancements.

New features in this release (details below):

  • Project templates updated to use Bootstrap 4
  • Async event handlers
  • New component lifecycle events: OnAfterRender / OnAfterRenderAsync
  • Component and element refs
  • Better encapsulation of component parameters
  • Simplified layouts

A full list of the changes in this release can be found in the Blazor 0.3.0 release notes.

Get Blazor 0.3.0

To get setup with Blazor 0.3.0:

  1. Install the .NET Core 2.1 SDK (2.1.300-preview2-008533 or later).
  2. Install Visual Studio 2017 (15.7 Preview 5 or later) with the ASP.NET and web development workload selected.
  3. Install the latest Blazor Language Services extension from the Visual Studio Marketplace.

To install the Blazor templates on the command-line:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates

You can find getting started instructions, docs, and tutorials for Blazor at https://blazor.net.

Upgrade an existing project to Blazor 0.3.0

To upgrade an existing Blazor project from 0.2.0 to 0.3.0:

  • Install all of the required bits listed above.
  • Update your Blazor package and .NET CLI tool references to 0.3.0.
  • Remove any package reference to Microsoft.AspNetCore.Razor.Design as it is now a transitive dependency.
  • Update the C# language version to be 7.3. You may need to restart Visual Studio for this change to take effect.
  • Update component parameters to not be public and to add the [Parameter] attribute.
  • Update layouts to inherit from BlazorLayoutComponent and remove the implementation of ILayoutComponent including the Body property.

Your upgraded Blazor project file should look like this:

<Project Sdk="Microsoft.NET.Sdk.Web">

 <PropertyGroup>
 <TargetFramework>netstandard2.0</TargetFramework>
 <RunCommand>dotnet</RunCommand>
 <RunArguments>blazor serve</RunArguments>
 <LangVersion>7.3</LangVersion>
 </PropertyGroup>

 <ItemGroup>
 <PackageReference Include="Microsoft.AspNetCore.Blazor.Browser" Version="0.3.0" />
 <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.3.0" />
 <DotNetCliToolReference Include="Microsoft.AspNetCore.Blazor.Cli" Version="0.3.0" />
 </ItemGroup>

</Project>

Project templates updated to use Bootstrap 4

The Blazor project templates have been updated to use Bootstrap 4. Bootstrap 4 includes lots of new features including an improved grid system based on flexbox, an improved reset file, new components, better tooltip support, better forms styling, built-in spacing utilities, and much more.

The new Bootstrap 4 styles also give the Blazor templates a fresh look:

Blazor Boostrap 4 template

Async event handlers

Event handlers can now be asynchronous and return a Task that gets managed by the runtime. Once the task is completed the component is rendered without the need to manually invoke StateHasChanged. Any exceptions that occur during the asynchronous execution of the event handler will be correctly handled and reported.

For example, we can update the FetchData.cshtml page to have an Update button that when selected asynchronously updates the weather forecast data by making HttpClient calls to the backend web API:

<button class="btn btn-primary" onclick="@UpdateForecasts">Update</button>

...

@functions {
 WeatherForecast[] forecasts;

 protected override Task OnInitAsync()
 {
 return UpdateForecasts();
 }

 async Task UpdateForecasts()
 {
 forecasts = await Http.GetJsonAsync<WeatherForecast[]>("/api/SampleData/WeatherForecasts");
 }
}

More strongly-typed events

This release adds strongly typed events for the most of the commonly used browser events, including mouse and focus events. You can now handle most events from your components.

You can see a full list of the events now supported in here.

<h1 class="display-1" onmouseover="@OnMouseOver" onmouseout="@OnMouseOut">@inOrOut</h1>

@functions {
 string inOrOut = "OUT";

 void OnMouseOver()
 {
 inOrOut = "IN!";
 }

 void OnMouseOut()
 {
 inOrOut = "OUT";
 }
}

Mouse events tooling screen shot

Most of the event arguments don’t yet capture and surface the data from the events. That’s something that we expect to handle in a future release. We welcome community contributions to help out with this effort.

Capturing references to DOM elements

Blazor components typically interact with the DOM through their rendering logic in markup. There are cases, however, when a parent component needs to modify or interact with DOM elements directly. Example scenarios including setting element focus or integrating with existing UI libraries that require references to elements for initialization. This release adds support for capturing DOM elements from components and using them when interacting with JavaScript.

To capture an element reference from a component attribute the element markup with a ref attribute that points to a component field of type ElementRef.

<input ref="username" />

@functions {
 ElementRef username;
}

ElementRef is an opaque handle. The only thing you can do with it is pass it through to JavaScript code, which receives the element as an HTMLElement that can be used with normal DOM APIs.

Note that the ElementRef field (username in the previous example) will uninitialized until after the component has been rendered. If you pass an uninitialized ElementRef to JavaScript code, the JavaScript code will receive null.

Let’s create a API that lets us set the focus on an element. We could define this API in our app, but to make it reusable let’s put it in a library.

  1. Create a new Blazor class library

     dotnet new blazorlib -o BlazorFocus
    
  2. Update content/exampleJsInterop.js to register a JavaScript method that sets the focus on a specified element.

     Blazor.registerFunction('BlazorFocus.FocusElement', function (element) {
 element.focus();
 });
    
  3. Add a ElementRefExtensions class to the library that defines a Focus extension method for ElementRef.

     using System;
 using Microsoft.AspNetCore.Blazor;
 using Microsoft.AspNetCore.Blazor.Browser.Interop;
    
 namespace BlazorFocus
 {
 public static class ElementRefExtensions
 {
 public static void Focus(this ElementRef elementRef)
 {
 RegisteredFunction.Invoke<object>("BlazorFocus.FocusElement", elementRef);
 }
 }
 }
    
  4. Create a new Blazor app and reference the BlazorFocus library

     dotnet new blazor -o BlazorApp1
     dotnet add BlazorApp1 reference BlazorFocus
    
  5. Update Pages/Index.cshtml to add a button and a text input. Capture a reference to the text input by adding a ref attribute that points to a field of type ElementRef with the same name. Add an onclick handler to the first button that sets the focus on the second button using the captured reference and the Focus extension method we defined previously.

     @using BlazorFocus
    
 ...
    
 <button onclick="@SetFocus">Set focus</button>
 <input ref="input1" />
    
 @functions {
 ElementRef input1;
    
 void SetFocus()
 {
 input1.Focus();
 }
 }
    
  6. Run the app and try out behavior

     dotnet run BlazorApp1
    

    Set focus

Capturing reference to components

You can also capture references to other components. This is useful when you want a parent component to be able to issue commands to child components such as Show or Reset.

To capture a component reference attribute the component with a ref attributes that points to a field of the matching component type.

<MyLoginDialog ref="loginDialog"/>

@functions {
 MyLoginDialog loginDialog;

 void OnSomething()
 {
 loginDialog.Show();
 }
}

Note that component references should not be used as a way of mutating the state of child components. Instead, always use normal declarative parameters to pass data to child components. This will allow child components to re-render at the correct times automatically.

OnAfterRender / OnAfterRenderAsync

To capture element and component references the component must already be rendered. Components now have a new life-cycle event that fires after the component has finished rendering: OnAfterRender / OnAfterRenderAsync. When this event fires element and component references have already been populated. This makes it possible to perform additional initialization steps using the rendered content, such as activating third-party JavaScript libraries that operate on the rendered DOM elements.

For example, we can use OnAfterRender to set the focus on a specific element when a component first renders.

The example below shows how you can receive the OnAfterRender event in your component.

<input ref="input1" placeholder="Focus on me first!" />
<button>Click me</button>

@functions {
 ElementRef input1;
 bool isFirstRender = true;

 protected override void OnAfterRender()
 {
 if (isFirstRender)
 {
 isFirstRender = false;
 input1.Focus();
 }
 }
}

Note that OnAfterRender / OnAfterRenderAsync is called after each render, not just the initial one, so the component has to keep try of whether this is the first render or not.

Better encapsulation of component parameters

In this release we’ve made some changes to the programming model for component parameters. These changes are intended to improve the encapsulation of the parameter values and discourage improper mutation of component state (e.g. using component references).

Component parameters are now defined by properties on the component type that have been attributed with [Parameter]. Parameters that are set by the Blazor runtime (e.g. ChildContent properties, route parameters) must be similarly attributed. Properties that define parameters should not be public.

A Counter component with an IncrementAmount parameter now looks like this:

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

@functions {
 int currentCount = 0;

 [Parameter]
 private int IncrementAmount { get; set; } = 1;

 void IncrementCount()
 {
 currentCount += IncrementAmount;
 }
}

Simplified layouts

Layouts now inherit from BlazorLayoutComponent instead of implementing ILayoutComponent. The BlazorLayoutComponent defines a Body parameter that can be used for specifying where content should be rendered. Layouts no longer need to define their own Body property.

An example layout with these changes is shown below:

@inherits BlazorLayoutComponent

<div class="sidebar">
 <NavMenu />
</div>

<div class="main">
 <div class="top-row px-4">
 <a href="http://blazor.net" target="_blank" class="ml-md-auto">About</a>
 </div>

 <div class="content px-4">
 @Body
 </div>
</div>

Summary

We hope you enjoy this latest preview of Blazor. Your feedback is especially important to us during this experimental phase for Blazor. If you run into issues or have questions while trying out Blazor please file issues on GitHub. You can also chat with us and the Blazor community on Gitter if you get stuck or to share how Blazor is working for you. After you’ve tried out Blazor for a while please also let us know what you think by taking our in-product survey. Just click the survey link shown on the app home page when running one of the Blazor project templates:

Blazor survey

Thanks for trying out Blazor!