Blog

  • Take advantage of the power of Blazor forms

    Users enter data using forms. In a classic web app, you create a form using the <form> element, and enable the user to provide data using <input> elements. When the user submits the form, the input can be validated. If the validation is successful, the appropriate actions can then be taken, such as using the information provided to add a new entry to a database or to update a record.

    The facilities the <form> and <input> elements provide are simple but relatively primitive. Blazor extends the capabilities of forms with its <EditForm> component. Additionally, Blazor provides a series of specialized input elements that you can use to format and validate the data the user enters.

    In this unit, you learn how to use the <EditForm> element and the input elements to build functional forms. You also see how to use data binding with a form.

    What is an EditForm?

    An EditForm is a Blazor component that fulfills the role of an HTML form on a Blazor page. The main differences between an EditForm and an HTML form are:

    • Data binding: You can associate an object with an EditForm. The EditForm acts like a view of the object for data entry and display purposes.
    • Validation: An EditForm provides extensive and extensible validation capabilities. You can add attributes to the elements in an EditForm that specify validation rules. The EditForm applies these rules automatically. This functionality is described in a later unit in this module.
    • Form submission: An HTML form sends a post request to a form handler when the form is submitted. This form handler is expected to perform the submit process, and then display any results. An EditForm follows the Blazor event model; you specify a C# event handler that captures the OnSubmit event. The event handler performs the submit logic.
    • Input elements: An HTML form uses an <input> control to gather user input, and a submit button to post the form for processing. An EditForm can use these same elements, but Blazor provides a library of input components that have other features, such as built-in validation and data binding.

    Create an EditForm with data binding

    The <EditForm> element supports data binding with the Model parameter. You specify an object as the argument for this parameter. The input elements in the EditForm can bind to properties and fields exposed by the model by using the @bind-Value parameter. The following example is based on the WeatherForecast class created by the default Blazor Server App template. The class looks like this:

    C#Copy

    public class WeatherForecast
    {
        public DateTime Date { get; set; }
    
        public int TemperatureC { get; set; }
    
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    
        public string Summary { get; set; }
    }
    

    The model for the EditForm is an instance of the WeatherForecast class stored in the @currentForecast variable, and the input elements are bound to the fields in the class:

    razorCopy

    @page "/fetchdata"
    
    @using WebApplication.Data
    @inject WeatherForecastService ForecastService
    
    <h1>Weather forecast</h1>
    
    <input type="number" width="2" min="0" max="@upperIndex" @onchange="ChangeForecast" value="@index"/>
    
    <EditForm Model=@currentForecast>
        <InputDate @bind-Value=currentForecast.Date></InputDate>
        <InputNumber @bind-Value=currentForecast.TemperatureC></InputNumber>
        <InputText @bind-Value=currentForecast.Summary></InputText>
    </EditForm>
    
    @code {
        private WeatherForecast[] forecasts;
        private WeatherForecast currentForecast;
        private int index = 0;
        private int upperIndex = 0;
    
        protected override async Task OnInitializedAsync()
        {
            forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
            currentForecast = forecasts[index];
            upperIndex = forecasts.Count() - 1;
        }
    
        private async Task ChangeForecast(ChangeEventArgs e)
        {
            index = int.Parse(e.Value as string);
            if (index <= upperIndex && index >= 0)
            {
                currentForecast = forecasts[index];
            }
        }
    }
    
    big data hadoop training courses malaysia
  • Attach C# code to DOM events with Blazor event handlers

    Most HTML elements expose events that are triggered when something significant happens. Such as, when a page finishes loading, the user clicks a button, or the contents of an HTML element are changed. An app can handle an event in several ways:

    • The app can ignore the event.
    • The app can run an event handler written in JavaScript to process the event.
    • The app can run a Blazor event handler written in C# to process the event.

    In this unit, you get a detailed look at the third option; how to create a Blazor event handler in C# to process an event.

    Handle an event with Blazor and C#

    Each element in the HTML markup of a Blazor app supports many events. Most of these events correspond to the DOM events available in regular web applications, but you can also create user-defined events that are triggered by writing code. To capture an event with Blazor, you write a C# method that handles the event, then bind the event to the method with a Blazor directive. For a DOM event, the Blazor directive shares the same name as the equivalent HTML event, such as @onkeydown or @onfocus. For example, the sample app generated by using the Blazor Server App contains the following code on the Counter.razor page. This page displays a button. When the user selects the button, the @onclick event triggers the IncrementCount method that increments a counter indicating how many times the button was clicked. The <p> element on the page displays the value of the counter variable:

    razorCopy

    @page "/counter"
    
    <h1>Counter</h1>
    
    <p>Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
    
        private void IncrementCount()
        {
            currentCount++;
        }
    }
    

    Many event handler methods take a parameter that provides extra contextual information. This parameter is known as an EventArgs parameter. For example, the @onclick event passes information about which button the user clicked, or whether they pressed a button such as Ctrl or Alt at the same time as clicking the button, in a MouseEventArgs parameter. You don’t need to provide this parameter when you call the method; the Blazor runtime adds it automatically. You can query this parameter in the event handler. The following code increments the counter shown in the previous example by five if the user presses the Ctrl key at the same time as clicking the button:

    razorCopy

    @page "/counter"
    
    <h1>Counter</h1>
    
    <p>Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    
    @code {
        private int currentCount = 0;
    
        private void IncrementCount(MouseEventArgs e)
        {
            if (e.CtrlKey) // Ctrl key pressed as well
            {
                currentCount += 5;
            }
            else
            {
                currentCount++;
            }
        }
    }
    

    Other events provide different EventArgs parameters. For instance, the @onkeypress event passes a KeyboardEventArgs parameter that indicates which key the user pressed. For any of the DOM events, if you don’t need this information, you can omit the EventArgs parameter from the event handling method.

    blockchaint raining courses malaysia
  • Publish an OpenAPI enabled web API to Azure App Service

    Now that the code is configured to generate an OpenAPI document file that describes the web API, VanArsdel’s development team turns their attention to publishing the application.

    Seamless development experiences in Visual Studio, from code to deploy

    In a fusion development team, time is one of the most valuable assets. You write code and build an app, then use different tools to deploy your app. You come back to the code, update it, and switch to the other tools for deployment. The cost for switching between tools is huge, and eventually it decreases your productivity.

    What if your development tool, Visual Studio, can do everything for you in one place? It saves time and increases productivity. Visual Studio offers features to publish your app to Azure App Service.

    Screenshot of Publish to Azure App Service in Visual Studio.

    Visual Studio also offers the feature to integrate your web API with Azure API Management while publishing the app.

    Screenshot of integrate using Azure API Management in Visual Studio.

    In the next couple of exercises, you’ll explore how to publish your web API application to Azure App Service and integrate it using Azure API Management.

    ibm aix system i training courses malaysia
  • Understand template components

    Template components that you can reuse across multiple apps provide a foundation of tried and tested layout and logic for UI element customization. Template components apply a standardized design across a web app by defining common elements and applying them to all pages. Templates can streamline updates, such as rebranding, because you make modifications only at the central template location.

    In this unit, you learn about template components and how you can incorporate them into a Blazor application.

    ibm cognos bi training courses malaysia

  • Understand the Blazor component lifecycle

    Blazor components have a well-defined lifecycle that starts when they’re first created and ends when they’re destroyed. A set of events that occur in response to specific triggers governs the component lifecycle. Such triggers include the component being initialized, users interacting with the component, or the page where the component resides being closed.

    In this unit, you learn about the events that occur during the Blazor component lifecycle. You see how to handle these events to optimize the work done and increase the responsiveness of a Blazor page.

    ibm informix training courses malaysia

  • JavaScript interoperability with Blazor

    Blazor uses C# components rather than JavaScript to create web pages or HTML sections with dynamic content. But you can use Blazor JavaScript interoperability (JS interop) to call JavaScript libraries in Blazor apps and call JavaScript functions from .NET C# code.

    In this unit, you learn how to call JavaScript from C# code in a Blazor page, and how to invoke C# methods from JavaScript functions. In the next unit, you use an alert component from a JavaScript library to update your Blazor pizza delivery website.

    Use Blazor JavaScript interoperability

    A typical Blazor component uses layout and user interface logic to render HTML at runtime. You use C# code to handle events and other dynamic page features that interact with the user and external services. In many cases, you don’t need to use JavaScript code. Instead, you can use Blazor with .NET libraries, which provide many equivalent capabilities.

    However, sometimes you need to use an existing JavaScript library. For example, some open-source JavaScript libraries render components and handle user interface elements in a specialized manner. Or, you might have existing tried and tested JavaScript code that you want to reuse instead of converting it into C#.

    You can integrate JavaScript libraries into your applications by using Blazor JavaScript interoperability, or JS interop. You use JS interop to call JavaScript functions from .NET methods and to invoke .NET methods from JavaScript functions. JS interop handles the marshaling of data and object references between Blazor and JavaScript to ease the transition between them.

    ibm infosphere datastage training courses malaysia

  • Package a Razor class library

    A task that you often need to perform is packaging libraries for reuse by other developers. NuGet packaging makes it trivial for any developer anywhere to acquire and properly configure all the .NET references for their applications.

    In the preceding unit, you built your modal dialog component and used it in your own application. Now you want to reuse it in other applications.

    In this unit, you learn the steps necessary to configure a Razor class library as a NuGet package. You also learn how to package the library for distribution by using a package-repository service, such as NuGet.org, or GitHub repositories.

    Configure a Razor class library for NuGet packaging

    The .NET ecosystem makes it easy to define the properties that are necessary for other developers to identify and use your components. You can define all these properties in the project file (*.csproj) of your Razor class library so they travel with the library. The properties are then updated appropriately when your library is updated.

    ibm lotus notes domino datastage training courses malaysia

  • Razor class library creation and concepts

    Components in web applications give developers the ability to reuse portions of an application user interface throughout the application. By using Razor class libraries, developers can share and reuse these components across many applications.

    In this unit, you learn how to create a Razor class library. You then use it to share rendered and static content for Blazor applications to customize and display.

    Razor class libraries

    A Razor class library is a .NET project type. It contains Razor components, pages, HTML, Cascading Style Sheet (CSS) files, JavaScript, images, and other static web content that a Blazor application can reference. Like other .NET class library projects, Razor class libraries can be bundled as a NuGet package and shared on NuGet package repositories such as NuGet.org.

    Let’s look at the default template for creating a Razor class library.

    Create a project by using the default template

    You can optionally begin creating a Razor class library in Visual Studio by selecting File > New Project.

    Screenshot of the "Create a new project" pane Razor component library template links in Visual Studio.

    You can also create projects on a command-line interface by running the following command:

    .NET CLICopy

    dotnet new razorclasslib -o MyProjectName
    

    This template delivers an initial component named Component1, which contains several important features that your components can use:

    • An isolated cascading style sheet named Component1.razor.css, which is stored in the same folder as Component1.razor. The Component1.razor.css file is conditionally included in a Blazor application that references Component1.
    • Static content, such as images and JavaScript files, which is available to a Blazor application at runtime and referenced within Component1. This content is delivered in a wwwroot folder that behaves in the same way as a wwwroot folder in an ASP.NET Core or Blazor application.
    • .NET code, which executes functions that reside in the included JavaScript file.
    Screenshot of Visual Studio Solution Explorer, showing the default project contents.

    Differences between a class library and a Razor class library

    A class library is a common package delivery structure in .NET applications, and a Razor class library is similar in structure with a few other features configured in the project file.

    XMLCopy

    <Project Sdk="Microsoft.NET.Sdk.Razor">
    
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
    
      
      <ItemGroup>
        <SupportedPlatform Include="browser" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0" />
      </ItemGroup>
    
    </Project>
    
    • The project file contains an SDK reference to Microsoft.NET.Sdk.Razor to declare that it contains and creates Razor content as a Razor class library.
    • The SupportedPlatform entry declares that this library can be used in a browser platform, namely WebAssembly.
    • The PackageReference to the Microsoft.AspNetCore.Components.Web library gives access to the base Blazor components that are shipped with the framework. This access lets you use those simple components to help you build more complex components.

    Razor component contents

    This initial Razor component is simple. It contains only an HTML div element with a short block of text:

    razorCopy

    <div class="my-component">
        This component is defined in the <strong>FirstRazorLibrary</strong> library.
    </div>
    ibm websphere training courses malaysia
  • Server-side request forgery

    Server-side request forgery (SSRF) describes situations where a web application is fetching a remote resource without validating the user-supplied URL. It allows an attacker to coerce the application to send a crafted request to an unexpected destination.

    Attackers might also use this functionality to import untrusted data into code that expects to only read data from trusted sources, allowing them to circumvent input validation.

    A URL or query string seen in a web browser’s address bar, when used as an input parameter, could be a perfect example of user input needing sanitization.

    During code review, you came across a seemingly harmless REST web GET request:

    C#Copy

    string url = Request.Form["url"];
    var client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(url);
    

    Without validating the supplied URL, an attacker can hijack the network connection and control the request schema by supplying ldap://, jar:// or file:// instead of https://. Furthermore, the POST method allows an attacker to force the application to send a crafted request to an unexpected destination.

    iot internet of things training courses malaysia
  • Security logging and monitoring

    How do you detect if you’re breached? How can you determine what steps the attacker took to penetrate your system?

    Without sufficient logging and monitoring, you can’t detect breaches. Logging and monitoring give you an opportunity to stop an attacker in their tracks. Telemetry, logging, and monitoring enables digital forensics and post-mortem after a breach. Logging and monitoring are essential components in ensuring that you can detect any suspicious activity in close to real time, or diagnosed after the fact.

    More importantly, collecting this data is useless without actively reviewing it or having alerting rules in place.

    Make sure to sanitize the data to prevent from over-logging or storing sensitive information as logs.

    Establish effective monitoring and alerting mechanisms. Ensure that sign in and access-control failures are logged with sufficient user context for identifying suspicious or malicious accounts. Take advantage of different logging levels (Info, Warning, Error, and so on) and log destinations. Avoid server-side error details from ever reaching client side, which can result in leaking your system’s implementation details.

    isaca certification training courses malaysia