Blog

  • Data binding and events

    Let’s explore how to define component rendering logic and handle UI events.

    Render C# expression values

    When you want to render the value of a C# expression in Razor, you use a leading @ character. For example, a Counter component can render the value of its currentCount field like this:

    razorCopy

    <p role="status">Current count: @currentCount</p>
    

    Razor can typically figure out when a C# expression ends and you transition back to writing HTML. But you can also be explicit about the beginning and ending of the expression using parens.

    razorCopy

    <p role="status">Current count: @(currentCount)</p>
    

    Add control flow

    You can add control flow to your component rendering logic using normal C# statements. For example, you can conditionally render some content using a C# if-statement, like this:

    razorCopy

    @if (currentCount > 3)
    {
        <p>You win!</p>
    }
    

    You can also use C# to loop over data and render a list of items:

    razorCopy

    <ul>
        @foreach (var item in items)
        {
            <li>@item.Name</li>
        }
    </ul>
    

    Handle events

    Blazor components often handle UI events. To specify an event callback for an event from a UI element, you use an attribute that starts with @on and ends with the event name. For example, you can specify the IncrementCount method as a handler for a button click event using the @onclick attribute, like this:

    razorCopy

    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    

    You can specify C# event handlers for other HTML events too, like @onchange@oninput, and so on. Event handling methods can be synchronous or asynchronous. You can also define event handlers inline using C# lambda expressions:

    razorCopy

    <button class="btn btn-primary" @onclick="() => currentCount++">Click me</button>
    

    Event handler methods can optionally take an event argument with information about the event. For example, you can access the value of an input element that changed, like this:

    razorCopy

    <input @onchange="InputChanged" />
    <p>@message</p>
    
    @code {
        string message = "";
    
        void InputChanged(ChangeEventArgs e)
        {
            message = (string)e.Value;
        }
    }
    

    After an event handler runs, Blazor will automatically render the component with its new state, so the message is displayed after the input changes.

    https://lernix.com.my/g-add

  • Razor components

    Now that you have your development environment set up, let’s explore the structure of a Blazor project and learn how Blazor components work.

    The Home page

    The app’s home page is defined by the Home.razor file located inside the Components/Pages directory. Home.razor contains the following code:

    razorCopy

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    

    The @page directive at the top specifies the route for this page, so that the Home component is displayed when the user navigates to the root of the app. The PageTitle tag is a Blazor component that sets the title for the current page so that it shows up in the browser tab. The rest of the file is normal HTML that defines the content for the page.

    What is Razor?

    Razor is a markup syntax based on HTML and C#. A Razor file (.razor) contains plain HTML and then C# to define any rendering logic, like for conditionals, control flow, and expression evaluation. Razor files are then compiled into C# classes that encapsulate the component’s rendering logic.

    What are Razor components?

    If you explore the files in the Blazor project, you notice that most of the files that make up the project are .razor files. In Blazor, a Razor file defines a reusable component that makes up a portion of the app UI. Components define what HTML to render and how to handle user events.

    At compile time, each Razor component is built into a C# class. The class can include common UI elements like state, rendering logic, lifecycle methods, and event handlers. Because Blazor components authored in Razor are just C# classes, you can use arbitrary .NET code from your components.

    Using components

    To use a component from another component, you add an HTML-style tag with a name that matches the component name. For example, if you have a component named MyButton.razor, you can add a MyButton component to another component by adding a <MyButton /> tag.

    Component parameters

    Components can also have parameters, which allow you to pass data to the component when it’s used. Component parameters are defined by adding a public C# property to the component that also has a [Parameter] attribute. You can then specify a value for a component parameter using an HTML-style attribute that matches the property name. The value of the parameter can be any C# expression.

    The @code block

    The @code block in a Razor file is used to add C# class members (fields, properties, and methods) to a component. You can use the @code to keep track of component state, add component parameters, implement component lifecycle events, and define event handlers.

    Try the Counter

    In the running app, navigate to the Counter page by selecting the Counter tab in the sidebar on the left. The following page should then be displayed:

    Screenshot of the Counter in the running app.

    Select the Click me button to increment the count without a page refresh. Incrementing a counter in a webpage normally requires writing JavaScript, but with Blazor, you can use C#.

    You can find the implementation of the Counter component at Components/Pages/Counter.razor.

    razorCopy

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

    A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content. The @rendermode directive enables interactive server rendering for the component, so that it can handle user interface events from the browser.

    Each time you select the Click me button:

    • The onclick event is fired.
    • The IncrementCount method is called.
    • The currentCount is incremented.
    • The component is rendered to show the updated count.

    https://lernix.com.my/contact

  • Configure your development environment

    To get started with Blazor, you first need to install the .NET SDK and an appropriate code editor.

    Using the .NET SDK

    The .NET SDK includes templates for creating different kinds of .NET projects. You create a new project using the dotnet new <template-name> command. For example, to create a new Blazor web app project, you can run dotnet new blazor. Tools like Visual Studio and Visual Studio Code provide convenient user interfaces for creating .NET projects using the templates in the .NET SDK.

    Once you create a new .NET project, you can build and run the project using the dotnet build and dotnet run commands. You can use the dotnet watch command to build and run a project, then automatically apply code changes as they’re made. You can run and debug .NET projects from within Visual Studio and Visual Studio Code.

    Blazor tooling

    Blazor tooling is available with Visual Studio on Windows and with the C# Dev Kit extension for Visual Studio Code, which is supported on Windows, macOS, and Linux. Visual Studio on Windows is a fully integrated development environment (IDE), while Visual Studio Code is a lighter-weight code editor with a rich ecosystem of extensions. Both have free options available for learning and community use. When you install Visual Studio on Windows, it automatically includes the .NET SDK. The .NET SDK isn’t currently included with the C# Dev Kit for Visual Studio Code and must be installed separately.

    https://lernix.com.my/g-add-m

  • CRUD actions in ASP.NET Core

    Our pizza service supports CRUD operations for a list of pizzas. These operations are performed through HTTP verbs, which are mapped via ASP.NET Core attributes. As you saw, the HTTP GET verb is used to retrieve one or more items from a service. Such an action is annotated with the [HttpGet] attribute.

    The following table shows the mapping of the four operations that you’re implementing for the pizza service:

    HTTP action verbCRUD operationASP.NET Core attribute
    GETRead[HttpGet]
    POSTCreate[HttpPost]
    PUTUpdate[HttpPut]
    DELETEDelete[HttpDelete]

    You already saw how GET actions work. Let’s learn more about POSTPUT, and DELETE actions.

    POST

    To enable users to add a new item to the endpoint, you must implement the POST action by using the [HttpPost] attribute. When you pass the item (in this example, a pizza) into the method as a parameter, ASP.NET Core automatically converts any application/JSON sent to the endpoint into a populated .NET Pizza object.

    Here’s the method signature of the Create method that you’ll implement in the next section:

    C#Copy

    [HttpPost]
    public IActionResult Create(Pizza pizza)
    {            
        // This code will save the pizza and return a result
    }
    

    The [HttpPost] attribute maps HTTP POST requests sent to http://localhost:5000/pizza by using the Create() method. Instead of returning a list of pizzas, as we saw with the Get() method, this method returns an IActionResult response.

    IActionResult lets the client know if the request succeeded and provides the ID of the newly created pizza. IActionResult uses standard HTTP status codes, so it can easily integrate with clients regardless of the language or platform they’re running on.

    ASP.NET Core
    action result
    HTTP status codeDescription
    CreatedAtAction201The pizza was added to the in-memory cache.
    The pizza is included in the response body in the media type, as defined in the accept HTTP request header (JSON by default).
    BadRequest is implied400The request body’s pizza object is invalid.

    Fortunately, ControllerBase has utility methods that create the appropriate HTTP response codes and messages for you. You’ll see how those methods work in the next exercise.

    PUT

    Modifying or updating a pizza in our inventory is similar to the POST method that you implemented, but it uses the [HttpPut] attribute and takes in the id parameter in addition to the Pizza object that needs to be updated:

    C#Copy

    [HttpPut("{id}")]
    public IActionResult Update(int id, Pizza pizza)
    {
        // This code will update the pizza and return a result
    }
    

    Each ActionResult instance used in the preceding action is mapped to the corresponding HTTP status code in the following table:

    ASP.NET Core
    action result
    HTTP status codeDescription
    NoContent204The pizza was updated in the in-memory cache.
    BadRequest400The request body’s Id value doesn’t match the route’s id value.
    BadRequest is implied400The request body’s Pizza object is invalid.

    DELETE

    One of the easier actions to implement is the DELETE action, which takes in just the id parameter of the pizza to remove from the in-memory cache:

    C#Copy

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        // This code will delete the pizza and return a result
    }
    

    Each ActionResult instance used in the preceding action is mapped to the corresponding HTTP status code in the following table:

    ASP.NET Core
    action result
    HTTP status codeDescription
    NoContent204The pizza was deleted from the in-memory cache.
    NotFound404A pizza that matches the provided id parameter doesn’t exist in the in-memory cache.

    The exercise in the next unit demonstrates how to support each of the four actions in the web API.

    https://lernix.com.my/php-and-mysql-training-courses-malaysia

  • ASP.NET Core Web API Controllers

    In the previous exercise, you created a web application that provides sample weather forecast data, then interacted with it in the HTTP Read-Eval-Print Loop (REPL).

    Before you dive in to writing your own PizzaController class, let’s look at the code in the WeatherController sample to understand how it works. In this unit, you learn how WeatherController uses the ControllerBase base class and a few .NET attributes to build a functional web API in a few dozen lines of code. After you understand those concepts, you’re ready to write your own PizzaController class.

    Here’s the code for the entire WeatherController class. Don’t worry if it doesn’t make sense yet. Let’s go through it step by step.

    C#Copy

    using Microsoft.AspNetCore.Mvc;
    
    namespace ContosoPizza.Controllers;
    
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
    
        private readonly ILogger<WeatherForecastController> _logger;
    
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

    https://lernix.com.my/red-hat-openstack-training-courses-malaysia

  • REST in ASP.NET Core

    When you browse to a webpage, the web server communicates with your browser by using HTML, CSS, and JavaScript. For example, If you interact with the page by submitting a sign-in form or selecting a buy button, the browser sends the information back to the web server.

    In a similar way, web servers can communicate with a broad range of clients (browsers, mobile devices, other web servers, and more) by using web services. API clients communicate with the server over HTTP, and the two exchange information by using a data format such as JSON or XML. APIs are often used in single-page applications (SPAs) that perform most of the user-interface logic in a web browser. Communication with the web server primarily happens through web APIs.

    REST: A common pattern for building APIs with HTTP

    Representational State Transfer (REST) is an architectural style for building web services. REST requests are made over HTTP. They use the same HTTP verbs that web browsers use to retrieve webpages and send data to servers. The verbs are:

    • GET: Retrieve data from the web service.
    • POST: Create a new item of data on the web service.
    • PUT: Update an item of data on the web service.
    • PATCH: Update an item of data on the web service by describing a set of instructions about how the item should be modified. The sample application in this module doesn’t use this verb.
    • DELETE: Delete an item of data on the web service.

    Web service APIs that adhere to REST are called RESTful APIs. They’re defined through:

    • A base URI.
    • HTTP methods, such as GETPOSTPUTPATCH, or DELETE.
    • A media type for the data, such as JavaScript Object Notation (JSON) or XML.

    An API often needs to provide services for a few different but related things. For example, our pizza API might manage pizzas, customers, and orders. We use routing to map URIs (uniform resource identifiers) to logical divisions in our code, so that requests to https://localhost:5000/pizza are routed to PizzaController and requests to https://localhost:5000/order are routed to OrderController.

    https://lernix.com.my/microsoft-system-center-certification-training-courses-malaysia

  • Monitor data insights

    To understand how Microsoft Search is performing in your organization, review your usage analytics in the Insights section of the Search & intelligence settings. For more information, see Microsoft Search Usage Reports.

    Search data is available for:

    • Office.com
    • Microsoft Search in Bing work tab (page URLs that begin with bing.com/work)
    • SharePoint Home (the site with URL ending in /SharePoint.aspx)

    Search insights include reports and data for:

    ReportDescription
    Query volumeThe total number of search queries performed. Use to determine periods of high and low search activity. Low volume may indicate a lack of user awareness of Microsoft Search or search entry points.
    Top queriesThe most popular search queries in your organization. Use to understand the types of information your users are searching for.
    No results queriesPopular search queries that returned no results and might create user dissatisfaction. Use to identify potential content gaps or improve discoverability of existing content.
    Abandoned queriesThe most popular search queries with low click-through. Use to identify potential content gaps or adjust keywords and settings of existing content.

    To get an Excel file with this same data, use the download arrow next to each report.

    https://lernix.com.my/visual-studio-net-training-courses-malaysia

  • Review bookmarks and keep content current

    Providing authoritative and accurate information in answers is critical to keeping users engaged with search. Search admins or editors should review suggested bookmarks regularly.

    Review suggested bookmarks

    Microsoft Search will evaluate SharePoint sites in your organization to identify high-traffic links and publish bookmarks for them. This evaluation is done on a 30-day cycle. If you opt to add them to your suggested bookmarks list instead of automatically publishing them, we encourage you to review the suggestions every month.

    Keep seasonal content current

    Answers that reference recurring events should be reviewed and updated on an ongoing basis. They might include information about:

    • Annual meetings
    • Benefit enrollment periods
    • Holidays and holiday events
    • Quarterly reports and deadlines

    You can also use settings to publish or expire a bookmark or Q&A on a specific date.

    https://lernix.com.my/ai-and-machine-learning-training-courses-malaysia

  • Increase Microsoft Search adoption, monitor usage, and maintain answers

    User adoption of Microsoft Search ensures your organization is getting a return on the time and effort spent optimizing and deploying the search experience. This module outlines the ready-to-share and customizable content available, and actions you can take to evangelize Microsoft Search. Keeping your work or school answer content current is also an important task. We’ll go over how to review and publish suggested bookmarks and share tips for managing seasonal content. In the last part of this module, we’ll cover how to access and monitor Microsoft Search usage reports. The insights generated from these reports can help you gauge how search is performing in your organization and guide actions to improve it.

    Scenario: A large retailer is ready to implement Microsoft Search. The organization’s Search admin is looking for support and ways to make sure the launch is a success. Since many at the company don’t know about this new work search tool, the IT team is looking for specific ways to improve user awareness. The Search admin is considering conducting some sort of launch event or training and knows they’ll have to implement a communication campaign.

    Learning objectives

    Once you’ve completed this module, you should be able to:

    • Develop a plan to evangelize Microsoft Search in your organization.
    • Download, review, and share the Microsoft Search adoption kit and other documentation.
    • Ensure work or school results are correct and current.
    • Access and monitor Microsoft Search data insights and reports.

    https://lernix.com.my/2024-02-09T10:12:46+00:00

  • Create answers faster

    The Import/Export feature and the Microsoft Search content creator extension can speed up the answer creation process.

    Import SharePoint promoted results

    If you use SharePoint promoted results, import them as suggested bookmarks.

    1. Go to Bookmarks in the Microsoft 365 admin center.
    2. Select Import.
    3. On the Import panel, select SharePoint.
    4. Select Import from SharePoint.

    Import and export answers using a .csv file

    Use the Import/Export feature to export content, bulk edit in a .csv file, and then import the updated answers.

    To import or export bookmarks:

    1. Go to Bookmarks in the Microsoft 365 admin center.
    2. Select Export.
    3. Bulk edit the content of the .csv file and Save.
    4. Import the edited .csv file.
    5. Publish draft bookmarks.

    You can also import or export acronyms, Q&As, and locations.

    Use the content creator extension

    The Microsoft Search content creator extension lets you publish bookmarks and Q&As from your browser. It’s compatible with both Google Chrome and Microsoft Edge.

    After you add the extension, you’ll see an icon in your browser that looks like this:

    Image showing Microsoft Search content creator extension icon in a browser.

    To create and publish answers using the extension:

    1. Select the content creator icon.
    2. Sign in with your Search admin or editor account.
    3. Go to any page, then select Add bookmark or Add Q&A.
    4. Add a title, URL, description, and keywords or edit the ones that appear. Image showing fields for adding a bookmark using the Microsoft Search content creator extension.
    5. Select Publish or Save to draft.

    https://lernix.com.my/986-2/2024-03-25T07:25:32+00:00