Quantcast
Channel: ASP.NET Blog
Viewing all 7144 articles
Browse latest View live

Razor support in Visual Studio Code now in Preview

$
0
0

Earlier this week we released a preview of support for working with Razor files (.cshtml) in the C# extension for Visual Studio Code (1.17.1). This initial release introduces C# completions, directive completions, and basic diagnostics (red squiggles for errors) for ASP.NET Core projects.

Prerequisites

To use this preview of Razor support in Visual Studio Code install the following:

If you already installed VS Code and the C# extension in the past, make sure you have updated to the latest versions of both.

Get started

To try out the new Razor tooling, create a new ASP.NET Core web app and then edit any Razor (.cshtml) file.

  1. Open Visual Studio Code
  2. Select Terminal > New Terminal
  3. In the new terminal run:

    dotnet new webapp -o WebApp1`
    code -r WebApp1
    
  4. Open About.cshtml

  5. Try out HTML completions

    HTML completions

  6. And Razor directive completions

    Directive completions

  7. And C# completions

    C# completions

  8. You also get diagnostics (red squiggles)

    C# diagnostics

Limitations and known issues

This is the first alpha release of the Razor tooling for Visual Studio Code, so there are a number of limitations and known issues:

  • Razor editing is currently only supported in ASP.NET Core projects (no support for ASP.NET projects or Blazor projects yet)
  • Support for tag helpers and formatting is not yet implemented
  • Limited support for colorization
  • Loss of HTML completions following C# less than (<) operator
  • Error squiggles misaligned for expressions near the start of a new line
  • Incorrect errors in Blazor projects for event bindings
  • Emmet based abbreviation expansion is not yet supported

Note that if you need to disable the Razor tooling for any reason:

  • Open the Visual Studio Code User Settings: File -> Preferences -> Settings
  • Search for "razor"
  • Check the "Razor: Disabled" checkbox

Feedback

Even though the functionality of Razor tooling is currently pretty limited, we are shipping this preview now so that we can start collecting feedback. Any issues or suggestions for the Razor tooling in Visual Studio Code should be reported on the https://github.com/aspnet/Razor.VSCode repo.

To help us diagnose any reported issues please provide the following information in the GitHub issue:

  1. Razor (cshtml) file content
  2. Generated C# code from the Razor CSharp output
    • Right-click inside your .cshtml file and select "Command Palette"
    • Search for and select "Razor: Show Razor CSharp"
  3. Verbose Razor log output
    • See instructions for capturing the Razor log output here
  4. OmniSharp log output
    • Open VS Code's "Output" pane
    • In the dropdown choose "OmniSharp Log"

What's next?

Next up we are working on tag helper support. This will include support for tag helper completions and IntelliSense. Once we have tag helper tooling support in place we can then start work on enabling Blazor tooling support as well. Follow our progress and join in the conversation on the https://github.com/aspnet/Razor.VSCode repo.

Thanks for trying out this early preview!


Announcing ASP.NET Core 2.2, available today!

$
0
0

I’m happy to announce that ASP.NET Core 2.2 is available as part of .NET Core 2.2 today!

How to get it

You can download the new .NET Core SDK (2.2.100) for your dev machine and build servers from the .NET Core 2.2 download page. New Windows Server hosting, runtime installers and binary archives are also available from this page for updating servers.

This release updates .NET Core, ASP.NET Core, and Entity Framework Core to version 2.2.0. The new SDK version is 2.2.100. Visual Studio requirements are as follows:

Visual Studio 2019 16.0 Preview 1, also available today, includes the .NET Core SDK 2.2.100 as an optional component.

What’s new?

The main theme for this ASP.NET Core release was to improve developer productivity and platform functionality with regard to building Web/HTTP APIs. As usual, we made some performance improvements as well. We’ve posted about these features as part of the preview releases and you as such you can read about them by following the links below:

Health Checks integration with BeatPulse

We’re happy to announce that the BeatPulse project now supports the new Health Checks API, which means you can easily add checks for dozens of popular systems and dependencies using their great support. Here’s a message from the BeatPulse team about their support for our new Health Checks API:

BeatPulse is a community driven project that was created to provide health checking mechanisms for systems, networking and a wide variety of services that are common within the enterprise, e.g. SqlServer, MySql,Postgress, Redis, Kafka and many more . When Microsoft announced ASP.NET Core Health Checks for the 2.2 roadmap, the BeatPulse team ported all the existing liveness packages and features to work with the new Microsoft Health Checks abstractions at the repository AspNetCore.Diagnostics.HealthChecks. Apart from all the health checking packages, the BeatPulse team also incorporates other features like pulse tracking (Application Insights and Prometheus), failure notifications and a UI interface were we can configure different monitored systems and have a global view of health status. This UI is available as a Docker image published in Docker Hub.

More coming soon

When we announced planning for ASP.NET Core 2.2, we mentioned a number of features that aren’t detailed above, including API Authorization with IdentityServer4, Open API (Swagger) driven client code generation, and the HTTP REPL command line tool. These features are still being worked on and aren’t quite ready for release, however we expect to make them available as add-ons in the coming months. Thanks for your patience while we complete these experiences and get them ready for you all to try out.

Migrating a project to ASP.NET Core 2.2

To migrate an ASP.NET Core project from 2.1 to 2.2, open the project’s .csproj file and change the value of the TargetFramework element to netcoreapp2.2. You do not need to do this if you’re targeting .NET Framework 4.x.

Finish by updating your NuGet package references to the latest stable versions. Note that projects targeting .NET Core (rather than .NET Framework) should not have a package version specified for the Microsoft.AspNetCore.App package reference as this will be managed automatically by the SDK. Doing so will now result in a build warning.

For more information on upgrading to ASP.NET Core 2.2 see here.

Support life cycle

ASP.NET Core 2.2 is the latest release in the “Current” .NET Core train. This represents the first release since the declaration of 2.1 LTS that reestablishes a separate LTS and Current train. The Current train is where new features, enhancements, and regular bug fixes are applied and is recommended for most customers. Note that both LTS and Current releases receive servicing updates for security and critical stability fixes. It is currently expected that 2.2 will the last non-servicing release in the 2.x life cycle, and as such customers not using an LTS release will need to migrate to 3.0 GA, within 3 months of its release in the second half of 2019 in order to remain supported.

Read more about the .NET Core support policy here.

Availability in Azure App Service

The .NET Core 2.2 SDK, runtime, and updated ASP.NET Core IIS Module are in the process of being deployed to Azure App Service regions around the world. We expect this to be completed before the end of December 2018.

Some regions may receive the updated runtime before the updated ASP.NET Core IIS Module (ANCM), which is required by default for projects targeting ASP.NET Core 2.2. It’s also a requirement for the new in-process hosting feature. If you receive startup errors after deploying to Azure App Service, try configuring your project to use the existing version of ANCM by setting the AspNetCoreModule property to the value “AspNetCoreModule”, e.g.:

<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>

Once the target region has been updated with the latest ANCM version, you can remove that property altogether and redeploy the application to have it switch to using the new ANCM.

This release also adds better 64-bit support for .NET Core in Azure App Service. If you’re running your ASP.NET Core application on .NET Core 2.2 with in-process hosting, you can simply enable the 64-bit option in the Azure Portal and the site will now run in a 64-bit process. For other information on how to run your ASP.NET Core application in a 64-bit process in Azure App Service with other configurations, see this article.

Giving feedback

As always, please provide us feedback by logging issues at https://github.com/aspnet/AspNetCore. We look forward to hearing from you!

Azure Hybrid Benefit for SQL Server

$
0
0

In my previous blog post I talked about how to migrate data from existing on-prem SQL Server instances to Azure SQL Database. If you haven’t heard SQL Server 2008 end of support is coming this summer, so it’s a good time to evaluate moving to an Azure SQL Database.

If you decide to try Azure, chances are you will not be able to immediately move 100% of your on-prem databases and relevant applications in one go. You’ll probably come up with a migration plan that spans weeks, months or even years. During the migration phase you will be spinning up new instances of Azure SQL Database and turning off on-prem SQL Server instances, but for a little bit of time there will be overlap.

To help manage the cost during such transitions we offer the Azure Hybrid Benefit. You can convert 1 core of SQL Enterprise edition to get up to 4 vCores of Azure SQL Database at a reduced rate. For example, if you have 4 core licenses of SQL Enterprise edition, you can receive up to 16 vCores of Azure SQL Database.

If you want to learn more check out the Azure Hybrid Benefit FAQ and don’t forget, if you have any questions around migrating your .NET applications to Azure you can always ask for free assistance. If you have any questions about this post just leave us a comment below.

The post Azure Hybrid Benefit for SQL Server appeared first on ASP.NET Blog.

ASP.NET Core updates in .NET Core 3.0 Preview 3

$
0
0

.NET Core 3.0 Preview 3 is now available and it includes a bunch of new updates to ASP.NET Core.

Here’s the list of what’s new in this preview:

  • Razor Components improvements:
    • Single project template
    • New .razor extension
    • Endpoint routing integration
    • Prerendering
    • Razor Components in Razor Class Libraries
    • Improved event handling
    • Forms & validation
  • Runtime compilation
  • Worker Service template
  • gRPC template
  • Angular template updated to Angular 7
  • Authentication for Single Page Applications
  • SignalR integration with endpoint routing
  • SignalR Java client support for long polling

Please see the release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET Core 3.0 Preview 3 install the .NET Core 3.0 Preview 3 SDK

If you’re on Windows using Visual Studio, you’ll also want to install the latest preview of Visual Studio 2019.

  • Note: To use use this preview of .NET Core 3.0 with the release channel of Visual Studio 2019, you will need to enable the option to use previews of the .NET Core SDK by going to Tools > Options > Projects and Solutions > .NET Core > Use previews of the .NET Core SDK

Upgrade an existing project

To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 3, follow the migrations steps in the ASP.NET Core docs.

Please also see the full list of breaking changes in ASP.NET Core 3.0.

Razor Components improvements

In the previous preview, we introduced Razor Components as a new way to build interactive client-side web UI with ASP.NET Core. This section covers the various improvements we’ve made to Razor Components in this preview update.

Single project template

The Razor Components project template is now a single project instead of two projects in the same solution. The authored Razor Components live directly in the ASP.NET Core app that hosts them. The same ASP.NET Core project can contain Razor Components, Pages, and Views. The Razor Components template also has HTTPS enabled by default like the other ASP.NET Core web app templates.

New .razor extension

Razor Components are authored using Razor syntax, but are compiled differently than Razor Pages and Views. To clarify which Razor files should be compiled as Razor Components we’ve introduced a new file extension: .razor. In the Razor Components template all component files now use the .razor extension. Razor Pages and Views still use the .cshtml extension.

Razor Components can still be authored using the .cshtml file extension as long as those files are identified as Razor Component files using the _RazorComponentInclude MSBuild property. For example, the Razor Component template in this release specifies that all .cshtml files under the Components folder should be treated as Razor Components.

<_RazorComponentInclude>Components\**\*.cshtml</_RazorComponentInclude>

Please note that there are a number of limitations with .razor files in this release. Please refer to the release notes for the list of known issues and available workarounds.

Endpoint routing integration

Razor Components are now integrated into ASP.NET Core’s new Endpoint Routing system. To enable Razor Components support in your application, use MapComponentHub<TComponent> within your routing configuration. For example,

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapComponentHub<App>("app");
});

This configures the application to accept incoming connections for interactive Razor Components, and specifies that the root component App should be rendered within a DOM element matching the selector app.

Prerendering

The Razor Components project template now does server-side prerendering by default. This means that when a user navigates to your application, the server will perform an initial render of your Razor Components and deliver the result to their browser as plain static HTML. Then, the browser will reconnect to the server via SignalR and switch the Razor Components into a fully interactive mode. This two-phase delivery is beneficial because:

  • It improves the perceived performance of the site, because the UI can appear sooner, without waiting to make any WebSocket connections or even running any client-side script. This makes a bigger difference for users on slow connections, such as 2G/3G mobiles.
  • It can make your application easily crawlable by search engines.

For users on faster connections, such as intranet users, this feature has less impact because the UI should appear near-instantly regardless.

To set up prerendering, the Razor Components project template no longer has a static HTML file. Instead a single Razor Page, /Pages/Index.cshtml, is used to prerender the app content using the Html.RenderComponentAsync<TComponent>() HTML helper. The page also references the components.server.js script to set up the SignalR connection after the content has been prerendered and downloaded. And because this is a Razor Page, features like the environment tag helper just work.

Index.cshtml

@page "{*clientPath}"
<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
    <app>@(await Html.RenderComponentAsync<App>())</app>

    <script src="_framework/components.server.js"></script>
</body>
</html>

Besides the app loading faster, you can see that prerendering is happening by looking at the downloaded HTML source in the browser dev tools. The Razor Components are fully rendered in the HTML.

Razor Components in Razor Class Libraries

You can now add Razor Components to Razor Class Libraries and reference them from ASP.NET Core projects using Razor Components.

To create reusable Razor Components in a Razor Class Library:

  1. Create an Razor Components app:

    dotnet new razorcomponents -o RazorComponentsApp1
    
  2. Create a new Razor Class Library

    dotnet new razorclasslib -o RazorClassLib1
    
  3. Add a Component1.razor file to the Razor Class Library

Component1.razor

<h1>Component1</h1>

<p>@message</p>

@functions {
    string message = "Hello from a Razor Class Library"!;
}
  1. Reference the Razor Class Library from an ASP.NET Core app using Razor Components:

    dotnet add RazorComponentsApp1 reference RazorClassLib1
    
  2. In the Razor Components app, import all components from the Razor Class Library using the @addTagHelper directive and then use Component1 in the app:

Index.razor

@page "/"
@addTagHelper *, RazorClassLib1

<h1>Hello, world!</h1>

Welcome to your new app.

<Component1 />

Note that Razor Class Libraries are not compatible with Blazor apps in this release. Also, Razor Class Libraries do not yet support static assets. To create components in a library that can be shared with Blazor and Razor Components apps you still need to use a Blazor Class Library. This is something we expect to address in a future update.

Improved event handling

The new EventCallback and EventCallback<> types make defining component callbacks much more straightforward. For example consider the following two components:

MyButton.razor

<button onclick="@OnClick">Click here and see what happens!</button>

@functions {
    [Parameter] EventCallback<UIMouseEventArgs> OnClick { get; set; }
}

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessage" />

@function {
    string text;

    void ShowMessage(UIMouseEventArgs e)
    {
        text = "Hello, world!";
    }
}

The OnClick callback is of type EventCallback<UIMouseEventArgs> (instead of Action<UIMouseEventArgs>), which MyButton passes off directly to the onclick event handler. The compiler handles converting the delegate to an EventCallback, and will do some other things to make sure that the rendering process has enough information to render the correct target component. As a result an explicit call to StateHasChanged in the ShowMessage event handler isn’t necessary.

By using the EventCallback<> type OnClick handler can now also be asynchronous without any additional code changes to MyButton:

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessageAsync" />

@function {
    string text;

    async Task ShowMessageAsync(UIMouseEventArgs e)
    {
        await Task.Yield(); 
        text = "Hello, world!";
    }
}

We recommend using EventCallback and EventCallback<T> when you define component parameters for event handling and binding. Use EventCallback<> where possible because it’s strongly typed and will provide better feedback to users of your component. Use EventCallback when there’s no value you will pass to the callback.

Note that consumers don’t have to write different code when using a component because of EventCallback. The same event handling code should still work, while removing some thorny issues and improving the usability of your components.

Forms & validation

This preview release adds built-in components and infrastructure for handling forms and validation.

One of the benefits of using .NET for client-side web development is the ability to share the same implementation logic between the client and the server. Validation logic is a prime example. The new forms & validation support in Razor Components includes support for handling validation using data annotations, or you can plug in your preferred validation system.

For example, the following Person type defines validation logic using data annotations:

public class Person
{
    [Required(ErrorMessage = "Enter a name")]
    [StringLength(10, ErrorMessage = "That name is too long")]
    public string Name { get; set; }

    [Range(0, 200, ErrorMessage = "Nobody is that old")]
    public int AgeInYears { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")]
    public bool AcceptsTerms { get; set; }
}

Here’s how you can create a validating form based on this Person model:

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p class="name">
        Name: <InputText bind-Value="@person.Name" />
    </p>
    <p class="age">
        Age (years): <InputNumber bind-Value="@person.AgeInYears" />
    </p>
    <p class="accepts-terms">
        Accepts terms: <InputCheckbox bind-Value="@person.AcceptsTerms" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@functions {
    Person person = new Person();

    void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

If you add this form to your app and run it you will get a basic form that automatically validates the field inputs when they are changed and when the form is submitted.

Validating form

There are quite a few things going on here, so let’s break it down piece by piece:

  • The form is defined using the new EditForm component. The EditForm sets up an EditContext as a cascading value that tracks metadata about the edit process (e.g. what’s been modified, current validation messages, etc.). The EditForm also provides convenient events for valid and invalid submits (OnValidSubmit, OnInvalidSubmit). Or you can use OnSubmit directly if you want to trigger the validation yourself.
  • The DataAnnotationsValidator component attaches validation support using data annotations to the cascaded EditContext. Enabling support for validation using data annotations currently requires this explicit gesture, but we are considering making this the default behavior that you can then override.
  • Each of the form fields are defined using a set of built-in input components (InputText, InputNumber, InputCheckbox, InputSelect, etc.). These components provide default behavior for validating on edit and changing their CSS class to reflect the field state. Some of them have useful parsing logic (e.g., InputDate and InputNumber handle unparseable values gracefully by registering them as validation errors). The relevant ones also support nullability of the target field (e.g., int?).
  • The ValidationMessage component displays validation messages for a specific field.
  • The ValidationSummary component summarizes all validation messages (similar to the validation summary tag helper).

There are some limitations with the built-in input components that we expect to improve in future updates. For example, you can’t currently specify arbitrary attributes on the generate input tags. In the future, we plan to enable components that pass through all extra attributes. For now, you’ll need to build your own component subclasses to handle these cases.

Runtime compilation

Support for runtime compilation was removed from the ASP.NET Core shared framework in .NET Core 3.0, but you can now enable it by adding a package to your app.

To enable runtime compilation:

  1. Add a package reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview3-19153-02" />
    
  2. In Startup.ConfigureServices add a call to AddRazorRuntimeCompilation

    services.AddMvc().AddRazorRuntimeCompilation();
    

Worker Service Template

In 3.0.0-preview3 we are introducing a new template called ‘Worker Service’. This template is designed as a starting point for running long-running background processes like you might run as a Windows Service or Linux Daemon. Examples of this would be producing/consuming messages from a message queue or monitoring a file to process when it appears. It’s intended to provide the productivity features of ASP.NET Core such as Logging, DI, Configuration, etc without carrying any web dependencies.

Worker Service

In the coming days we will publish a few blog posts giving more walkthroughs on using the Worker template to get started. We will have dedicated posts about publishing as a Windows/Systemd service, running on ACI/AKS, as well as running as a WebJob.

Caveats

Whilst the intent is for the worker template to not have any dependencies on web technologies by default, in preview3 it still uses the Web SDK and is shown after you select ‘ASP.NET Core WebApplication’ in Visual Studio. This is temporary and will be changed in a future preview. This means that for preview3 you will see many options in VS that may not make sense, such as publishing your worker as a web app to IIS.

Angular template updated to Angular 7

The Angular template is now updated to Angular 7. We anticipate updating again to Angular 8 before .NET Core 3.0 ships a stable release.

Authentication for the Single Page Application templates

This release introduces support for authentication in our Angular and React templates. In this section we show how to create a new Angular or React template that allows us to authenticate users and access a protected API resource.

Our support for authenticating and authorizing users is powered behind the scenes by IdentityServer, with some extensions we built to simplify the configuration experience for the scenarios we are targeting.

Note: In this post we showcase authentication support for Angular but the React template offers equivalent functionality.

Create a new Angular application

To create a new Angular application with authentication support we invoke the following command:

dotnet new angular -au Individual

This command creates a new ASP.NET Core application with a hosted client Angular application. The ASP.NET Core application includes an Identity Server instance already configured so that your Angular application can authenticate users and send HTTP requests against the protected resources in the ASP.NET Core application.

The authentication and authorization support is built as an Angular module that gets imported into your application and offers a suite of components and services to enhance the functionality of the main applicaiton module.

Run the application

To run the application simply execute the command below and open the browser in the url displayed on the console:

dotnet run
Hosting environment: Development
Content root path: C:\angularapp
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

SPA index

When we open the application we see the usual Home, Counter and Fetch data menu options and two new options: Register and Login. If we click on Register we get sent to the default Identity UI where (after running migrations and updating the database) we can register as a new user.

Register a new user

SPA register

After registering as a new user we get redirected back to the application where we can see that we are successfully authenticated

SPA logged in

Call an authenticated API

If we click on the Fetch data we can see the weather forecast data table

SPA fetch data

Protect an existing API

To protect an API on the server we simply need to use the [Authorize] attribute on the controller or action that we want to protect.

[Authorize]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
...
}

Require authentication for a client route.

To require the user be authenticated when visiting a page in the Angular application we apply the [AuthorizeGuard] to the route we are configuring.

import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ApiAuthorizationModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
    ])
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Get more details by visiting the docs page

This is a quick introduction to what our new authentication support for Single Page Applications has to offer. For more details check out the docs.

Endpoint Routing with SignalR Hubs

In 3.0.0-preview3 we are hooking SignalR hubs into the new Endpoint Routing feature recently released. SignalR hub wire-up was previously done explicitly:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

This meant developers would need to wire up controllers, Razor pages, and hubs in a variety of different places during startup, leading to a series of nearly-identical routing segments:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

app.UseRouting(routes =>
{
    routes.MapRazorPages();
});

Now, SignalR hubs can also be routed via endpoint routing, so you’ve got a one-stop place to route nearly everything in ASP.NET Core.

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapHub<ChatHub>("hubs/chat");
});

Long Polling for Java SignalR Client

We added long polling support to the Java client which enables it to establish connections even in environments that do not support WebSockets. This also gives you the ability to specifically select the long polling transport in your client apps.

gRPC Template

This preview release introduces a new template for building gRPC services with ASP.NET Core using a new gRPC framework we are building in collaboration with Google.

gRPC is a popular RPC (remote procedure call) framework that offers an opinionated contract-first approach to API development. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, and cancellation and timeouts.

gRPC template

The templates create two projects: a gRPC service hosted inside ASP.NET Core, and a console application to test it with.

gRPC solution

This is the first public preview of gRPC for ASP.NET Core and it doesn’t implement all of gRPC’s features, but we’re working hard to make the best gRPC experience for ASP.NET possible. Please try it out and give us feedback at grpc/grpc-dotnet on GitHub.

Stay tuned for future blog posts discussing gRPC for ASP.NET Core in more detail.

Give feedback

We hope you enjoy the new features in this preview release of ASP.NET Core! Please let us know what you think by filing issues on Github.

The post ASP.NET Core updates in .NET Core 3.0 Preview 3 appeared first on ASP.NET Blog.

Blazor 0.9.0 experimental release now available

$
0
0

Blazor 0.9.0 is now available! This release updates Blazor with the Razor Components improvements in .NET Core 3.0 Preview 3.

New Razor Component improvements now available to Blazor apps:

  • Improved event handling
  • Forms & validation

Checkout the ASP.NET Core 3.0 Preview 3 announcement for details on these improvements. See also the Blazor 0.9.0 release notes for additional details.

Note: The Blazor templates have not been updated to use the new .razor file extension for Razor Components in this release. This update will be done in a future release.

Get Blazor 0.9.0

To get started with Blazor 0.9.0 install the following:

  1. .NET Core 3.0 Preview 3 SDK (3.0.100-preview3-010431)
  2. Visual Studio 2019 (Preview 4 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor extension from the Visual Studio Marketplace.
  4. The Blazor templates on the command-line:

    dotnet new -i Microsoft.AspNetCore.Blazor.Templates::0.9.0-preview3-19154-02
    

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

Upgrade to Blazor 0.9.0

To upgrade your existing Blazor apps to Blazor 0.9.0 first make sure you’ve installed the prerequisites listed above.

To upgrade a Blazor 0.8.0 project to 0.9.0:

  • Update the Blazor packages and .NET CLI tool references to 0.9.0-preview3-19154-02.
  • Update the remaining Microsoft.AspNetCore.* packages to 3.0.0-preview3-19153-02.
  • Remove any usage of JSRuntime.Current and instead use dependency injection to get the current IJSRuntime instance and pass it through to where it is needed.

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

The post Blazor 0.9.0 experimental release now available appeared first on ASP.NET Blog.

Blazor 0.7.0 experimental release now available

$
0
0

Blazor 0.7.0 is now available! This release focuses on enabling component coordination across ancestor-descendent relationships. We've also added some improvements to the debugging experience.

Here's what's new in the Blazor 0.7.0 release:

  • Cascading values and parameters
  • Debugging improvements

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

Get Blazor 0.7.0

Install the following:

  1. .NET Core 2.1 SDK (2.1.500 or later).
  2. Visual Studio 2017 (15.9 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor Language Services extension from the Visual Studio Marketplace.
  4. 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.7.0

To upgrade a Blazor 0.6.0 project to 0.7.0:

  • Install the prerequisites listed above.
  • Update the Blazor packages and .NET CLI tool references to 0.7.0. The 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.7.0" />
        <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.7.0" />
        <DotNetCliToolReference Include="Microsoft.AspNetCore.Blazor.Cli" Version="0.7.0" />
    </ItemGroup>
    
    </Project>
    

That's it! You're now ready to try out the latest Blazor features.

Cascading values and parameters

Blazor components can accept parameters that can be used to flow data into a component and impact the component's rendering. Parameter values are provided from parent component to child component. Sometimes, however, it's inconvenient to flow data from an ancestor component to a descendent component, especially when there are many layers in between. Cascading values and parameters solve this problem by providing a convenient way for an ancestor component to provide a value that is then available to all descendent components. They also provide a great way for components to coordinate.

For example, if you wanted to provide some theme information for a specific part of your app you could flow the relevant styles and classes from component to component, but this would be tedious and cumbersome. Instead, a common ancestor component can provide the theme information as a cascading value that descendents can accept as a cascading parameter and then consume as needed.

Let's say the following ThemeInfo class specifies all of the theme information that you want to flow down the component hierarchy so that all of the buttons within that part of your app share the same look and feel:

public class ThemeInfo 
{
    public string ButtonClass { get; set; }
}

An ancestor component can provide a cascading value using the CascadingValue component. The CascadingValue component wraps a subtree of the component hierarchy and specifies a single value that will be available to all components within that subtree. For example, we could specify the theme info in our application layout as a cascading parameter for all components that make up the layout body like this:

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

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

@functions {
    ThemeInfo theme = new ThemeInfo { ButtonClass = "btn-success" };
}

To make use of cascading values, components can declare cascading parameters using the [CascadingParameter] attribute. Cascading values are bound to cascading parameters by type. In the following example the Counter component is modified to have a cascading parameter that binds to the ThemeInfo cascading value, which is then used to set the class for the button.

@page "/counter"

<h1>Counter</h1>

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

<button class="btn @ThemeInfo.ButtonClass" onclick="@IncrementCount">Click me</button>

@functions {
    int currentCount = 0;

    [CascadingParameter] protected ThemeInfo ThemeInfo { get; set; }

    void IncrementCount()
    {
        currentCount++;
    }
}

When we run the app we can see that the new style is applied:

Counter with cascading parameter

Cascading parameters also enable components to collaborate across the component hierarchy. For example, let's say you have a TabSet component that contains a number of Tab components, like this:

<TabSet>
    <Tab Title="First tab">
        <h4>First tab</h4>
        This is the first tab.
    </Tab>

    @if (showSecondTab)
    {
        <Tab Title="Second">
            <h4>Second tab</h4>
            You can toggle me.
        </Tab>
    }

    <Tab Title="Third">
        <h4>Third tab</h4>

        <label>
            <input type="checkbox" bind=@showSecondTab />
            Toggle second tab
        </label>
    </Tab>
</TabSet>

In this example the child Tab components are not explicitly passed as parameters to the TabSet. Instead they are simply part of the child content of the TabSet. But the TabSet still needs to know about each Tab so that it can render the headers and the active tab. To enable this coordination without requiring any specific wire up from the user, the TabSet component can provide itself as a cascading value that can then be picked up by the descendent Tab components:

In TabSet.cshtml

<!-- Display the tab headers -->
<CascadingValue Value=this>
    <ul class="nav nav-tabs">
        @ChildContent
    </ul>
</CascadingValue>

This allows the descendent Tab components to capture the containing TabSet as a cascading parameter, so they can add themselves to the TabSet and coordinate on which Tab is active:

In Tab.cshtml

[CascadingParameter] TabSet ContainerTabSet { get; set; }

Check out the full TabSet sample here.

Debugging improvements

In Blazor 0.5.0 we added some very preliminary support for debugging client-side Blazor apps in the browser. While this initial debugging support demonstrated that debugging .NET apps in the browser was possible, it was still a pretty rough experience. Blazor 0.7.0 picks up the latest runtime updates, which includes some fixes that makes the debugging experience more reliable. You can now more reliably set and remove breakpoints, and the reliability of step debugging has been improved.

Improved Blazor debugging

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

Razor support in Visual Studio Code now in Preview

$
0
0

Earlier this week we released a preview of support for working with Razor files (.cshtml) in the C# extension for Visual Studio Code (1.17.1). This initial release introduces C# completions, directive completions, and basic diagnostics (red squiggles for errors) for ASP.NET Core projects.

Prerequisites

To use this preview of Razor support in Visual Studio Code install the following:

If you already installed VS Code and the C# extension in the past, make sure you have updated to the latest versions of both.

Get started

To try out the new Razor tooling, create a new ASP.NET Core web app and then edit any Razor (.cshtml) file.

  1. Open Visual Studio Code
  2. Select Terminal > New Terminal
  3. In the new terminal run:

    dotnet new webapp -o WebApp1`
    code -r WebApp1
    
  4. Open About.cshtml

  5. Try out HTML completions

    HTML completions

  6. And Razor directive completions

    Directive completions

  7. And C# completions

    C# completions

  8. You also get diagnostics (red squiggles)

    C# diagnostics

