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!