100% found this document useful (6 votes)
57 views46 pages

PDF Blazor WebAssembly Succinctly 1st Edition Michael Washington Download

ebook

Uploaded by

tvorosogwuma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
57 views46 pages

PDF Blazor WebAssembly Succinctly 1st Edition Michael Washington Download

ebook

Uploaded by

tvorosogwuma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Full download test bank at ebookmeta.

com

Blazor WebAssembly Succinctly 1st Edition Michael


Washington

For dowload this book click LINK or Button below

https://ebookmeta.com/product/blazor-webassembly-
succinctly-1st-edition-michael-washington/

OR CLICK BUTTON

DOWLOAD EBOOK

Download More ebooks from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Blazor Succinctly 1st Edition Michael Washington

https://ebookmeta.com/product/blazor-succinctly-1st-edition-
michael-washington/

Custom Blazor Oqtane Modules Succinctly 1st Edition


Michael Washington

https://ebookmeta.com/product/custom-blazor-oqtane-modules-
succinctly-1st-edition-michael-washington/

Learning Blazor: Build Single-Page Apps with


WebAssembly and C# David Pine

https://ebookmeta.com/product/learning-blazor-build-single-page-
apps-with-webassembly-and-c-david-pine/

The Art of WebAssembly 1st Edition Rick Battagline

https://ebookmeta.com/product/the-art-of-webassembly-1st-edition-
rick-battagline/
WebAssembly: The Definitive Guide 1st Edition Brian
Sletten

https://ebookmeta.com/product/webassembly-the-definitive-
guide-1st-edition-brian-sletten/

ReSharper Succinctly 1st Edition Peter Shaw

https://ebookmeta.com/product/resharper-succinctly-1st-edition-
peter-shaw/

Razor Components Succinctly 1st Edition Ed Freitas

https://ebookmeta.com/product/razor-components-succinctly-1st-
edition-ed-freitas/

Blazor in Action 1st Edition Chris Sainty

https://ebookmeta.com/product/blazor-in-action-1st-edition-chris-
sainty/

Microsoft Blazor, 2nd Edition Peter Himschoot

https://ebookmeta.com/product/microsoft-blazor-2nd-edition-peter-
himschoot/
Copyright © 2020 by Syncfusion Inc.
2501 Aerial Center Parkway
Suite 200
Morrisville, NC 27560
USA
All rights reserved.
ISBN: 978-1-64200-202-7

Important licensing information. Please read.


This book is available for free download
from www.syncfusion.com on completion of a registration form.
If you obtained this book from any other source, please register and
download a free copy from www.syncfusion.com.
This book is licensed for reading only if obtained from
www.syncfusion.com.
This book is licensed strictly for personal, educational use.
Redistribution in any form is prohibited.
The authors and copyright holders provide absolutely no warranty
for any information provided.
The authors and copyright holders shall not be liable for any claim,
damages, or any other liability arising from, out of, or in connection
with the information in this book.
Please do not use this book if the listed terms are unacceptable.
Use shall constitute acceptance of the terms listed.
SYNCFUSION, SUCCINCTLY, DELIVER INNOVATION WITH EASE,
ESSENTIAL, and .NET ESSENTIALS are the registered trademarks of
Syncfusion, Inc.
Technical Reviewer: James McCaffrey
Copy Editor: Courtney Wright
Acquisitions Coordinator: Tres Watkins, vice president of content,
Syncfusion, Inc.
Proofreader: Jacqueline Bieringer, content producer, Syncfusion,
Inc.
Table of Contents
The Story Behind the Succinctly Series of Books
Chapter 1 What is Blazor?
Chapter 2 The Help Desk Application
Chapter 3 Create the Help Desk Application
Chapter 4 Explore the Project
Chapter 5 Add Syncfusion
Chapter 6 Creating a Data Layer
Chapter 7 Creating New Tickets
Chapter 8 Help Desk Ticket Administration
Chapter 9 Sending Emails
Detailed Table of Contents
The Story behind the
Succinctly Series of Books
Daniel Jebaraj, Vice President
Syncfusion, Inc.