Limitations and known issues

This is the first alpha release of the Razor tooling for Visual Studio Code, so there are a number of limitations and known issues:

  • Razor editing is currently only supported in ASP.NET Core projects (no support for ASP.NET projects or Blazor projects yet)
  • Support for tag helpers and formatting is not yet implemented
  • Limited support for colorization
  • Loss of HTML completions following C# less than (<) operator
  • Error squiggles misaligned for expressions near the start of a new line
  • Incorrect errors in Blazor projects for event bindings
  • Emmet based abbreviation expansion is not yet supported

Note that if you need to disable the Razor tooling for any reason:

  • Open the Visual Studio Code User Settings: File -> Preferences -> Settings
  • Search for "razor"
  • Check the "Razor: Disabled" checkbox

Feedback

Even though the functionality of Razor tooling is currently pretty limited, we are shipping this preview now so that we can start collecting feedback. Any issues or suggestions for the Razor tooling in Visual Studio Code should be reported on the https://github.com/aspnet/Razor.VSCode repo.

To help us diagnose any reported issues please provide the following information in the GitHub issue:

  1. Razor (cshtml) file content
  2. Generated C# code from the Razor CSharp output
    • Right-click inside your .cshtml file and select "Command Palette"
    • Search for and select "Razor: Show Razor CSharp"
  3. Verbose Razor log output
    • See instructions for capturing the Razor log output here
  4. OmniSharp log output
    • Open VS Code's "Output" pane
    • In the dropdown choose "OmniSharp Log"

