Sunday, 1 September 2024

How to Build a Full-Stack Web App with Blazor

 

Blazor Stack Overview

Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't mean you can't use JavaScript). So, it is obvious that Micrsoft is making c#  to flourish on client side also. So, in nutshell Blazor makes it possible to create Dynamic Web app only using c# . How? Let us understand it

Microsoft Blazor is a modern web framework that allows developers to build interactive web applications using C# and .NET instead of JavaScript. It is part of the ASP.NET Core framework and enables the development of rich, client-side web applications with .NET, providing an alternative to traditional JavaScript frameworks like React, Angular.

The Blazor stack can be understood as the combination of several technologies and components within the.NET ecosystem that come together to provide a full-featured platform for building web applications. Here’s an overview of the key components and technologies that make up the Blazor stack:

Blazor Hosting Models

Blazor provides two primary hosting models, each with different deployment scenarios and architectures:

  • Blazor Server:

    • Runs the Blazor application on the server.
    • UI updates and event handling are performed on the server, and updates are sent to the client over a SignalR connection.
    • The client renders the UI and communicates user events back to the server.
    • Ideal for applications requiring rapid load times and those that can tolerate network latency for UI interactions.
  • Blazor WebAssembly (Blazor WASM):

    WebAssembly (WASM) is a binary instruction format that allows code written in languages other than JavaScript (like C, C++, Rust, and others) to run on the web. It is designed to be a portable, compact, and efficient format that can be executed in modern web browsers at near-native speed. WebAssembly provides a way to run code on the web that is faster and more efficient than traditional JavaScript, especially for compute-intensive tasks. Key Concepts: Binary Format: WebAssembly is a low-level binary format, which is compact and designed for performance. Portability: Code written for WebAssembly can run on any platform that supports WebAssembly, making it highly portable. Language Agnostic: WebAssembly is not tied to any specific programming language. Code written in languages like C, C++, Rust, and others can be compiled to WebAssembly. Interoperability with JavaScript: WebAssembly can interact with JavaScript, allowing developers to call WebAssembly modules from JavaScript and vice versa.

    • Runs the Blazor application entirely on the client using WebAssembly.
    • The application, including the .NET runtime, is downloaded to the client’s browser and executed there.
    • Offers offline capabilities and reduces server load, but with a larger initial download size.
    • Ideal for public-facing applications where offline support and client-side processing are important.

    Important Points:  We can finally share code (assemblies) between client and server. You can define Enums, validation logic, some business rules, etc. once and use them everywhere. Yes, it’s going to be the same language on both ends (Client or Server Side).

.NET Runtime

Blazor applications are built on the .NET platform, which provides a robust runtime for executing C# code.

  • .NET Core/.NET 5/6/7+:

    • The Blazor framework is part of the ASP.NET Core framework, which runs on .NET.
    • For Blazor Server, the .NET runtime executes entirely on the server.
    • For Blazor WebAssembly, a WebAssembly-based .NET runtime is downloaded to the client and runs in the browser's sandboxed environment.

Razor Components

Blazor uses Razor Components as the fundamental building blocks of its applications.

  • Razor Syntax:

    • Razor is a markup syntax that allows embedding C# code into HTML. Razor Components are reusable, encapsulated units of UI that combine HTML markup with C# code.
    • Components can be nested, reused, and parameterized, making them highly flexible and modular.
  • Component Model:

    • Each Razor Component is a .razor file that defines the UI structure and behavior using a combination of HTML, C#, and Razor syntax.
    • Components can handle events, manage state, and interact with other components or services.

Data Binding and Events

Blazor provides rich data-binding capabilities and event handling mechanisms.

  • Two-Way Data Binding:

    • Blazor supports two-way data binding, allowing data in the UI to stay in sync with the underlying component state.
    • This is similar to what is found in frameworks like Angular and React but done using C#.
  • Event Handling:

    • Blazor allows handling DOM events such as clicks, input changes, and form submissions directly in C# code.
    • Event handlers are defined in components and can trigger UI updates or other actions.

Dependency Injection (DI)

Blazor supports the use of dependency injection, a design pattern used to manage service dependencies.

  • Service Registration:

    • Services such as data repositories, API clients, and logging can be registered and injected into Blazor components or services using the built-in DI container provided by ASP.NET Core.
    • This promotes a clean separation of concerns and makes components more testable and maintainable.

Routing

Blazor includes a routing system that allows navigation between different components or pages in a Blazor application.

  • Router Component:

    • The Router component is used to define the routes for your application.
    • Routes map URLs to Razor components, enabling client-side navigation without refreshing the page.
  • Parameter Passing:

    • Route parameters can be passed to components, allowing dynamic content generation based on the URL.