Staying on the cutting edge


As many of you may know, Syncfusion is a provider of software
components for the Microsoft platform. This puts us in the exciting
but challenging position of always being on the cutting edge.
Whenever platforms or tools are shipping out of Microsoft, which
seems to be about every other week these days, we have to educate
ourselves, quickly.

Information is plentiful but harder to digest


In reality, this translates into a lot of book orders, blog searches, and
Twitter scans.
While more information is becoming available on the Internet and
more and more books are being published, even on topics that are
relatively new, one aspect that continues to inhibit us is the inability
to find concise technology overview books.
We are usually faced with two options: read several 500+ page books
or scour the web for relevant blog posts and other articles. Just as
everyone else who has a job to do and customers to serve, we find
this quite frustrating.

The Succinctly series


This frustration translated into a deep desire to produce a series of
concise technical books that would be targeted at developers working
on the Microsoft platform.
We firmly believe, given the background knowledge such developers
have, that most topics can be translated into books that are between
50 and 100 pages.
This is exactly what we resolved to accomplish with the Succinctly
series. Isn't everything wonderful born out of a deep desire to change
things for the better?

The best authors, the best content


Each author was carefully chosen from a pool of talented experts who
shared our vision. The book you now hold in your hands, and the
others available in this series, are a result of the authors' tireless
work. You will find original content that is guaranteed to get you up
and running in about the time it takes to drink a few cups of coffee.

Free forever
Syncfusion will be working to produce books on several topics. The
books will always be free. Any updates we publish will also be free.

Free? What is the catch?


There is no catch here. Syncfusion has a vested interest in this effort.
As a component vendor, our unique claim has always been that we
offer deeper and broader frameworks than anyone else on the
market. Developer education greatly helps us market and sell against
competing vendors who promise to “enable AJAX support with one
click,” or “turn the moon to cheese!”

Let us know what you think


If you have any topics of interest, thoughts, or feedback, please feel
free to send them to us at [email protected].
We sincerely hope you enjoy reading this book and that it helps you
better understand the topic of study. Thank you for reading.
Please follow us on Twitter and “Like” us on Facebook to help us
spread the word about the Succinctly series!
About the Author
Michael Washington is a Microsoft MVP, an ASP.NET C# programmer,
and the founder of BlazorHelpWebsite.com. He is the author of the
book An Introduction to Building Applications with Blazor. He has
extensive knowledge in process improvement, billing systems, and
student information systems. He has a son, Zachary, and resides in
Los Angeles with his wife, Valerie.
You can follow him on Twitter at @ADefWebserver.
Introduction
Blazor is an exciting technology that allows you to create web-based
applications using C# instead of JavaScript. However, you still have
the ability to implement custom JavaScript when you desire. Blazor
WebAssembly is a component that allows browsers to run binary
code for enhanced performance and security.
Blazor is an alternative to other single-page application (SPA)
frameworks such as Angular, React, and Vue.js.

Figure 1: Help Desk Administration


In this book, we will cover the core elements of Blazor, and then
explore additional features by building a sample application called
Syncfusion Help Desk.
This application will demonstrate the following:
Implementing authentication and authorization.
Inserting, updating, and deleting data from the database.
Using forms and validation.
Implementing email notifications.
The code for this e-book is available on GitHub. The step-by-step
instructions use Visual Studio 2019 Community edition, which is
available for free at this link. In addition, SQL Server Developer
edition is recommended, and it is available for download for free at
this link.
You may want to bookmark the official Microsoft Blazor
documentation available at https://blazor.net.
Chapter 1 What is Blazor?
Blazor applications are composed of components that are constructed
using C#, HTML-based Razor syntax, and CSS.
Blazor has two different runtime modes: server-side Blazor and client-
side Blazor, also known as Blazor WebAssembly. Both modes run in all
modern web browsers, including web browsers on mobile phones.

Server-side Blazor

Figure 2: Server-Side Blazor