What's next?

Next up we are working on tag helper support. This will include support for tag helper completions and IntelliSense. Once we have tag helper tooling support in place we can then start work on enabling Blazor tooling support as well. Follow our progress and join in the conversation on the https://github.com/aspnet/Razor.VSCode repo.

Thanks for trying out this early preview!

Announcing ASP.NET Core 2.2, available today!

$
0
0

I’m happy to announce that ASP.NET Core 2.2 is available as part of .NET Core 2.2 today!

How to get it

You can download the new .NET Core SDK (2.2.100) for your dev machine and build servers from the .NET Core 2.2 download page. New Windows Server hosting, runtime installers and binary archives are also available from this page for updating servers.

This release updates .NET Core, ASP.NET Core, and Entity Framework Core to version 2.2.0. The new SDK version is 2.2.100. Visual Studio requirements are as follows:

Visual Studio 2019 16.0 Preview 1, also available today, includes the .NET Core SDK 2.2.100 as an optional component.

What’s new?

The main theme for this ASP.NET Core release was to improve developer productivity and platform functionality with regard to building Web/HTTP APIs. As usual, we made some performance improvements as well. We’ve posted about these features as part of the preview releases and you as such you can read about them by following the links below:

Health Checks integration with BeatPulse

We’re happy to announce that the BeatPulse project now supports the new Health Checks API, which means you can easily add checks for dozens of popular systems and dependencies using their great support. Here’s a message from the BeatPulse team about their support for our new Health Checks API:

BeatPulse is a community driven project that was created to provide health checking mechanisms for systems, networking and a wide variety of services that are common within the enterprise, e.g. SqlServer, MySql,Postgress, Redis, Kafka and many more . When Microsoft announced ASP.NET Core Health Checks for the 2.2 roadmap, the BeatPulse team ported all the existing liveness packages and features to work with the new Microsoft Health Checks abstractions at the repository AspNetCore.Diagnostics.HealthChecks. Apart from all the health checking packages, the BeatPulse team also incorporates other features like pulse tracking (Application Insights and Prometheus), failure notifications and a UI interface were we can configure different monitored systems and have a global view of health status. This UI is available as a Docker image published in Docker Hub.

More coming soon

When we announced planning for ASP.NET Core 2.2, we mentioned a number of features that aren’t detailed above, including API Authorization with IdentityServer4, Open API (Swagger) driven client code generation, and the HTTP REPL command line tool. These features are still being worked on and aren’t quite ready for release, however we expect to make them available as add-ons in the coming months. Thanks for your patience while we complete these experiences and get them ready for you all to try out.

Migrating a project to ASP.NET Core 2.2

To migrate an ASP.NET Core project from 2.1 to 2.2, open the project’s .csproj file and change the value of the TargetFramework element to netcoreapp2.2. You do not need to do this if you’re targeting .NET Framework 4.x.

Finish by updating your NuGet package references to the latest stable versions. Note that projects targeting .NET Core (rather than .NET Framework) should not have a package version specified for the Microsoft.AspNetCore.App package reference as this will be managed automatically by the SDK. Doing so will now result in a build warning.

For more information on upgrading to ASP.NET Core 2.2 see here.

Support life cycle

ASP.NET Core 2.2 is the latest release in the “Current” .NET Core train. This represents the first release since the declaration of 2.1 LTS that reestablishes a separate LTS and Current train. The Current train is where new features, enhancements, and regular bug fixes are applied and is recommended for most customers. Note that both LTS and Current releases receive servicing updates for security and critical stability fixes. It is currently expected that 2.2 will the last non-servicing release in the 2.x life cycle, and as such customers not using an LTS release will need to migrate to 3.0 GA, within 3 months of its release in the second half of 2019 in order to remain supported.