JavaScript Interoperability (JS Interop)

While Blazor aims to minimize the need for JavaScript, there are scenarios where interacting with JavaScript is necessary.

  • JS Interop:

    • Blazor provides JavaScript Interoperability (JS Interop) to call JavaScript functions from C# and vice versa.
    • This allows Blazor to integrate with existing JavaScript libraries or frameworks and perform tasks that require direct DOM manipulation or access to browser APIs.

State Management

Blazor provides several ways to manage state across components and user sessions.

  • Component State:

    • State can be managed within a single component, passed between components using parameters, or shared across components using services.
  • Persistent State:

    • State can be persisted using tools like local storage, session storage, or server-side storage when necessary, especially in Blazor WebAssembly.

Security

Blazor includes several features to help secure your applications.

  • Authentication and Authorization:

    • Blazor integrates with ASP.NET Core Identity for authentication and supports OAuth, OpenID Connect, and other security standards.
    • Policies, roles, and claims-based authorization are used to control access to components, pages, and APIs.

Integration with ASP.NET Core

Blazor is a part of the ASP.NET Core ecosystem and integrates seamlessly with it.

  • Server-Side Features:

    • Blazor can interact with ASP.NET Core services like MVC, Razor Pages, Web API, SignalR, and Entity Framework Core.
    • This enables full-stack development within the .NET ecosystem, including server-side data access and processing.

Tooling and Development Environment

Blazor development is supported by rich tooling in Visual Studio and Visual Studio Code.

  • Visual Studio Integration:

    • Full IntelliSense support for C#, Razor syntax, and component development.
    • Integrated debugging, project templates, and scaffolding for Blazor applications.
  • Live Reload and Hot Reload:

    • Blazor supports live reloading of UI changes during development, speeding up the feedback loop.

How to Build a Full-Stack Web App with Blazor

I am sure got to know why you must think about building a full-stack web app with Blazor, let us have a look at the steps that you must follow to ensure error-free and seamless development and delivery.

1. Create a New Blazor Project

After you open Visual Studio, click on Create a new Project and type Blazor in the search box and press Enter. You can select the available Blazor Web App template and can click on Next to move to the Configure Your New Project Window. I recommend adding a recognizable project name and clicking on Next; then, in the Additional Information window, choose .NET 8.0 (Long Term Support) from the Framework drop-down and click on Create button.

2. Explore the Overall Project Structure

If you have followed the above steps correctly, your new Blazor project will be created and you will be available to view the contents in the Solution Explorer page. Some common files and a brief description about them are as follows: -

Program.cs : acts as the entry-point for the Blazor app and is used to start the server and configure the app services and middleware (if any).

App.razor : contains the app’s root components.

Routes.razor : used to configure the complete Blazor router.

Components/Pages directory: contains all example web pages that you can check out for your Blazor app.

BlazorApp.csproj : used to define the app project and the dependencies it has.

launchSettings.json inside Properties directory : lists the complete definition of different profile settings for your local development environment.

3. Understand the Main Blazor Components like Pages, Components, and Services

Pages : Can be considered as the top-level view of your Blazor project that can be accessed via an URL.

Components These can be referred to as the building blocks that can be glued together to be used as a foundation of your Blazor app.

Services In Blazor, service classes contain the code that fetches and logs any data that is not a part of the application’s UI component.

4. Local Running of the Application

To run your Blazor app locally, click on the Start Debugging (or the green arrow button) available in the Debug Toolbar; now, once your app is running, you can click on the Hot Reload button in case you want any code changes to be reflected. You can click the Stop button in the top toolbar to stop your application at any time; but, an important point to note is that the first time you run your application in Visual Studio, a development certificate will be set up to host your app over HTTPS and will prompt you to trust the certificate.  

Creating Components

Let us Create and add Component(folder name could be of your choice) Folder to root of the Solutions. Once you've created the new Components folder, create a file within it named MyFirstComponent.razor and enter the following mark-up.

We have two ways to add this component refrence to Page where you want to consume or render this component
  • Now edit the home.razor file. At this point we can either reference the component with a fully qualified name: <BlazorDemo.Components.MyFirstComponent />
  • Or edit /_Imports.razor and add @using BlazorDemo.Components. The using statements here are cascaded into all Razor views - which means the mark-up to use the new component in /Pages/home.razor no longer needs a namespace.

Let us run this Blazor App