© BlazorHelpWebsite.com, used with permission
Server-side Blazor renders the Razor components on the server and
updates the webpage using a SignalR connection. The Blazor
framework sends events from the web browser, such as button clicks
and mouse movements, to the server. The Blazor runtime computes
changes to the components on the server and sends a diff-based
webpage back to the browser.
Client-side Blazor (WebAssembly)

Figure 3: Client-Side Blazor (WebAssembly)


© BlazorHelpWebsite.com, used with permission
Client-side Blazor is composed of the same code as server-side
Blazor; however, it runs entirely in the web browser using a
technology known as WebAssembly.
The primary difference in Blazor applications that are created in
server-side Blazor versus client-side Blazor is that the client-side
Blazor applications need to make web calls to access server data,
whereas the server-side Blazor applications can omit this step as all
their code is executed on the server.
One way to think of Blazor is that Blazor is a framework for creating
SPA webpages using one of two architectures (client side or server
side), using Razor technology written with the C# language.
Because client-side Blazor with WebAssembly executes entirely on a
user's browser, it is very fast for many applications.
The Syncfusion Help Desk sample application covered in this book will
be built using client-side Blazor.
Core Blazor features
Components and routing
A Blazor application is composed of components. A component is a
chunk of code consisting of a user interface and processing logic. A
Blazor component is also called a Razor component.
Blazor features routing, where you can provide navigation to your
controls using the @page directive followed by a unique route in
quotes preceded by a slash.
The following is an example of a simple Razor component called
ComponentExample.razor.

Code Listing 1: ComponentExample.razor


@page "/componentexample"
<h3>This is Component Example</h3>
@code {
}

The following shows what the component looks like in a running


application.

Figure 4: A Simple Component


A Razor component is contained in a .razor file and can be nested
inside of other components.
For example, we can create a component named ComponentOne.razor
using the following code.
Code Listing 2: ComponentOne.razor
<h4 style="background-color:goldenrod">
This is ComponentOne
</h4>
@code {
}

We can alter ComponentExample.razor to contain ComponentOne.razor.

Code Listing 3: ComponentExample.razor


@page "/componentexample"
<h3>This is Component Example</h3>
<ComponentOne />
@code {
}

The following shows what ComponentExample.razor now looks like


when running in the application.

Figure 5: Nested Component


Note: A component's name must start with an uppercase character.

Parameters
Razor components can pass values to other components using
parameters. Component parameters are defined using the
[Parameter] attribute, which must be declared as public.
For example, we can create a Razor component called
ParameterExampleComponent.razor that contains a parameter called
Title.

Code Listing 4: ParameterExampleComponent.razor


<h4>Parameter Example Component</h4>
<h5 style="color:red">@Title</h5>
@code {
[Parameter]
public string Title { get; set; }
}

We create another Razor component called ParameterExample.razor


that consumes the ParameterExampleComponent.razor control and
passes a value (Passed from Parent) to the Title parameter in the
ParameterExampleComponent.razor control.

Code Listing 5: ParameterExample.razor


@page "/parameterexample"
<h4>Parameter Example</h4>
<ParameterExampleComponent Title="Passed from Parent" />
@code {
}

When we run the application, we get the following result.


Figure 6: Parameter Example

Data binding
Simple, one-way binding in Blazor is achieved by declaring a
parameter and referencing it using the @ symbol. An example of this
is shown in the following code.
Code Listing 6: One-Way Binding
<b>BoundValue:</b> @BoundValue
@code {
private string BoundValue { get; set; }
protected override void OnInitialized()
{
BoundValue = "Initial Value";
}
}

This displays the following when rendered.

Figure 7: One-Way Binding


Two-way, dynamic data binding in Razor components is implemented
using the @bind attribute.
The following example demonstrates this.
Code Listing 7: Two-Way Binding
<input @bind="BoundValue" @bind:event="oninput" />
<p>Display CurrentValue: @BoundValue</p>
@code {
private string BoundValue { get; set; }
}