Read more about the .NET Core support policy here.

Availability in Azure App Service

The .NET Core 2.2 SDK, runtime, and updated ASP.NET Core IIS Module are in the process of being deployed to Azure App Service regions around the world. We expect this to be completed before the end of December 2018.

Some regions may receive the updated runtime before the updated ASP.NET Core IIS Module (ANCM), which is required by default for projects targeting ASP.NET Core 2.2. It’s also a requirement for the new in-process hosting feature. If you receive startup errors after deploying to Azure App Service, try configuring your project to use the existing version of ANCM by setting the AspNetCoreModule property to the value “AspNetCoreModule”, e.g.:

<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>

Once the target region has been updated with the latest ANCM version, you can remove that property altogether and redeploy the application to have it switch to using the new ANCM.

This release also adds better 64-bit support for .NET Core in Azure App Service. If you’re running your ASP.NET Core application on .NET Core 2.2 with in-process hosting, you can simply enable the 64-bit option in the Azure Portal and the site will now run in a 64-bit process. For other information on how to run your ASP.NET Core application in a 64-bit process in Azure App Service with other configurations, see this article.

Giving feedback

As always, please provide us feedback by logging issues at https://github.com/aspnet/AspNetCore. We look forward to hearing from you!


Azure Hybrid Benefit for SQL Server

$
0
0

In my previous blog post I talked about how to migrate data from existing on-prem SQL Server instances to Azure SQL Database. If you haven’t heard SQL Server 2008 end of support is coming this summer, so it’s a good time to evaluate moving to an Azure SQL Database.

If you decide to try Azure, chances are you will not be able to immediately move 100% of your on-prem databases and relevant applications in one go. You’ll probably come up with a migration plan that spans weeks, months or even years. During the migration phase you will be spinning up new instances of Azure SQL Database and turning off on-prem SQL Server instances, but for a little bit of time there will be overlap.

To help manage the cost during such transitions we offer the Azure Hybrid Benefit. You can convert 1 core of SQL Enterprise edition to get up to 4 vCores of Azure SQL Database at a reduced rate. For example, if you have 4 core licenses of SQL Enterprise edition, you can receive up to 16 vCores of Azure SQL Database.

If you want to learn more check out the Azure Hybrid Benefit FAQ and don’t forget, if you have any questions around migrating your .NET applications to Azure you can always ask for free assistance. If you have any questions about this post just leave us a comment below.

The post Azure Hybrid Benefit for SQL Server appeared first on ASP.NET Blog.

ASP.NET Core updates in .NET Core 3.0 Preview 3

$
0
0

.NET Core 3.0 Preview 3 is now available and it includes a bunch of new updates to ASP.NET Core.

Here’s the list of what’s new in this preview:

  • Razor Components improvements:
    • Single project template
    • New .razor extension
    • Endpoint routing integration
    • Prerendering
    • Razor Components in Razor Class Libraries
    • Improved event handling
    • Forms & validation
  • Runtime compilation
  • Worker Service template
  • gRPC template
  • Angular template updated to Angular 7
  • Authentication for Single Page Applications
  • SignalR integration with endpoint routing
  • SignalR Java client support for long polling

Please see the release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET Core 3.0 Preview 3 install the .NET Core 3.0 Preview 3 SDK

If you’re on Windows using Visual Studio, you’ll also want to install the latest preview of Visual Studio 2019.

  • Note: To use use this preview of .NET Core 3.0 with the release channel of Visual Studio 2019, you will need to enable the option to use previews of the .NET Core SDK by going to Tools > Options > Projects and Solutions > .NET Core > Use previews of the .NET Core SDK

Upgrade an existing project

To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 3, follow the migrations steps in the ASP.NET Core docs.

Please also see the full list of breaking changes in ASP.NET Core 3.0.

Razor Components improvements

In the previous preview, we introduced Razor Components as a new way to build interactive client-side web UI with ASP.NET Core. This section covers the various improvements we’ve made to Razor Components in this preview update.

Single project template

The Razor Components project template is now a single project instead of two projects in the same solution. The authored Razor Components live directly in the ASP.NET Core app that hosts them. The same ASP.NET Core project can contain Razor Components, Pages, and Views. The Razor Components template also has HTTPS enabled by default like the other ASP.NET Core web app templates.

New .razor extension

Razor Components are authored using Razor syntax, but are compiled differently than Razor Pages and Views. To clarify which Razor files should be compiled as Razor Components we’ve introduced a new file extension: .razor. In the Razor Components template all component files now use the .razor extension. Razor Pages and Views still use the .cshtml extension.

Razor Components can still be authored using the .cshtml file extension as long as those files are identified as Razor Component files using the _RazorComponentInclude MSBuild property. For example, the Razor Component template in this release specifies that all .cshtml files under the Components folder should be treated as Razor Components.

<_RazorComponentInclude>Components\**\*.cshtml</_RazorComponentInclude>

Please note that there are a number of limitations with .razor files in this release. Please refer to the release notes for the list of known issues and available workarounds.

Endpoint routing integration

Razor Components are now integrated into ASP.NET Core’s new Endpoint Routing system. To enable Razor Components support in your application, use MapComponentHub<TComponent> within your routing configuration. For example,

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapComponentHub<App>("app");
});

This configures the application to accept incoming connections for interactive Razor Components, and specifies that the root component App should be rendered within a DOM element matching the selector app.

Prerendering

The Razor Components project template now does server-side prerendering by default. This means that when a user navigates to your application, the server will perform an initial render of your Razor Components and deliver the result to their browser as plain static HTML. Then, the browser will reconnect to the server via SignalR and switch the Razor Components into a fully interactive mode. This two-phase delivery is beneficial because:

  • It improves the perceived performance of the site, because the UI can appear sooner, without waiting to make any WebSocket connections or even running any client-side script. This makes a bigger difference for users on slow connections, such as 2G/3G mobiles.
  • It can make your application easily crawlable by search engines.

For users on faster connections, such as intranet users, this feature has less impact because the UI should appear near-instantly regardless.

To set up prerendering, the Razor Components project template no longer has a static HTML file. Instead a single Razor Page, /Pages/Index.cshtml, is used to prerender the app content using the Html.RenderComponentAsync<TComponent>() HTML helper. The page also references the components.server.js script to set up the SignalR connection after the content has been prerendered and downloaded. And because this is a Razor Page, features like the environment tag helper just work.

Index.cshtml

@page "{*clientPath}"
<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
    <app>@(await Html.RenderComponentAsync<App>())</app>

    <script src="_framework/components.server.js"></script>
</body>
</html>

Besides the app loading faster, you can see that prerendering is happening by looking at the downloaded HTML source in the browser dev tools. The Razor Components are fully rendered in the HTML.

Razor Components in Razor Class Libraries

You can now add Razor Components to Razor Class Libraries and reference them from ASP.NET Core projects using Razor Components.

To create reusable Razor Components in a Razor Class Library:

  1. Create an Razor Components app:

    dotnet new razorcomponents -o RazorComponentsApp1
    
  2. Create a new Razor Class Library

    dotnet new razorclasslib -o RazorClassLib1
    
  3. Add a Component1.razor file to the Razor Class Library

Component1.razor

<h1>Component1</h1>

<p>@message</p>

@functions {
    string message = "Hello from a Razor Class Library"!;
}
  1. Reference the Razor Class Library from an ASP.NET Core app using Razor Components:

    dotnet add RazorComponentsApp1 reference RazorClassLib1
    
  2. In the Razor Components app, import all components from the Razor Class Library using the @addTagHelper directive and then use Component1 in the app:

Index.razor

@page "/"
@addTagHelper *, RazorClassLib1

<h1>Hello, world!</h1>

Welcome to your new app.

<Component1 />

Note that Razor Class Libraries are not compatible with Blazor apps in this release. Also, Razor Class Libraries do not yet support static assets. To create components in a library that can be shared with Blazor and Razor Components apps you still need to use a Blazor Class Library. This is something we expect to address in a future update.

Improved event handling

The new EventCallback and EventCallback<> types make defining component callbacks much more straightforward. For example consider the following two components:

MyButton.razor

<button onclick="@OnClick">Click here and see what happens!</button>

@functions {
    [Parameter] EventCallback<UIMouseEventArgs> OnClick { get; set; }
}

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessage" />

@function {
    string text;

    void ShowMessage(UIMouseEventArgs e)
    {
        text = "Hello, world!";
    }
}

The OnClick callback is of type EventCallback<UIMouseEventArgs> (instead of Action<UIMouseEventArgs>), which MyButton passes off directly to the onclick event handler. The compiler handles converting the delegate to an EventCallback, and will do some other things to make sure that the rendering process has enough information to render the correct target component. As a result an explicit call to StateHasChanged in the ShowMessage event handler isn’t necessary.

By using the EventCallback<> type OnClick handler can now also be asynchronous without any additional code changes to MyButton:

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessageAsync" />

@function {
    string text;

    async Task ShowMessageAsync(UIMouseEventArgs e)
    {
        await Task.Yield(); 
        text = "Hello, world!";
    }
}

We recommend using EventCallback and EventCallback<T> when you define component parameters for event handling and binding. Use EventCallback<> where possible because it’s strongly typed and will provide better feedback to users of your component. Use EventCallback when there’s no value you will pass to the callback.

Note that consumers don’t have to write different code when using a component because of EventCallback. The same event handling code should still work, while removing some thorny issues and improving the usability of your components.

Forms & validation

This preview release adds built-in components and infrastructure for handling forms and validation.

One of the benefits of using .NET for client-side web development is the ability to share the same implementation logic between the client and the server. Validation logic is a prime example. The new forms & validation support in Razor Components includes support for handling validation using data annotations, or you can plug in your preferred validation system.

For example, the following Person type defines validation logic using data annotations:

public class Person
{
    [Required(ErrorMessage = "Enter a name")]
    [StringLength(10, ErrorMessage = "That name is too long")]
    public string Name { get; set; }

