Skip to content

Commit 21b1757

Browse files
authored
Added samples for intro session (#72)
* Added samples for intro session * Updated with content from live stream
1 parent 0051109 commit 21b1757

File tree

104 files changed

+4352
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

104 files changed

+4352
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# Session 0301 - Introducing Blazor
2+
3+
[Blazor](https://blazor.net) is the new web user-interface framework from the .NET team that allows you to build component-based, event-driven applications that run in the browser with Web Assembly or on a web server with ASP.NET Core. Web Assembly delivery of the application means all content is sent to the client for execution. Server-side execution means the same application runs on ASP.NET Core and rendered content is delivered to the browser with updates managed and delivered with a SignalR connection between browser and server. With both models, you can use the full .NET and C# development toolset to build end-to-end applications that run in the browser.
4+
5+
Blazor is built with web standards in mind, and works in all modern browsers (including mobile browsers) that fully support the HTML5 specification.
6+
7+
All of the tools you need to get started with Blazor ship with the [.NET SDK](https://get.dot.net) (version 3.1 and later). You will have great editor support in Visual Studio 2019 and Visual Studio Code. The included demos are built to work with .NET 5.
8+
9+
## Who's Using Blazor?
10+
11+
Check out the Customer Story for [The Postage](https://customers.microsoft.com/story/1338933582129668706-the-postage-professional-services-azure) where they use Blazor to power the web applications:
12+
13+
“Using Blazor gave our small development team a huge advantage, enabling the same people to build both the front end and the back end of our solution. We were intimately familiar with the back-end services we had built, so we were able to use them on the front end much faster. I’d estimate that it cut our development time in half.”
14+
15+
[![The Postage Customer Story](img/ThePostage.png)](https://customers.microsoft.com/story/1338933582129668706-the-postage-professional-services-azure)
16+
17+
## Get Started
18+
19+
Build an app that uses Web Assembly with the default template and explore the folders. Use the command line:
20+
21+
`dotnet new blazorwasm -o FirstWebAssembly`
22+
23+
This creates a new application using the Blazor Web Assembly model and places the **o**utput in a folder called `FirstWebAssembly`
24+
25+
Explore the folders
26+
- `Pages` is where Blazor application pages live and are written with Razor templates
27+
- `Shared` is where common Razor templates that will be re-used in the application reside. You'll find layout and component files here
28+
- `wwwroot` is the ___location containing those static web assets like images, CSS, and JavaScript
29+
30+
Other files to note:
31+
- `Program.cs` is the starting point for the application. Blazor application configuration starts here
32+
- `App.razor` is the root component that starts the web rendering and contains the Blazor router
33+
- `_Imports.razor` contains shared directives to be used in Razor templates like `@using` statements
34+
- `wwwroot/index.html` is the static HTML page that browsers will read and start using Blazor
35+
36+
Run the application with:
37+
38+
`dotnet run`
39+
40+
Browse to https://localhost:5001 to see the application running. Be sure to check the network tab, console, and application storage to see where Blazor is interacting.
41+
42+
## WebAssembly with ASP.NET Core Hosted
43+
44+
Very similar to the Web Assembly template, this version of the project template has a complete ASP.NET Core webserver that will assist in rendering and delivering data to the browser.
45+
46+
`dotnet new blazorwasm --hosted -o HostedWebAssembly`
47+
48+
Content is now delivered in 3 applications: Client, Server, and Shared.
49+
50+
- **Client** is the Blazor Web Assembly application just like we saw previously
51+
- **Server** is the ASP.NET Core application that hosts the server-side Api and will deliver the HTML of the Blazor application.
52+
- **Shared** contains classes that are used by both the client and server projects
53+
54+
Inspect the `Server/Startup.cs` file to see how the Blazor Web Assembly app's `index.html` is referenced as a ___location to start the application.
55+
56+
```c#
57+
...
58+
app.UseHttpsRedirection();
59+
app.UseBlazorFrameworkFiles();
60+
app.UseStaticFiles();
61+
62+
app.UseRouting();
63+
64+
app.UseEndpoints(endpoints =>
65+
{
66+
endpoints.MapRazorPages();
67+
endpoints.MapControllers();
68+
endpoints.MapFallbackToFile("index.html");
69+
});
70+
```
71+
72+
Run the application and check the Fetch Data sample to see how the application fetches data from the ASP.NET Core `Server` application.
73+
74+
## Server-Side Application
75+
76+
This type of Blazor application runs completely on the server and delivers user-interface updates through a SignalR channel. Start a new application with:
77+
78+
`dotnet new blazorserver -o FirstServer`
79+
80+
This is an ASP.NET Core application and has a few enhancements to support Blazor. Look at the `Startup.cs` class to see the enhancements to support the framework.
81+
82+
The contents of the Pages and Shared folders are similar to the Web Assembly app, with the addition of the `_Host.cshtml` file that replaces the `wwwroot/index.html` file that we saw previously.
83+
84+
Run this application and watch the interactions with the server using your browser developer tools. Pay particular attention to the establishment of the websockets connection. All .NET processing and painting of the same components presented on screen is managed by the server.
85+
86+
![Browser Developer Tools - WebSocket messages](img/Sockets.png)
87+
88+
## Interact with C# and HTML
89+
90+
- @bind feature
91+
- Write code in the @code block
92+
- Handle the OnInitialized event
93+
94+
## Pages are components
95+
96+
- @page directive
97+
- Reference other pages using tags
98+
99+
## Inject HTTP client
100+
101+
- The FetchData samples across the various application models
Loading
Loading
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
2+
<Found Context="routeData">
3+
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
4+
</Found>
5+
<NotFound>
6+
<LayoutView Layout="@typeof(MainLayout)">
7+
<p>Sorry, there's nothing at this address.</p>
8+
</LayoutView>
9+
</NotFound>
10+
</Router>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System;
2+
3+
namespace FirstServer.Data
4+
{
5+
public class WeatherForecast
6+
{
7+
public DateTime Date { get; set; }
8+
9+
public int TemperatureC { get; set; }
10+
11+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12+
13+
public string Summary { get; set; }
14+
}
15+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Linq;
3+
using System.Threading.Tasks;
4+
5+
namespace FirstServer.Data
6+
{
7+
public class WeatherForecastService
8+
{
9+
private static readonly string[] Summaries = new[]
10+
{
11+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
12+
};
13+
14+
public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
15+
{
16+
var rng = new Random();
17+
return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
18+
{
19+
Date = startDate.AddDays(index),
20+
TemperatureC = rng.Next(-20, 55),
21+
Summary = Summaries[rng.Next(Summaries.Length)]
22+
}).ToArray());
23+
}
24+
}
25+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net5.0</TargetFramework>
5+
</PropertyGroup>
6+
7+
</Project>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@page "/counter"
2+
3+
<h1>Counter</h1>
4+
5+
<p>Current count: @currentCount</p>
6+
7+
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
8+
9+
@code {
10+
private int currentCount = 0;
11+
12+
[Parameter] public int Step { get; set; } = 1;
13+
14+
private void IncrementCount()
15+
{
16+
currentCount+=Step;
17+
}
18+
19+
protected override async Task OnParametersSetAsync() {
20+
21+
Console.WriteLine($"Step = {Step}");
22+
23+
}
24+
25+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
@page
2+
@model FirstServer.Pages.ErrorModel
3+
4+
<!DOCTYPE html>
5+
<html>
6+
7+
<head>
8+
<meta charset="utf-8" />
9+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
10+
<title>Error</title>
11+
<link href="~/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
12+
<link href="~/css/app.css" rel="stylesheet" />
13+
</head>
14+
15+
<body>
16+
<div class="main">
17+
<div class="content px-4">
18+
<h1 class="text-danger">Error.</h1>
19+
<h2 class="text-danger">An error occurred while processing your request.</h2>
20+
21+
@if (Model.ShowRequestId)
22+
{
23+
<p>
24+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
25+
</p>
26+
}
27+
28+
<h3>Development Mode</h3>
29+
<p>
30+
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
31+
</p>
32+
<p>
33+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
34+
It can result in displaying sensitive information from exceptions to end users.
35+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
36+
and restarting the app.
37+
</p>
38+
</div>
39+
</div>
40+
</body>
41+
42+
</html>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Linq;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Mvc;
7+
using Microsoft.AspNetCore.Mvc.RazorPages;
8+
using Microsoft.Extensions.Logging;
9+
10+
namespace FirstServer.Pages
11+
{
12+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
13+
[IgnoreAntiforgeryToken]
14+
public class ErrorModel : PageModel
15+
{
16+
public string RequestId { get; set; }
17+
18+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
19+
20+
private readonly ILogger<ErrorModel> _logger;
21+
22+
public ErrorModel(ILogger<ErrorModel> logger)
23+
{
24+
_logger = logger;
25+
}
26+
27+
public void OnGet()
28+
{
29+
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)