When we run the code, it displays the value entered into the text
input box as text is typed into the input box.

Figure 8: Two-Way Binding

Events
Raising events in Razor components is straightforward. The following
example demonstrates using the @onclick event handler to execute
the method IncrementCount when the button is clicked.
Code Listing 8: Simple Event
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">
Click me
</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}

When the control is rendered and the button is clicked six times, the
UI looks like this.

Figure 9: Simple Event


Chapter 2 The Help Desk
Application
To demonstrate the features of Blazor, and how controls such as the
suite available from Syncfusion can make development faster and
easier, we will create a simple help desk application.

Help desk users

Figure 10: New Help Desk Ticket


Users of the application will see a form that allows them to create a
new help desk ticket.
Figure 11: Syncfusion Toast
With the Syncfusion Toast control, a pop-up is displayed to let the
user know that their action was successful.

Figure 12: Email Notification


An email is sent to the administrator with a link that will navigate
directly to the help desk ticket.
Figure 13: Administrator Adding Details
When the administrator is logged in and they click on the link in the
email, they will have the ability to edit all fields and enter help desk
ticket detail records at the bottom of the form by entering the desired
text and clicking Add.
Figure 14: Administrator Saving Details
After adding the desired help desk ticket details, the administrator
clicks Save to save the record and send a notification email to the
user who created the help desk ticket.
Figure 15: User Adding Details
The user who created the help desk ticket receives an email with a
link that navigates them to the help desk ticket and allows them to
also enter details.
However, the fields at the top of the help desk ticket are grayed-out
and disabled for them. They can only add new details.
Help desk administrators

Figure 16: Administration Menu Link


A user logged in as the administrator will see an Administration link
that will take them to the section of the application that will allow
them to administer all help desk tickets.

Figure 17: Syncfusion Data Grid


This will display the Syncfusion Data Grid. The administrator can edit
records, sort, page, and resize the data grid.
Figure 18: Syncfusion Dialog
Clicking the Edit button next to a record in the data grid will open it
up in the Syncfusion Dialog control.
This dialog will allow the administrator to edit all fields of the help
desk ticket, as well as add help desk ticket detail records at the
bottom of the form.
When the administrator saves the record, the user who created the
help desk ticket receives an email with a link that navigates them to
the help desk ticket.
Figure 19: Delete Confirmation
Clicking the Delete button next to a record in the Data Grid will open
the delete confirmation pop-up in the Syncfusion Dialog.
Clicking Yes will delete the record and clicking No will cancel the
action.
Chapter 3 Create the Help
Desk Application
In this chapter, we will cover the steps to create the Help Desk
application.

Figure 20: The Help Desk Application in Action


The source code for the completed application is available on GitHub.
Install SQL Server

Figure 21: SQL Server


The application requires a database to store the data. Download and
install the free SQL Server 2019 Developer edition here, or use the
full SQL Server, if you have access to it.

Install .NET Core and Visual Studio


To create the application, these steps are required (if you do not
already have the following software installed):
Install the .NET Core 3.1 SDK.
Install Visual Studio 2019 version 16.6 (or later) with the
ASP.NET and web development workload here.
Note: The requirements for creating applications using Blazor are
constantly evolving. See the latest requirements.
Note: If you install Visual Studio 2019 and select the .NET Core
workload during installation, the .NET Core SDK and runtime will be
installed for you. Learn more.
Create the project

Figure 22: Blazor App


Open Visual Studio and select Create a New Project > Blazor App
> Next. Enter SyncfusionHelpDeskClient for Project name and
click Create.

Figure 23: Change Authentication


On the Create a new Blazor app dialog, select Blazor
WebAssembly App and ASP.NET Core hosted and click the
Change link under Authentication.
Figure 24: Set Authentication
In the Change Authentication dialog, select Individual User
Accounts and Store user accounts in-app.
Click OK, and on the Create a new Blazor app dialog, click Create.

Figure 25: In Visual Studio


The project will be created and will open in Visual Studio.

Create the database