    [Range(0, 200, ErrorMessage = "Nobody is that old")]
    public int AgeInYears { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")]
    public bool AcceptsTerms { get; set; }
}

Here’s how you can create a validating form based on this Person model:

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p class="name">
        Name: <InputText bind-Value="@person.Name" />
    </p>
    <p class="age">
        Age (years): <InputNumber bind-Value="@person.AgeInYears" />
    </p>
    <p class="accepts-terms">
        Accepts terms: <InputCheckbox bind-Value="@person.AcceptsTerms" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@functions {
    Person person = new Person();

    void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

If you add this form to your app and run it you will get a basic form that automatically validates the field inputs when they are changed and when the form is submitted.

Validating form

There are quite a few things going on here, so let’s break it down piece by piece:

  • The form is defined using the new EditForm component. The EditForm sets up an EditContext as a cascading value that tracks metadata about the edit process (e.g. what’s been modified, current validation messages, etc.). The EditForm also provides convenient events for valid and invalid submits (OnValidSubmit, OnInvalidSubmit). Or you can use OnSubmit directly if you want to trigger the validation yourself.
  • The DataAnnotationsValidator component attaches validation support using data annotations to the cascaded EditContext. Enabling support for validation using data annotations currently requires this explicit gesture, but we are considering making this the default behavior that you can then override.
  • Each of the form fields are defined using a set of built-in input components (InputText, InputNumber, InputCheckbox, InputSelect, etc.). These components provide default behavior for validating on edit and changing their CSS class to reflect the field state. Some of them have useful parsing logic (e.g., InputDate and InputNumber handle unparseable values gracefully by registering them as validation errors). The relevant ones also support nullability of the target field (e.g., int?).
  • The ValidationMessage component displays validation messages for a specific field.
  • The ValidationSummary component summarizes all validation messages (similar to the validation summary tag helper).

There are some limitations with the built-in input components that we expect to improve in future updates. For example, you can’t currently specify arbitrary attributes on the generate input tags. In the future, we plan to enable components that pass through all extra attributes. For now, you’ll need to build your own component subclasses to handle these cases.

Runtime compilation

Support for runtime compilation was removed from the ASP.NET Core shared framework in .NET Core 3.0, but you can now enable it by adding a package to your app.

To enable runtime compilation:

  1. Add a package reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview3-19153-02" />
    
  2. In Startup.ConfigureServices add a call to AddRazorRuntimeCompilation

    services.AddMvc().AddRazorRuntimeCompilation();
    

Worker Service Template

In 3.0.0-preview3 we are introducing a new template called ‘Worker Service’. This template is designed as a starting point for running long-running background processes like you might run as a Windows Service or Linux Daemon. Examples of this would be producing/consuming messages from a message queue or monitoring a file to process when it appears. It’s intended to provide the productivity features of ASP.NET Core such as Logging, DI, Configuration, etc without carrying any web dependencies.

Worker Service

In the coming days we will publish a few blog posts giving more walkthroughs on using the Worker template to get started. We will have dedicated posts about publishing as a Windows/Systemd service, running on ACI/AKS, as well as running as a WebJob.

Caveats

Whilst the intent is for the worker template to not have any dependencies on web technologies by default, in preview3 it still uses the Web SDK and is shown after you select ‘ASP.NET Core WebApplication’ in Visual Studio. This is temporary and will be changed in a future preview. This means that for preview3 you will see many options in VS that may not make sense, such as publishing your worker as a web app to IIS.

Angular template updated to Angular 7

The Angular template is now updated to Angular 7. We anticipate updating again to Angular 8 before .NET Core 3.0 ships a stable release.

Authentication for the Single Page Application templates

This release introduces support for authentication in our Angular and React templates. In this section we show how to create a new Angular or React template that allows us to authenticate users and access a protected API resource.

Our support for authenticating and authorizing users is powered behind the scenes by IdentityServer, with some extensions we built to simplify the configuration experience for the scenarios we are targeting.

Note: In this post we showcase authentication support for Angular but the React template offers equivalent functionality.

Create a new Angular application

To create a new Angular application with authentication support we invoke the following command:

dotnet new angular -au Individual

This command creates a new ASP.NET Core application with a hosted client Angular application. The ASP.NET Core application includes an Identity Server instance already configured so that your Angular application can authenticate users and send HTTP requests against the protected resources in the ASP.NET Core application.

The authentication and authorization support is built as an Angular module that gets imported into your application and offers a suite of components and services to enhance the functionality of the main applicaiton module.

Run the application

To run the application simply execute the command below and open the browser in the url displayed on the console:

dotnet run
Hosting environment: Development
Content root path: C:\angularapp
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

SPA index

When we open the application we see the usual Home, Counter and Fetch data menu options and two new options: Register and Login. If we click on Register we get sent to the default Identity UI where (after running migrations and updating the database) we can register as a new user.

Register a new user

SPA register

After registering as a new user we get redirected back to the application where we can see that we are successfully authenticated

SPA logged in

Call an authenticated API

If we click on the Fetch data we can see the weather forecast data table

SPA fetch data

Protect an existing API

To protect an API on the server we simply need to use the [Authorize] attribute on the controller or action that we want to protect.

[Authorize]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
...
}

Require authentication for a client route.

To require the user be authenticated when visiting a page in the Angular application we apply the [AuthorizeGuard] to the route we are configuring.

import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ApiAuthorizationModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
    ])
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Get more details by visiting the docs page

This is a quick introduction to what our new authentication support for Single Page Applications has to offer. For more details check out the docs.

Endpoint Routing with SignalR Hubs

In 3.0.0-preview3 we are hooking SignalR hubs into the new Endpoint Routing feature recently released. SignalR hub wire-up was previously done explicitly:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

This meant developers would need to wire up controllers, Razor pages, and hubs in a variety of different places during startup, leading to a series of nearly-identical routing segments:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

app.UseRouting(routes =>
{
    routes.MapRazorPages();
});

Now, SignalR hubs can also be routed via endpoint routing, so you’ve got a one-stop place to route nearly everything in ASP.NET Core.

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapHub<ChatHub>("hubs/chat");
});

Long Polling for Java SignalR Client

We added long polling support to the Java client which enables it to establish connections even in environments that do not support WebSockets. This also gives you the ability to specifically select the long polling transport in your client apps.

gRPC Template

This preview release introduces a new template for building gRPC services with ASP.NET Core using a new gRPC framework we are building in collaboration with Google.

gRPC is a popular RPC (remote procedure call) framework that offers an opinionated contract-first approach to API development. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, and cancellation and timeouts.

gRPC template

The templates create two projects: a gRPC service hosted inside ASP.NET Core, and a console application to test it with.

gRPC solution

This is the first public preview of gRPC for ASP.NET Core and it doesn’t implement all of gRPC’s features, but we’re working hard to make the best gRPC experience for ASP.NET possible. Please try it out and give us feedback at grpc/grpc-dotnet on GitHub.

Stay tuned for future blog posts discussing gRPC for ASP.NET Core in more detail.

Give feedback

We hope you enjoy the new features in this preview release of ASP.NET Core! Please let us know what you think by filing issues on Github.

The post ASP.NET Core updates in .NET Core 3.0 Preview 3 appeared first on ASP.NET Blog.

Blazor 0.9.0 experimental release now available

$
0
0

Blazor 0.9.0 is now available! This release updates Blazor with the Razor Components improvements in .NET Core 3.0 Preview 3.

New Razor Component improvements now available to Blazor apps:

  • Improved event handling
  • Forms & validation

Checkout the ASP.NET Core 3.0 Preview 3 announcement for details on these improvements. See also the Blazor 0.9.0 release notes for additional details.

Note: The Blazor templates have not been updated to use the new .razor file extension for Razor Components in this release. This update will be done in a future release.

Get Blazor 0.9.0