Difference between Blazor Server App and Blazor Client App

Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# and .NET instead of JavaScript. Blazor can be implemented in two main hosting models: Blazor Server and Blazor Web Assembly (Client-side). Below are the key differences between these two models:

1. Hosting Model

  • Blazor Server App:

    • The application runs on the server. The UI updates and event handling are performed on the server, and the results are sent to the client over a SignalR connection.
    • The client (browser) only handles the rendering of the UI and relays user events to the server, where they are processed.
    • No WebAssembly is used on the client side.
  • Blazor WebAssembly (Client-side) App:

    • The application runs entirely on the client within the browser using WebAssembly.
    • The entire Blazor application, including .NET runtime, is downloaded to the client’s browser.
    • The application runs directly in the browser's memory and interacts with the DOM without involving the server for UI updates or event handling.

2. Performance and Latency

  • Blazor Server App:

    • Performance can be impacted by network latency because every UI update and event handling operation involves a round trip to the server.
    • The server handles the state and logic, which means faster load times since the browser only loads minimal static content.
    • Suitable for scenarios with reliable, low-latency networks.
  • Blazor Web Assembly (Client-side) App:

    • Once the application is loaded in the browser, it runs independently of the server, providing a more responsive and interactive experience since there is no network latency for UI updates.
    • Initial load times can be longer because the entire application (including the .NET runtime) needs to be downloaded to the browser.
    • More suitable for scenarios where offline capabilities and responsiveness are critical.

3. App Size and Load Time

  • Blazor Server App:

    • The initial download size is minimal because only the static assets and the SignalR connection script are downloaded.
    • The server-side processing means the client is lightweight.
    • The server has a constant connection to the client via SignalR.
  • Blazor WebAssembly (Client-side) App:

    • The initial download size is larger because the application and .NET runtime are downloaded to the browser.
    • After the initial load, the application does not need a constant connection to the server to function.
    • The app can work offline after the initial download.

4. Scalability

  • Blazor Server App:

    • The server must manage multiple SignalR connections, maintain UI state for each client, and handle all processing, which can limit scalability, especially in high-user environments.
    • Requires more server resources to manage multiple concurrent users.
  • Blazor Web Assembly (Client-side) App:

    • The client-side model is more scalable because the server is only needed for API calls or data access; the client handles the rest.
    • Server resources are conserved as the processing and state management are offloaded to the client.

5. State Management

  • Blazor Server App:

    • The application state is managed on the server, and the server must keep track of the state for each connected client.
    • Automatic reconnection features help preserve state if the connection is temporarily lost.
  • Blazor WebAssembly (Client-side) App:

    • State is managed on the client. Developers must manage state persistence manually if needed (e.g., using local storage or session storage).
    • The state remains with the client, so the application continues to run even if the server is disconnected.

6. Security

  • Blazor Server App:

    • The server handles all business logic and data processing, making it easier to secure since sensitive data does not need to be exposed to the client.
    • Vulnerabilities mainly relate to the SignalR connection, such as potential issues with connection management and DoS attacks.
  • Blazor Web Assembly (Client-side) App:

    • The entire application, including business logic, is downloaded to the client, which can expose it to potential tampering. Sensitive operations should still be handled on the server via API calls.
    • Security measures such as encryption and obfuscation can mitigate risks, but they do not eliminate them.

7. Offline Support

  • Blazor Server App:

    • Limited to no offline support because it relies on a constant server connection via SignalR.
    • If the connection is lost, the application cannot function until it is reestablished.
  • Blazor Web Assembly (Client-side) App:

    • Offers better offline support because the application runs entirely in the browser once downloaded.
    • Can continue to function with local data even when the network is unavailable, and sync with the server when the connection is restored.

8. Use Cases

  • Blazor Server App:

    • Best for internal applications with controlled environments where network reliability is strong and latency is minimal.
    • Ideal for scenarios where the initial load time is critical and you need to minimize client-side resource usage.
  • Blazor WebAssembly (Client-side) App:

    • Suitable for public-facing web applications where offline support, responsiveness, and reduced server load are important.
    • Ideal for applications that need to be highly responsive with less dependency on server round trips.

Conclusion

  • Blazor Server is best for applications where server-side processing, security, and minimal initial load times are important, but it requires a constant, low-latency connection to the server.
  • C is better for scenarios requiring offline capabilities, scalability, and client-side performance, but it involves a larger initial download and potential security concerns due to client-side execution.

Choosing between Blazor Server and Blazor Web Assembly depends on your application's specific requirements, including performance, scalability, security, and user experience.

How to Build a Full-Stack Web App with Blazor

  Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...