From the toolbar, click View and select the SQL Server Object
Explorer.

Figure 26: Add SQL Server


Click Add SQL Server to add a connection to your database server,
if you don’t already have it in the SQL Server list.
Note: For this example, we do not want to use the localdb
connection (for SQL Express) that you may see in the list.

Figure 27: Add New Database


Expand the tree node for your SQL Server, then right-click
Databases and select Add New Database. Name the database
SyncfusionHelpDesk.
Figure 28: Copy Connection String
After the database has been created, right-click it and select
Properties. In the Properties window, copy the connection string.

Figure 29: Paste Connection String


Open the appsettings.json file in the Server project and paste the
connection string in the DefaultConnection property.
Save and close the file.

Blazor WebAssembly security


The default code the Visual Studio wizard creates will allow us to
create new users. However, we want some users to be
administrators. To do this, we must enable role management.
Open the Startup.cs file in the Server project and remove the
following code
Code Listing 9: Original Identity Code
services.AddDefaultIdentity<IdentityUser>(
options => options.SignIn.RequireConfirmedAccount = tru
e)
.AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, Applicatio
nDbContext>();

Replace the code with the following code to remove the requirement
to confirm new user accounts and to enable role management.
Code Listing 10: Updated Identity Code
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>() // Add roles.
.AddEntityFrameworkStores<ApplicationDbContext>
();
// From: https://github.com/dotnet/AspNetCore.Docs/i
ssues/17649
// Configure identity server to put the role claim i
nto the id token
// and the access token and prevent the default mapp
ing for roles
// in the JwtSecurityTokenHandler.
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, Applicatio
nDbContext>(options =>
{
options.IdentityResources["openid"].UserClai
ms.Add("role");
options.ApiResources.Single().UserClaims.Add
("role");
});
// Need to do this as it maps "role" to ClaimTypes.R
ole and causes issues.
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHand
ler
.DefaultInboundClaimTypeMap.Remove("role");

In Visual Studio, press F5 to run the application and open it in your


web browser.

Figure 30: Register User


Click Register and create a user with the email Test@Email.
You will then see the following page.
Figure 31: Apply Migrations
Click Apply Migrations. After a few moments, you will see a
message to refresh the page. Refresh the page in your web browser.

Figure 32: Logged In


The required tables will be created in the database and the
application will display the home page and indicate that the
Test@Email account is logged in.
Close the web browser to stop the application and return to Visual
Studio.
Create an administrator
We will now create code that will programmatically create an
administrator role and add the Administrator@Email account to
the administrator role.

Figure 33: Add Custom Register Page


To do this, we need to override the registration page with a custom
registration page.
In the Server project, create an Account folder in the
Areas/Identity/Pages folder. Create a Register.cshtml page and
a Register.cshtml.cs page, using the following code.
Code Listing 11: Register.cshtml
@page
@model RegisterModel
@{
ViewData["Title"] = "Register";
}
<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="pos
t">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-dange
r"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-contro
l" />
<span asp-validation-for="Input.Email" class="te
xt-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-cont
rol" />
<span asp-validation-for="Input.Password" class
="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="fo
rm-control" />
<span asp-validation-for="Input.ConfirmPassword"
class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Regist
er</button>
</form>
</div>
<div class="col-md-6 col-md-offset-2">

</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

Code Listing 12: Register.cshtml.cs


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SyncfusionHelpDeskClient.Server.Models;
namespace SyncfusionHelpDeskClient.Server.Areas.Identity.Pages
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
const string ADMINISTRATION_ROLE = "Administrators";
const string ADMINISTRATOR_USERNAME = "Admin@email";
private readonly SignInManager<ApplicationUser> _signInM
anager;
private readonly UserManager<ApplicationUser> _userManag
er;
private readonly RoleManager<IdentityRole> _roleManager;
public RegisterModel(
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get;
set; }
public class InputModel
{
[Required]
[EmailAddress]
Another random document with
no related content on Scribd:
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.

Project Gutenberg™ eBooks are often created from several printed


editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like