To get started with Blazor 0.9.0 install the following:

  1. .NET Core 3.0 Preview 3 SDK (3.0.100-preview3-010431)
  2. Visual Studio 2019 (Preview 4 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor extension from the Visual Studio Marketplace.
  4. The Blazor templates on the command-line:

    dotnet new -i Microsoft.AspNetCore.Blazor.Templates::0.9.0-preview3-19154-02
    

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

Upgrade to Blazor 0.9.0

To upgrade your existing Blazor apps to Blazor 0.9.0 first make sure you’ve installed the prerequisites listed above.

To upgrade a Blazor 0.8.0 project to 0.9.0:

  • Update the Blazor packages and .NET CLI tool references to 0.9.0-preview3-19154-02.
  • Update the remaining Microsoft.AspNetCore.* packages to 3.0.0-preview3-19153-02.
  • Remove any usage of JSRuntime.Current and instead use dependency injection to get the current IJSRuntime instance and pass it through to where it is needed.

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

The post Blazor 0.9.0 experimental release now available appeared first on ASP.NET Blog.

Blazor 0.7.0 experimental release now available

$
0
0

Blazor 0.7.0 is now available! This release focuses on enabling component coordination across ancestor-descendent relationships. We've also added some improvements to the debugging experience.

Here's what's new in the Blazor 0.7.0 release:

  • Cascading values and parameters
  • Debugging improvements

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

Get Blazor 0.7.0

Install the following:

  1. .NET Core 2.1 SDK (2.1.500 or later).
  2. Visual Studio 2017 (15.9 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor Language Services extension from the Visual Studio Marketplace.
  4. 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.7.0

To upgrade a Blazor 0.6.0 project to 0.7.0:

  • Install the prerequisites listed above.
  • Update the Blazor packages and .NET CLI tool references to 0.7.0. The 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.7.0" />
        <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.7.0" />
        <DotNetCliToolReference Include="Microsoft.AspNetCore.Blazor.Cli" Version="0.7.0" />
    </ItemGroup>
    
    </Project>
    

That's it! You're now ready to try out the latest Blazor features.

Cascading values and parameters

Blazor components can accept parameters that can be used to flow data into a component and impact the component's rendering. Parameter values are provided from parent component to child component. Sometimes, however, it's inconvenient to flow data from an ancestor component to a descendent component, especially when there are many layers in between. Cascading values and parameters solve this problem by providing a convenient way for an ancestor component to provide a value that is then available to all descendent components. They also provide a great way for components to coordinate.

For example, if you wanted to provide some theme information for a specific part of your app you could flow the relevant styles and classes from component to component, but this would be tedious and cumbersome. Instead, a common ancestor component can provide the theme information as a cascading value that descendents can accept as a cascading parameter and then consume as needed.

Let's say the following ThemeInfo class specifies all of the theme information that you want to flow down the component hierarchy so that all of the buttons within that part of your app share the same look and feel:

public class ThemeInfo 
{
    public string ButtonClass { get; set; }
}

An ancestor component can provide a cascading value using the CascadingValue component. The CascadingValue component wraps a subtree of the component hierarchy and specifies a single value that will be available to all components within that subtree. For example, we could specify the theme info in our application layout as a cascading parameter for all components that make up the layout body like this:

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

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

@functions {
    ThemeInfo theme = new ThemeInfo { ButtonClass = "btn-success" };
}

To make use of cascading values, components can declare cascading parameters using the [CascadingParameter] attribute. Cascading values are bound to cascading parameters by type. In the following example the Counter component is modified to have a cascading parameter that binds to the ThemeInfo cascading value, which is then used to set the class for the button.

@page "/counter"

<h1>Counter</h1>

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

<button class="btn @ThemeInfo.ButtonClass" onclick="@IncrementCount">Click me</button>

@functions {
    int currentCount = 0;

    [CascadingParameter] protected ThemeInfo ThemeInfo { get; set; }

    void IncrementCount()
    {
        currentCount++;
    }
}

When we run the app we can see that the new style is applied:

Counter with cascading parameter

Cascading parameters also enable components to collaborate across the component hierarchy. For example, let's say you have a TabSet component that contains a number of Tab components, like this:

<TabSet>
    <Tab Title="First tab">
        <h4>First tab</h4>
        This is the first tab.
    </Tab>

    @if (showSecondTab)
    {
        <Tab Title="Second">
            <h4>Second tab</h4>
            You can toggle me.
        </Tab>
    }

    <Tab Title="Third">
        <h4>Third tab</h4>

        <label>
            <input type="checkbox" bind=@showSecondTab />
            Toggle second tab
        </label>
    </Tab>
</TabSet>

In this example the child Tab components are not explicitly passed as parameters to the TabSet. Instead they are simply part of the child content of the TabSet. But the TabSet still needs to know about each Tab so that it can render the headers and the active tab. To enable this coordination without requiring any specific wire up from the user, the TabSet component can provide itself as a cascading value that can then be picked up by the descendent Tab components:

In TabSet.cshtml

<!-- Display the tab headers -->
<CascadingValue Value=this>
    <ul class="nav nav-tabs">
        @ChildContent
    </ul>
</CascadingValue>

This allows the descendent Tab components to capture the containing TabSet as a cascading parameter, so they can add themselves to the TabSet and coordinate on which Tab is active:

In Tab.cshtml

[CascadingParameter] TabSet ContainerTabSet { get; set; }

Check out the full TabSet sample here.

Debugging improvements

In Blazor 0.5.0 we added some very preliminary support for debugging client-side Blazor apps in the browser. While this initial debugging support demonstrated that debugging .NET apps in the browser was possible, it was still a pretty rough experience. Blazor 0.7.0 picks up the latest runtime updates, which includes some fixes that makes the debugging experience more reliable. You can now more reliably set and remove breakpoints, and the reliability of step debugging has been improved.

Improved Blazor debugging

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

Razor support in Visual Studio Code now in Preview

$
0
0

Earlier this week we released a preview of support for working with Razor files (.cshtml) in the C# extension for Visual Studio Code (1.17.1). This initial release introduces C# completions, directive completions, and basic diagnostics (red squiggles for errors) for ASP.NET Core projects.

Prerequisites

To use this preview of Razor support in Visual Studio Code install the following:

If you already installed VS Code and the C# extension in the past, make sure you have updated to the latest versions of both.

Get started

To try out the new Razor tooling, create a new ASP.NET Core web app and then edit any Razor (.cshtml) file.

  1. Open Visual Studio Code
  2. Select Terminal > New Terminal
  3. In the new terminal run:

    dotnet new webapp -o WebApp1`
    code -r WebApp1
    
  4. Open About.cshtml

  5. Try out HTML completions

    HTML completions

  6. And Razor directive completions

    Directive completions

  7. And C# completions

    C# completions

  8. You also get diagnostics (red squiggles)

    C# diagnostics

Limitations and known issues

This is the first alpha release of the Razor tooling for Visual Studio Code, so there are a number of limitations and known issues:

  • Razor editing is currently only supported in ASP.NET Core projects (no support for ASP.NET projects or Blazor projects yet)
  • Support for tag helpers and formatting is not yet implemented
  • Limited support for colorization
  • Loss of HTML completions following C# less than (<) operator
  • Error squiggles misaligned for expressions near the start of a new line
  • Incorrect errors in Blazor projects for event bindings
  • Emmet based abbreviation expansion is not yet supported

Note that if you need to disable the Razor tooling for any reason:

  • Open the Visual Studio Code User Settings: File -> Preferences -> Settings
  • Search for "razor"
  • Check the "Razor: Disabled" checkbox

Feedback

Even though the functionality of Razor tooling is currently pretty limited, we are shipping this preview now so that we can start collecting feedback. Any issues or suggestions for the Razor tooling in Visual Studio Code should be reported on the https://github.com/aspnet/Razor.VSCode repo.

To help us diagnose any reported issues please provide the following information in the GitHub issue:

  1. Razor (cshtml) file content
  2. Generated C# code from the Razor CSharp output
    • Right-click inside your .cshtml file and select "Command Palette"
    • Search for and select "Razor: Show Razor CSharp"
  3. Verbose Razor log output
    • See instructions for capturing the Razor log output here
  4. OmniSharp log output
    • Open VS Code's "Output" pane
    • In the dropdown choose "OmniSharp Log"

What's next?

Next up we are working on tag helper support. This will include support for tag helper completions and IntelliSense. Once we have tag helper tooling support in place we can then start work on enabling Blazor tooling support as well. Follow our progress and join in the conversation on the https://github.com/aspnet/Razor.VSCode repo.

Thanks for trying out this early preview!

Announcing ASP.NET Core 2.2, available today!

$
0
0

I’m happy to announce that ASP.NET Core 2.2 is available as part of .NET Core 2.2 today!

How to get it

You can download the new .NET Core SDK (2.2.100) for your dev machine and build servers from the .NET Core 2.2 download page. New Windows Server hosting, runtime installers and binary archives are also available from this page for updating servers.

This release updates .NET Core, ASP.NET Core, and Entity Framework Core to version 2.2.0. The new SDK version is 2.2.100. Visual Studio requirements are as follows:

Visual Studio 2019 16.0 Preview 1, also available today, includes the .NET Core SDK 2.2.100 as an optional component.

What’s new?

The main theme for this ASP.NET Core release was to improve developer productivity and platform functionality with regard to building Web/HTTP APIs. As usual, we made some performance improvements as well. We’ve posted about these features as part of the preview releases and you as such you can read about them by following the links below:

Health Checks integration with BeatPulse

We’re happy to announce that the BeatPulse project now supports the new Health Checks API, which means you can easily add checks for dozens of popular systems and dependencies using their great support. Here’s a message from the BeatPulse team about their support for our new Health Checks API:

BeatPulse is a community driven project that was created to provide health checking mechanisms for systems, networking and a wide variety of services that are common within the enterprise, e.g. SqlServer, MySql,Postgress, Redis, Kafka and many more . When Microsoft announced ASP.NET Core Health Checks for the 2.2 roadmap, the BeatPulse team ported all the existing liveness packages and features to work with the new Microsoft Health Checks abstractions at the repository AspNetCore.Diagnostics.HealthChecks. Apart from all the health checking packages, the BeatPulse team also incorporates other features like pulse tracking (Application Insights and Prometheus), failure notifications and a UI interface were we can configure different monitored systems and have a global view of health status. This UI is available as a Docker image published in Docker Hub.

More coming soon

When we announced planning for ASP.NET Core 2.2, we mentioned a number of features that aren’t detailed above, including API Authorization with IdentityServer4, Open API (Swagger) driven client code generation, and the HTTP REPL command line tool. These features are still being worked on and aren’t quite ready for release, however we expect to make them available as add-ons in the coming months. Thanks for your patience while we complete these experiences and get them ready for you all to try out.

Migrating a project to ASP.NET Core 2.2

To migrate an ASP.NET Core project from 2.1 to 2.2, open the project’s .csproj file and change the value of the TargetFramework element to netcoreapp2.2. You do not need to do this if you’re targeting .NET Framework 4.x.

Finish by updating your NuGet package references to the latest stable versions. Note that projects targeting .NET Core (rather than .NET Framework) should not have a package version specified for the Microsoft.AspNetCore.App package reference as this will be managed automatically by the SDK. Doing so will now result in a build warning.

For more information on upgrading to ASP.NET Core 2.2 see here.

Support life cycle

ASP.NET Core 2.2 is the latest release in the “Current” .NET Core train. This represents the first release since the declaration of 2.1 LTS that reestablishes a separate LTS and Current train. The Current train is where new features, enhancements, and regular bug fixes are applied and is recommended for most customers. Note that both LTS and Current releases receive servicing updates for security and critical stability fixes. It is currently expected that 2.2 will the last non-servicing release in the 2.x life cycle, and as such customers not using an LTS release will need to migrate to 3.0 GA, within 3 months of its release in the second half of 2019 in order to remain supported.

Read more about the .NET Core support policy here.

Availability in Azure App Service

The .NET Core 2.2 SDK, runtime, and updated ASP.NET Core IIS Module are in the process of being deployed to Azure App Service regions around the world. We expect this to be completed before the end of December 2018.

Some regions may receive the updated runtime before the updated ASP.NET Core IIS Module (ANCM), which is required by default for projects targeting ASP.NET Core 2.2. It’s also a requirement for the new in-process hosting feature. If you receive startup errors after deploying to Azure App Service, try configuring your project to use the existing version of ANCM by setting the AspNetCoreModule property to the value “AspNetCoreModule”, e.g.:

<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>

Once the target region has been updated with the latest ANCM version, you can remove that property altogether and redeploy the application to have it switch to using the new ANCM.

This release also adds better 64-bit support for .NET Core in Azure App Service. If you’re running your ASP.NET Core application on .NET Core 2.2 with in-process hosting, you can simply enable the 64-bit option in the Azure Portal and the site will now run in a 64-bit process. For other information on how to run your ASP.NET Core application in a 64-bit process in Azure App Service with other configurations, see this article.

Giving feedback

As always, please provide us feedback by logging issues at https://github.com/aspnet/AspNetCore. We look forward to hearing from you!

Azure Hybrid Benefit for SQL Server

$
0
0

In my previous blog post I talked about how to migrate data from existing on-prem SQL Server instances to Azure SQL Database. If you haven’t heard SQL Server 2008 end of support is coming this summer, so it’s a good time to evaluate moving to an Azure SQL Database.

If you decide to try Azure, chances are you will not be able to immediately move 100% of your on-prem databases and relevant applications in one go. You’ll probably come up with a migration plan that spans weeks, months or even years. During the migration phase you will be spinning up new instances of Azure SQL Database and turning off on-prem SQL Server instances, but for a little bit of time there will be overlap.

To help manage the cost during such transitions we offer the Azure Hybrid Benefit. You can convert 1 core of SQL Enterprise edition to get up to 4 vCores of Azure SQL Database at a reduced rate. For example, if you have 4 core licenses of SQL Enterprise edition, you can receive up to 16 vCores of Azure SQL Database.

If you want to learn more check out the Azure Hybrid Benefit FAQ and don’t forget, if you have any questions around migrating your .NET applications to Azure you can always ask for free assistance. If you have any questions about this post just leave us a comment below.

The post Azure Hybrid Benefit for SQL Server appeared first on ASP.NET Blog.


ASP.NET Core updates in .NET Core 3.0 Preview 3

$
0
0

.NET Core 3.0 Preview 3 is now available and it includes a bunch of new updates to ASP.NET Core.

Here’s the list of what’s new in this preview:

  • Razor Components improvements:
    • Single project template
    • New .razor extension
    • Endpoint routing integration
    • Prerendering
    • Razor Components in Razor Class Libraries
    • Improved event handling
    • Forms & validation
  • Runtime compilation
  • Worker Service template
  • gRPC template
  • Angular template updated to Angular 7
  • Authentication for Single Page Applications
  • SignalR integration with endpoint routing
  • SignalR Java client support for long polling

Please see the release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET Core 3.0 Preview 3 install the .NET Core 3.0 Preview 3 SDK

If you’re on Windows using Visual Studio, you’ll also want to install the latest preview of Visual Studio 2019.

  • Note: To use use this preview of .NET Core 3.0 with the release channel of Visual Studio 2019, you will need to enable the option to use previews of the .NET Core SDK by going to Tools > Options > Projects and Solutions > .NET Core > Use previews of the .NET Core SDK

Upgrade an existing project

To upgrade an existing an ASP.NET Core app to .NET Core 3.0 Preview 3, follow the migrations steps in the ASP.NET Core docs.

Please also see the full list of breaking changes in ASP.NET Core 3.0.

Razor Components improvements

In the previous preview, we introduced Razor Components as a new way to build interactive client-side web UI with ASP.NET Core. This section covers the various improvements we’ve made to Razor Components in this preview update.

Single project template

The Razor Components project template is now a single project instead of two projects in the same solution. The authored Razor Components live directly in the ASP.NET Core app that hosts them. The same ASP.NET Core project can contain Razor Components, Pages, and Views. The Razor Components template also has HTTPS enabled by default like the other ASP.NET Core web app templates.

New .razor extension

Razor Components are authored using Razor syntax, but are compiled differently than Razor Pages and Views. To clarify which Razor files should be compiled as Razor Components we’ve introduced a new file extension: .razor. In the Razor Components template all component files now use the .razor extension. Razor Pages and Views still use the .cshtml extension.

Razor Components can still be authored using the .cshtml file extension as long as those files are identified as Razor Component files using the _RazorComponentInclude MSBuild property. For example, the Razor Component template in this release specifies that all .cshtml files under the Components folder should be treated as Razor Components.

<_RazorComponentInclude>Components\**\*.cshtml</_RazorComponentInclude>

Please note that there are a number of limitations with .razor files in this release. Please refer to the release notes for the list of known issues and available workarounds.

Endpoint routing integration

Razor Components are now integrated into ASP.NET Core’s new Endpoint Routing system. To enable Razor Components support in your application, use MapComponentHub<TComponent> within your routing configuration. For example,

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapComponentHub<App>("app");
});

This configures the application to accept incoming connections for interactive Razor Components, and specifies that the root component App should be rendered within a DOM element matching the selector app.

Prerendering

The Razor Components project template now does server-side prerendering by default. This means that when a user navigates to your application, the server will perform an initial render of your Razor Components and deliver the result to their browser as plain static HTML. Then, the browser will reconnect to the server via SignalR and switch the Razor Components into a fully interactive mode. This two-phase delivery is beneficial because:

  • It improves the perceived performance of the site, because the UI can appear sooner, without waiting to make any WebSocket connections or even running any client-side script. This makes a bigger difference for users on slow connections, such as 2G/3G mobiles.
  • It can make your application easily crawlable by search engines.

For users on faster connections, such as intranet users, this feature has less impact because the UI should appear near-instantly regardless.

To set up prerendering, the Razor Components project template no longer has a static HTML file. Instead a single Razor Page, /Pages/Index.cshtml, is used to prerender the app content using the Html.RenderComponentAsync<TComponent>() HTML helper. The page also references the components.server.js script to set up the SignalR connection after the content has been prerendered and downloaded. And because this is a Razor Page, features like the environment tag helper just work.

Index.cshtml

@page "{*clientPath}"
<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
    <app>@(await Html.RenderComponentAsync<App>())</app>

    <script src="_framework/components.server.js"></script>
</body>
</html>

Besides the app loading faster, you can see that prerendering is happening by looking at the downloaded HTML source in the browser dev tools. The Razor Components are fully rendered in the HTML.

Razor Components in Razor Class Libraries

You can now add Razor Components to Razor Class Libraries and reference them from ASP.NET Core projects using Razor Components.

To create reusable Razor Components in a Razor Class Library:

  1. Create an Razor Components app:

    dotnet new razorcomponents -o RazorComponentsApp1
    
  2. Create a new Razor Class Library

    dotnet new razorclasslib -o RazorClassLib1
    
  3. Add a Component1.razor file to the Razor Class Library

Component1.razor

<h1>Component1</h1>

<p>@message</p>

@functions {
    string message = "Hello from a Razor Class Library"!;
}
  1. Reference the Razor Class Library from an ASP.NET Core app using Razor Components:

    dotnet add RazorComponentsApp1 reference RazorClassLib1
    
  2. In the Razor Components app, import all components from the Razor Class Library using the @addTagHelper directive and then use Component1 in the app:

Index.razor

@page "/"
@addTagHelper *, RazorClassLib1

<h1>Hello, world!</h1>

Welcome to your new app.

<Component1 />

Note that Razor Class Libraries are not compatible with Blazor apps in this release. Also, Razor Class Libraries do not yet support static assets. To create components in a library that can be shared with Blazor and Razor Components apps you still need to use a Blazor Class Library. This is something we expect to address in a future update.

Improved event handling

The new EventCallback and EventCallback<> types make defining component callbacks much more straightforward. For example consider the following two components:

MyButton.razor

<button onclick="@OnClick">Click here and see what happens!</button>

@functions {
    [Parameter] EventCallback<UIMouseEventArgs> OnClick { get; set; }
}

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessage" />

@function {
    string text;

    void ShowMessage(UIMouseEventArgs e)
    {
        text = "Hello, world!";
    }
}

The OnClick callback is of type EventCallback<UIMouseEventArgs> (instead of Action<UIMouseEventArgs>), which MyButton passes off directly to the onclick event handler. The compiler handles converting the delegate to an EventCallback, and will do some other things to make sure that the rendering process has enough information to render the correct target component. As a result an explicit call to StateHasChanged in the ShowMessage event handler isn’t necessary.

By using the EventCallback<> type OnClick handler can now also be asynchronous without any additional code changes to MyButton:

UsesMyButton.razor

<div>@text</div>

<MyButton OnClick="ShowMessageAsync" />

@function {
    string text;

    async Task ShowMessageAsync(UIMouseEventArgs e)
    {
        await Task.Yield(); 
        text = "Hello, world!";
    }
}

We recommend using EventCallback and EventCallback<T> when you define component parameters for event handling and binding. Use EventCallback<> where possible because it’s strongly typed and will provide better feedback to users of your component. Use EventCallback when there’s no value you will pass to the callback.

Note that consumers don’t have to write different code when using a component because of EventCallback. The same event handling code should still work, while removing some thorny issues and improving the usability of your components.

Forms & validation

This preview release adds built-in components and infrastructure for handling forms and validation.

One of the benefits of using .NET for client-side web development is the ability to share the same implementation logic between the client and the server. Validation logic is a prime example. The new forms & validation support in Razor Components includes support for handling validation using data annotations, or you can plug in your preferred validation system.

For example, the following Person type defines validation logic using data annotations:

public class Person
{
    [Required(ErrorMessage = "Enter a name")]
    [StringLength(10, ErrorMessage = "That name is too long")]
    public string Name { get; set; }

    [Range(0, 200, ErrorMessage = "Nobody is that old")]
    public int AgeInYears { get; set; }

    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")]
    public bool AcceptsTerms { get; set; }
}

Here’s how you can create a validating form based on this Person model:

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p class="name">
        Name: <InputText bind-Value="@person.Name" />
    </p>
    <p class="age">
        Age (years): <InputNumber bind-Value="@person.AgeInYears" />
    </p>
    <p class="accepts-terms">
        Accepts terms: <InputCheckbox bind-Value="@person.AcceptsTerms" />
    </p>

    <button type="submit">Submit</button>
</EditForm>

@functions {
    Person person = new Person();

    void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

If you add this form to your app and run it you will get a basic form that automatically validates the field inputs when they are changed and when the form is submitted.

Validating form

There are quite a few things going on here, so let’s break it down piece by piece:

  • The form is defined using the new EditForm component. The EditForm sets up an EditContext as a cascading value that tracks metadata about the edit process (e.g. what’s been modified, current validation messages, etc.). The EditForm also provides convenient events for valid and invalid submits (OnValidSubmit, OnInvalidSubmit). Or you can use OnSubmit directly if you want to trigger the validation yourself.
  • The DataAnnotationsValidator component attaches validation support using data annotations to the cascaded EditContext. Enabling support for validation using data annotations currently requires this explicit gesture, but we are considering making this the default behavior that you can then override.
  • Each of the form fields are defined using a set of built-in input components (InputText, InputNumber, InputCheckbox, InputSelect, etc.). These components provide default behavior for validating on edit and changing their CSS class to reflect the field state. Some of them have useful parsing logic (e.g., InputDate and InputNumber handle unparseable values gracefully by registering them as validation errors). The relevant ones also support nullability of the target field (e.g., int?).
  • The ValidationMessage component displays validation messages for a specific field.
  • The ValidationSummary component summarizes all validation messages (similar to the validation summary tag helper).

There are some limitations with the built-in input components that we expect to improve in future updates. For example, you can’t currently specify arbitrary attributes on the generate input tags. In the future, we plan to enable components that pass through all extra attributes. For now, you’ll need to build your own component subclasses to handle these cases.

Runtime compilation

Support for runtime compilation was removed from the ASP.NET Core shared framework in .NET Core 3.0, but you can now enable it by adding a package to your app.

To enable runtime compilation:

  1. Add a package reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview3-19153-02" />
    
  2. In Startup.ConfigureServices add a call to AddRazorRuntimeCompilation

    services.AddMvc().AddRazorRuntimeCompilation();
    

Worker Service Template

In 3.0.0-preview3 we are introducing a new template called ‘Worker Service’. This template is designed as a starting point for running long-running background processes like you might run as a Windows Service or Linux Daemon. Examples of this would be producing/consuming messages from a message queue or monitoring a file to process when it appears. It’s intended to provide the productivity features of ASP.NET Core such as Logging, DI, Configuration, etc without carrying any web dependencies.

Worker Service

In the coming days we will publish a few blog posts giving more walkthroughs on using the Worker template to get started. We will have dedicated posts about publishing as a Windows/Systemd service, running on ACI/AKS, as well as running as a WebJob.

Caveats

Whilst the intent is for the worker template to not have any dependencies on web technologies by default, in preview3 it still uses the Web SDK and is shown after you select ‘ASP.NET Core WebApplication’ in Visual Studio. This is temporary and will be changed in a future preview. This means that for preview3 you will see many options in VS that may not make sense, such as publishing your worker as a web app to IIS.

Angular template updated to Angular 7

The Angular template is now updated to Angular 7. We anticipate updating again to Angular 8 before .NET Core 3.0 ships a stable release.

Authentication for the Single Page Application templates

This release introduces support for authentication in our Angular and React templates. In this section we show how to create a new Angular or React template that allows us to authenticate users and access a protected API resource.

Our support for authenticating and authorizing users is powered behind the scenes by IdentityServer, with some extensions we built to simplify the configuration experience for the scenarios we are targeting.

Note: In this post we showcase authentication support for Angular but the React template offers equivalent functionality.

Create a new Angular application

To create a new Angular application with authentication support we invoke the following command:

dotnet new angular -au Individual

This command creates a new ASP.NET Core application with a hosted client Angular application. The ASP.NET Core application includes an Identity Server instance already configured so that your Angular application can authenticate users and send HTTP requests against the protected resources in the ASP.NET Core application.

The authentication and authorization support is built as an Angular module that gets imported into your application and offers a suite of components and services to enhance the functionality of the main applicaiton module.

Run the application

To run the application simply execute the command below and open the browser in the url displayed on the console:

dotnet run
Hosting environment: Development
Content root path: C:\angularapp
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

SPA index

When we open the application we see the usual Home, Counter and Fetch data menu options and two new options: Register and Login. If we click on Register we get sent to the default Identity UI where (after running migrations and updating the database) we can register as a new user.

Register a new user

SPA register

After registering as a new user we get redirected back to the application where we can see that we are successfully authenticated

SPA logged in

Call an authenticated API

If we click on the Fetch data we can see the weather forecast data table

SPA fetch data

Protect an existing API

To protect an API on the server we simply need to use the [Authorize] attribute on the controller or action that we want to protect.

[Authorize]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
...
}

Require authentication for a client route.

To require the user be authenticated when visiting a page in the Angular application we apply the [AuthorizeGuard] to the route we are configuring.

import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ApiAuthorizationModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
    ])
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Get more details by visiting the docs page

This is a quick introduction to what our new authentication support for Single Page Applications has to offer. For more details check out the docs.

Endpoint Routing with SignalR Hubs

In 3.0.0-preview3 we are hooking SignalR hubs into the new Endpoint Routing feature recently released. SignalR hub wire-up was previously done explicitly:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

This meant developers would need to wire up controllers, Razor pages, and hubs in a variety of different places during startup, leading to a series of nearly-identical routing segments:

app.UseSignalR(routes =>
{
    routes.MapHub<ChatHub>("hubs/chat");
});

app.UseRouting(routes =>
{
    routes.MapRazorPages();
});

Now, SignalR hubs can also be routed via endpoint routing, so you’ve got a one-stop place to route nearly everything in ASP.NET Core.

app.UseRouting(routes =>
{
    routes.MapRazorPages();
    routes.MapHub<ChatHub>("hubs/chat");
});

Long Polling for Java SignalR Client

We added long polling support to the Java client which enables it to establish connections even in environments that do not support WebSockets. This also gives you the ability to specifically select the long polling transport in your client apps.

gRPC Template

This preview release introduces a new template for building gRPC services with ASP.NET Core using a new gRPC framework we are building in collaboration with Google.

gRPC is a popular RPC (remote procedure call) framework that offers an opinionated contract-first approach to API development. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, and cancellation and timeouts.

gRPC template

The templates create two projects: a gRPC service hosted inside ASP.NET Core, and a console application to test it with.

gRPC solution

This is the first public preview of gRPC for ASP.NET Core and it doesn’t implement all of gRPC’s features, but we’re working hard to make the best gRPC experience for ASP.NET possible. Please try it out and give us feedback at grpc/grpc-dotnet on GitHub.

Stay tuned for future blog posts discussing gRPC for ASP.NET Core in more detail.

Give feedback

We hope you enjoy the new features in this preview release of ASP.NET Core! Please let us know what you think by filing issues on Github.

The post ASP.NET Core updates in .NET Core 3.0 Preview 3 appeared first on ASP.NET Blog.

Blazor 0.9.0 experimental release now available

$
0
0

Blazor 0.9.0 is now available! This release updates Blazor with the Razor Components improvements in .NET Core 3.0 Preview 3.

New Razor Component improvements now available to Blazor apps:

  • Improved event handling
  • Forms & validation

Checkout the ASP.NET Core 3.0 Preview 3 announcement for details on these improvements. See also the Blazor 0.9.0 release notes for additional details.

Note: The Blazor templates have not been updated to use the new .razor file extension for Razor Components in this release. This update will be done in a future release.

Get Blazor 0.9.0

To get started with Blazor 0.9.0 install the following:

  1. .NET Core 3.0 Preview 3 SDK (3.0.100-preview3-010431)
  2. Visual Studio 2019 (Preview 4 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor extension from the Visual Studio Marketplace.
  4. The Blazor templates on the command-line:

    dotnet new -i Microsoft.AspNetCore.Blazor.Templates::0.9.0-preview3-19154-02
    

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

Upgrade to Blazor 0.9.0

To upgrade your existing Blazor apps to Blazor 0.9.0 first make sure you’ve installed the prerequisites listed above.

To upgrade a Blazor 0.8.0 project to 0.9.0:

  • Update the Blazor packages and .NET CLI tool references to 0.9.0-preview3-19154-02.
  • Update the remaining Microsoft.AspNetCore.* packages to 3.0.0-preview3-19153-02.
  • Remove any usage of JSRuntime.Current and instead use dependency injection to get the current IJSRuntime instance and pass it through to where it is needed.

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

The post Blazor 0.9.0 experimental release now available appeared first on ASP.NET Blog.

Re-reading ASP.Net Core request bodies with EnableBuffering()

$
0
0

In some scenarios there’s a need to read the request body multiple times. Some examples include

  • Logging the raw requests to replay in load test environment
  • Middleware that read the request body multiple times to process it

Usually Request.Body does not support rewinding, so it can only be read once. A straightforward solution is to save a copy of the stream in another stream that supports seeking so the content can be read multiple times from the copy.

In ASP.NET framework it was possible to read the body of an HTTP request multiple times using HttpRequest.GetBufferedInputStream method. However, in ASP.NET Core a different approach must be used.

In ASP.NET Core 2.1 we added an extension method EnableBuffering() for HttpRequest. This is the suggested way to enable request body for multiple reads. Here is an example usage in the InvokeAsync() method of a custom ASP.NET middleware:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    context.Request.EnableBuffering();

    // Leave the body open so the next middleware can read it.
    using (var reader = new StreamReader(
        context.Request.Body,
        encoding: Encoding.UTF8,
        detectEncodingFromByteOrderMarks: false,
        bufferSize: bufferSize,
        leaveOpen: true))
    {
        var body = await reader.ReadToEndAsync();
        // Do some processing with body…

        // Reset the request body stream position so the next middleware can read it
        context.Request.Body.Position = 0;
    }

    // Call the next delegate/middleware in the pipeline
    await next(context);
}

The backing FileBufferingReadStream uses memory stream of a certain size first then falls back to a temporary file stream. By default the size of the memory stream is 30KB. There are also other EnableBuffering() overloads that allow specifying a different threshold, and/or a limit for the total size:

public static void EnableBuffering(this HttpRequest request, int bufferThreshold)

public static void EnableBuffering(this HttpRequest request, long bufferLimit)

public static void EnableBuffering(this HttpRequest request, int bufferThreshold, long bufferLimit)

For example, a call of

context.Request.EnableBuffering(bufferThreshold: 1024 * 45, bufferLimit: 1024 * 100);

enables a read buffer with limit of 100KB. Data is buffered in memory until the content exceeds 45KB, then it’s moved to a temporary file. By default there’s no limit on the buffer size but if there’s one specified and the content of request body exceeds the limit, an System.IOException will be thrown.

These overloads offer flexibility if there’s a need to fine-tune the buffering behaviors. Just keep in mind that:

  • Even though the memory stream is rented from a pool, it still has memory cost associated with it.
  • After the read is over the bufferThreshold the performance will be slower since a file stream will be used.

The post Re-reading ASP.Net Core request bodies with EnableBuffering() appeared first on ASP.NET Blog.

Blazor 0.7.0 experimental release now available

$
0
0

Blazor 0.7.0 is now available! This release focuses on enabling component coordination across ancestor-descendent relationships. We've also added some improvements to the debugging experience.

Here's what's new in the Blazor 0.7.0 release:

  • Cascading values and parameters
  • Debugging improvements

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

Get Blazor 0.7.0

Install the following:

  1. .NET Core 2.1 SDK (2.1.500 or later).
  2. Visual Studio 2017 (15.9 or later) with the ASP.NET and web development workload selected.
  3. The latest Blazor Language Services extension from the Visual Studio Marketplace.
  4. 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.7.0

To upgrade a Blazor 0.6.0 project to 0.7.0:

  • Install the prerequisites listed above.
  • Update the Blazor packages and .NET CLI tool references to 0.7.0. The 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.7.0" />
        <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="0.7.0" />
        <DotNetCliToolReference Include="Microsoft.AspNetCore.Blazor.Cli" Version="0.7.0" />
    </ItemGroup>
    
    </Project>
    

That's it! You're now ready to try out the latest Blazor features.

Cascading values and parameters

Blazor components can accept parameters that can be used to flow data into a component and impact the component's rendering. Parameter values are provided from parent component to child component. Sometimes, however, it's inconvenient to flow data from an ancestor component to a descendent component, especially when there are many layers in between. Cascading values and parameters solve this problem by providing a convenient way for an ancestor component to provide a value that is then available to all descendent components. They also provide a great way for components to coordinate.

For example, if you wanted to provide some theme information for a specific part of your app you could flow the relevant styles and classes from component to component, but this would be tedious and cumbersome. Instead, a common ancestor component can provide the theme information as a cascading value that descendents can accept as a cascading parameter and then consume as needed.

Let's say the following ThemeInfo class specifies all of the theme information that you want to flow down the component hierarchy so that all of the buttons within that part of your app share the same look and feel:

public class ThemeInfo 
{
    public string ButtonClass { get; set; }
}

An ancestor component can provide a cascading value using the CascadingValue component. The CascadingValue component wraps a subtree of the component hierarchy and specifies a single value that will be available to all components within that subtree. For example, we could specify the theme info in our application layout as a cascading parameter for all components that make up the layout body like this:

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

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

@functions {
    ThemeInfo theme = new ThemeInfo { ButtonClass = "btn-success" };
}

To make use of cascading values, components can declare cascading parameters using the [CascadingParameter] attribute. Cascading values are bound to cascading parameters by type. In the following example the Counter component is modified to have a cascading parameter that binds to the ThemeInfo cascading value, which is then used to set the class for the button.

@page "/counter"

<h1>Counter</h1>

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

<button class="btn @ThemeInfo.ButtonClass" onclick="@IncrementCount">Click me</button>

@functions {
    int currentCount = 0;

    [CascadingParameter] protected ThemeInfo ThemeInfo { get; set; }

    void IncrementCount()
    {
        currentCount++;
    }
}

When we run the app we can see that the new style is applied:

Counter with cascading parameter

Cascading parameters also enable components to collaborate across the component hierarchy. For example, let's say you have a TabSet component that contains a number of Tab components, like this:

<TabSet>
    <Tab Title="First tab">
        <h4>First tab</h4>
        This is the first tab.
    </Tab>

    @if (showSecondTab)
    {
        <Tab Title="Second">
            <h4>Second tab</h4>
            You can toggle me.
        </Tab>
    }

    <Tab Title="Third">
        <h4>Third tab</h4>

        <label>
            <input type="checkbox" bind=@showSecondTab />
            Toggle second tab
        </label>
    </Tab>
</TabSet>

In this example the child Tab components are not explicitly passed as parameters to the TabSet. Instead they are simply part of the child content of the TabSet. But the TabSet still needs to know about each Tab so that it can render the headers and the active tab. To enable this coordination without requiring any specific wire up from the user, the TabSet component can provide itself as a cascading value that can then be picked up by the descendent Tab components:

In TabSet.cshtml

<!-- Display the tab headers -->
<CascadingValue Value=this>
    <ul class="nav nav-tabs">
        @ChildContent
    </ul>
</CascadingValue>

This allows the descendent Tab components to capture the containing TabSet as a cascading parameter, so they can add themselves to the TabSet and coordinate on which Tab is active:

In Tab.cshtml

[CascadingParameter] TabSet ContainerTabSet { get; set; }

Check out the full TabSet sample here.

Debugging improvements

In Blazor 0.5.0 we added some very preliminary support for debugging client-side Blazor apps in the browser. While this initial debugging support demonstrated that debugging .NET apps in the browser was possible, it was still a pretty rough experience. Blazor 0.7.0 picks up the latest runtime updates, which includes some fixes that makes the debugging experience more reliable. You can now more reliably set and remove breakpoints, and the reliability of step debugging has been improved.

Improved Blazor debugging

Give feedback

We hope you enjoy this latest preview release of Blazor. As with previous releases, your feedback is important to us. If you run into issues or have questions while trying out Blazor, 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 let us know what you think by taking our in-product survey. 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!

Razor support in Visual Studio Code now in Preview

$
0
0

Earlier this week we released a preview of support for working with Razor files (.cshtml) in the C# extension for Visual Studio Code (1.17.1). This initial release introduces C# completions, directive completions, and basic diagnostics (red squiggles for errors) for ASP.NET Core projects.

Prerequisites

To use this preview of Razor support in Visual Studio Code install the following:

If you already installed VS Code and the C# extension in the past, make sure you have updated to the latest versions of both.

Get started

To try out the new Razor tooling, create a new ASP.NET Core web app and then edit any Razor (.cshtml) file.

  1. Open Visual Studio Code
  2. Select Terminal > New Terminal
  3. In the new terminal run:

    dotnet new webapp -o WebApp1`
    code -r WebApp1
    
  4. Open About.cshtml

  5. Try out HTML completions

    HTML completions

  6. And Razor directive completions

    Directive completions

  7. And C# completions

    C# completions

  8. You also get diagnostics (red squiggles)

    C# diagnostics

Limitations and known issues

This is the first alpha release of the Razor tooling for Visual Studio Code, so there are a number of limitations and known issues:

  • Razor editing is currently only supported in ASP.NET Core projects (no support for ASP.NET projects or Blazor projects yet)
  • Support for tag helpers and formatting is not yet implemented
  • Limited support for colorization
  • Loss of HTML completions following C# less than (<) operator
  • Error squiggles misaligned for expressions near the start of a new line
  • Incorrect errors in Blazor projects for event bindings
  • Emmet based abbreviation expansion is not yet supported

Note that if you need to disable the Razor tooling for any reason:

  • Open the Visual Studio Code User Settings: File -> Preferences -> Settings
  • Search for "razor"
  • Check the "Razor: Disabled" checkbox

Feedback

Even though the functionality of Razor tooling is currently pretty limited, we are shipping this preview now so that we can start collecting feedback. Any issues or suggestions for the Razor tooling in Visual Studio Code should be reported on the https://github.com/aspnet/Razor.VSCode repo.

To help us diagnose any reported issues please provide the following information in the GitHub issue:

  1. Razor (cshtml) file content
  2. Generated C# code from the Razor CSharp output
    • Right-click inside your .cshtml file and select "Command Palette"
    • Search for and select "Razor: Show Razor CSharp"
  3. Verbose Razor log output
    • See instructions for capturing the Razor log output here
  4. OmniSharp log output
    • Open VS Code's "Output" pane
    • In the dropdown choose "OmniSharp Log"

What's next?

Next up we are working on tag helper support. This will include support for tag helper completions and IntelliSense. Once we have tag helper tooling support in place we can then start work on enabling Blazor tooling support as well. Follow our progress and join in the conversation on the https://github.com/aspnet/Razor.VSCode repo.

Thanks for trying out this early preview!

Viewing all 7144 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>