Blog

  • Share information by using cascading parameters

    Component parameters work well when you want to pass a value to the immediate child of a component. Things become awkward when you have a deep hierarchy with children of children and so on. Component parameters aren’t automatically passed to grandchild components from ancestor components or further down the hierarchy. To handle this problem elegantly, Blazor includes cascading parameters. When you set the value of a cascading parameter in a component, its value is automatically available to all descendant components to any depth.

    In the parent component, using the <CascadingValue> tag specifies the information that will cascade to all descendants. This tag is implemented as a built-in Blazor component. Any component rendered within that tag is able to access the value.

    razorCopy

    @page "/specialoffers"
    
    <h1>Special Offers</h1>
    
    <CascadingValue Name="DealName" Value="Throwback Thursday">
        <!-- Any descendant component rendered here will be able to access the cascading value. -->
    </CascadingValue>
    

    In the descendant components, you can access the cascading value by using component members and decorating them with the [CascadingParameter] attribute.

    razorCopy

    <h2>Deal: @DealName</h2>
    
    @code {
        [CascadingParameter(Name="DealName")]
        private string DealName { get; set; }
    }
    isaca certification malaysia
  • Share data in Blazor applications

    Blazor includes several ways to share information between components. You can use component parameters or cascading parameters to send values from a parent component to a child component. The AppState pattern is another approach you can use to store values and access them from any component in the application.

    Suppose you’re working on the new pizza delivery website. Multiple pizzas should be displayed on the home page in the same way. You want to display the pizzas by rendering a child component for each pizza. Now, you want to pass an ID to that child component that determines the pizza it displays. You also want to store and display a value on multiple components that shows the total number of pizzas you sold today.

    In this unit, you learn three different techniques you can use to share values between two or more Blazor components.

    Sharing information with other components by using component parameters

    In a Blazor web app, each component renders a portion of HTML. Some components render a complete page but others render smaller fragments of markup, such as a table, a form, or a single control. If your component renders only a section of markup, you must use it as a child component within a parent component. Your child component can also be a parent to other smaller components that render within it. Child components are also known as nested components.

    In this hierarchy of parent and child components, you can share information between them by using component parameters. Define these parameters on child components, and then set their values in the parent. For example, if you have a child component that displays pizza photos, you could use a component parameter to pass the pizza ID. The child component looks up the pizza from the ID and obtains pictures and other data. If you want to display many different pizzas, you can use this child component multiple times on the same parent page, passing a different ID to each child.

    Start by defining the component parameter in the child component. You define it as a C# public property and decorate it with the [Parameter] attribute:

    razorCopy

    <h2>New Pizza: @PizzaName</h2>
    
    <p>@PizzaDescription</p>
    
    @code {
        [Parameter]
        public string PizzaName { get; set; }
        
        [Parameter]
        public string PizzaDescription { get; set; } = "The best pizza you've ever tasted."
    }
    

    Because the component parameters are members of the child component, you can render them in your HTML by using Blazor’s reserved @ symbol, followed by their name. Also, the preceding code specifies a default value for the PizzaDescription parameter. This value is rendered if the parent component doesn’t pass a value. Otherwise, the value passed from the parent overrides it.

    You can also use custom classes in your project as component parameters. Consider this class that describes a topping:

    C#Copy

    public class PizzaTopping
    {
        public string Name { get; set; }
        public string Ingredients { get; set; }
    }
    

    You can use that as a component parameter in the same way as a parameter value to access individual properties of the class by using dot syntax:

    razorCopy

    <h2>New Topping: @Topping.Name</h2>
    
    <p>Ingredients: @Topping.Ingredients</p>
    
    @code {
        [Parameter]
        public PizzaTopping Topping { get; set; }
    }
    

    In the parent component, you set parameter values by using attributes of the child component’s tags. You set simple components directly. With a parameter based on a custom class, you use inline C# code to create a new instance of that class and set its values:

    razorCopy

    @page "/pizzas-toppings"
    
    <h1>Our Latest Pizzas and Topping</h1>
    
    <Pizza PizzaName="Hawaiian" PizzaDescription="The one with pineapple" />
    
    <PizzaTopping Topping="@(new PizzaTopping() { Name = "Chilli Sauce", Ingredients = "Three kinds of chilli.
    istqb certification malaysia

  • Access data from a Blazor component

    Engaging websites need to display dynamic content that might change all the time. Learning how to obtain data from a dynamic source, such as a database or web service, is a fundamental technique in web development.

    Suppose you’re working for a pizza delivery firm on its updated customer-facing website. You have a range of webpages laid out and designed as Blazor components. Now, you want to populate those pages with information about pizzas, toppings, and orders that you want to obtain from a database.

    In this unit, you learn how to access data and render it within HTML markup for display to the user.

    Creating a registered data service

    If you want to create a dynamic website that shows changing information to users, you must write code to get that data from somewhere. For example, suppose you have a database that stores all the pizzas your company sells. Because the pizzas are always changing, it’s a bad idea to hardcode them into the website HTML. Instead, use C# code and Blazor to query the database, and then format the details as HTML so that the user can pick their favorite.

    juniper certification malaysia
  • Create a user interface with Blazor components

    Blazor components let you define webpages or portions of HTML that include dynamic content by using .NET code. In Blazor, you can formulate dynamic content by using C#, instead of using JavaScript.

    Suppose you’re working for a pizza delivery company to create a new modern website. You’re starting with a welcome page that is going to become the landing page for most site users. You want to display special deals and popular pizzas on that page.

    In this unit, you learn how to create components in Blazor and write code that renders dynamic content on those components.

    Understand Blazor components

    Blazor is a framework that developers can use to create a rich interactive user interface (UI) by writing C# code. With Blazor, you can use the same language for all your code, both server-side and client-side. You can render it for display in many different browsers, including browsers on mobile devices.

    microsoft certification malaysia

  • Perform CRUD operations with EF Core

    After EF Core is configured, you can use it to perform CRUD operations on your entity classes. Then, you can develop against C# classes, delegating the database operations to the context class. Database providers in turn translate it to database-specific query language. An example is SQL for a relational database. Queries are always executed against the database, even if the entities returned in the result already exist in the context.

    Query data

    The context object exposes a collection class for each entity type. In the preceding example, the context class exposes a collection of Pizza objects as Pizzas. Given that we have an instance of the context class, you can query the database for all pizzas:

    C#Copy

    var pizzas = await db.Pizzas.ToListAsync();
    

    Insert data

    You can use the same context object to insert a new pizza:

    C#Copy

    await db.pizzas.AddAsync(
        new Pizza { ID = 1, Name = "Pepperoni", Description = "The classic pepperoni pizza" });
    

    Delete data

    Delete operations are simple. They require only an ID of the item to be deleted:

    C#Copy

    var pizza = await db.pizzas.FindAsync(id);
    if (pizza is null)
    {
        //Handle error
    }
    db.pizzas.Remove(pizza);
    

    Update data

    Similarly, you can update an existing pizza:

    C#Copy

    int id = 1;
    var updatepizza = new Pizza { Name = "Pineapple", Description = "Ummmm?" };
    var pizza = await db.pizzas.FindAsync(id);
    if (pizza is null)
    {
        //Handle error
    }
    pizza.Description = updatepizza.Description;
    pizza.Name = updatepizza.Name;
    await db.SaveChangesAsync();
    nutanix certification malaysia
  • What is Entity Framework Core?

    Most nontrivial web applications need to reliably run operations on data, such as create, read, update, and delete (CRUD). They also need to persist any changes made by these operations between application restarts. Although there are various options for persisting data in .NET applications, Entity Framework (EF) Core is a user-friendly solution and a great fit for many .NET applications.

    Understand EF Core

    EF Core is a lightweight, extensible, open source, and cross-platform data access technology for .NET applications.

    EF Core can serve as an object-relational mapper, which:

    • Enables .NET developers to work with a database by using .NET objects.
    • Eliminates the need for most of the data-access code that typically needs to be written.

    EF Core supports a large number of popular databases, including SQLite, MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.

    The model

    With EF Core, data access is performed by using a model. A model is made up of entity classes and a context object that represents a session with the database. The context object allows querying and saving data.

    The entity class

    In this scenario, you’re implementing a pizza store management API, so you use a Pizza entity class. The pizzas in your store have a name and a description. They also need an ID to allow the API and database to identify them. The Pizza entity class that you use in your application identifies pizzas:

    C#Copy

    namespace PizzaStore.Models 
    {
      public class Pizza
      {
          public int Id { get; set; }
          public string? Name { get; set; }
          public string? Description { get; set; }
      }
    }
    
    about

  • Publish .NET apps

    Coding an app with ASP.NET Core is different from designing a static website with HTML, CSS, and JavaScript. A static website can be deployed to any web server that supports static files. The web server doesn’t need to process static files; it simply serves them over HTTP. When a web browser requests a resource, the web server simply sends the file back to the browser.

    An ASP.NET Core app, on the other hand, is a dynamic web application. It runs as a program on the web server. When the user’s web browser sends a request to the web server, the web server runs the app to generate a response, and then the web server sends the response back to the browser.

    Publishing a .NET app is the process of preparing the app for deployment on a server. When you publish a .NET app, you package your app and its dependencies into a folder that can be easily deployed. The published app doesn’t include any source code files, but it does include all the files needed to run the app, including the compiled assemblies (DLLs), configuration files, and any other assets your app needs. The app can then be deployed to a web server, cloud service, or other hosting environment.

    Types of deployments

    When you publish a .NET app, you can choose between two different types of deployments: framework-dependent and self-contained. The type of deployment you choose affects how your app is packaged and deployed.

    affiliation
  • Discover Razor syntax

    Razor is a markup syntax for embedding .NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Razor syntax is similar to the templating engines of various JavaScript single-page application (SPA) frameworks, such as Angular, React, VueJs, and Svelte.

    The default Razor language is HTML. Rendering HTML from Razor markup is no different than rendering HTML from an HTML file. The server renders HTML markup in .cshtml Razor files unchanged.

    Razor syntax

    Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.

    When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup. Otherwise, it transitions into plain HTML. To escape an @ symbol in Razor markup, use a second @ symbol. The following code sample would render the value of @Username in the HTML output.Expand table

    SyntaxOutput
    <p>@Username</p>Renders the value of @Username in the HTML output.
    <p>@@Username</p>Renders “@Username” in the HTML output.

    HTML attributes and content containing email addresses don’t treat the @ symbol as a transition character. For example, the email addresses in the following code are untouched by Razor parsing:

    HTMLCopy

    <a href="mailto:Support@contoso.com">Support@contoso.com</a>
    

    Add code to a page using the @ character

    The following code examples show how the @ character can be used to implement inline expressions, single statement blocks, and multi-statement blocks:

    HTMLCopy

    <!-- Single statement blocks  -->
    @{ var myMessage = "Hello World"; }
    
    <!-- Inline expressions -->
    <p>The value of myMessage is: @myMessage</p>
    
    <!-- Multi-statement block -->
    @{
        var greeting = "Welcome to our site!";
        var weekDay = DateTime.Now.DayOfWeek;
        var greetingMessage = greeting + " Today is: " + weekDay;
    }
    <p>The greeting is: @greetingMessage</p>
    rooms

  • Perform HTTP operations in Blazor Web apps

    In this unit, you learn how to use the IHttpClientFactory to handle the HTTP client creation and disposal, and to use that client to perform REST operations in an ASP.NET Blazor Web app. The code samples used throughout this unit are based on interacting with an API that enables managing a list of fruit stored in a database. The information in this unit is based on using code-behind files in a Razor app.

    The following code represents the data model that is referenced in the code examples:

    C#Copy

    public class FruitModel
    {
        // An id assigned by the database
        public int id { get; set; }
        // The name of the fruit
        public string? name { get; set; }
        // A boolean to indicate if the fruit is in stock
        public bool instock { get; set; }
    }
    

    Register IHttpClientFactory in your app

    To add IHttpClientFactory to your app, register AddHttpClient in the Program.cs file. The following code example uses the named client type and sets the base address of the API used in REST operations, and is referenced throughout the rest of this unit.

    C#Copy

    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();
    
    // Add IHttpClientFactory to the container and set the name of the factory
    // to "FruitAPI". The base address for API requests is also set.
    builder.Services.AddHttpClient("FruitAPI", httpClient =>
    {
        httpClient.BaseAddress = new Uri("http://localhost:5050/");
    });
    
    var app = builder.Build();
    careers

  • Service lifetimes

    When you register a service, you must choose a lifetime that matches how the service is used in the app. The lifetime affects how the service behaves when it’s injected into components. So far, you’ve registered services using the AddSingleton method. This method registers a service with a singleton lifetime. There are three built-in lifetimes for services in ASP.NET Core:

    • Singleton
    • Scoped
    • Transient

    Singleton lifetime

    Services registered with a singleton lifetime are created once when the app starts and are reused for the lifetime of the app. This lifetime is useful for services that are expensive to create or that don’t change often. For example, a service that reads configuration settings from a file can be registered as a singleton.

    Use the AddSingleton method to add a singleton service to the service container.

    Scoped lifetime

    Services registered with a scoped lifetime are created once per configured scope, which ASP.NET Core sets up for each request. A scoped service in ASP.NET Core is typically created when a request is received and disposed of when the request is completed. This lifetime is useful for services that access request-specific data. For example, a service that fetches a customer’s data from a database can be registered as a scoped service.

    Use the AddScoped method to add a scoped service to the service container.

    Transient lifetime

    Services registered with a transient lifetime are created each time they’re requested. This lifetime is useful for lightweight, stateless services. For example, a service that performs a specialized calculation can be registered as a transient service.

    Use the AddTransient method to add a transient service to the service container.

    g add