Category: Uncategorized

  • Overview of Adaptive Cards

    Developers can use Adaptive Cards to create engaging messages that are rendered into a native UI that adapts to the hosted app experience. Adaptive Cards are authored in JSON can be used for Outlook Actionable Messages, Microsoft Teams conversations, and many other host applications.

    In this unit, you’ll learn about Adaptive Cards, where they can be used and how to create Adaptive Cards with the online designer.

    Adaptive Cards overview

    Adaptive Cards are platform-agnostic snippets of UI, authored in JSON, that apps and services can openly exchange. When delivered to a specific app, the JSON is transformed into native UI that automatically adapts to its surroundings. It helps design and integrate light-weight UI for all major platforms and frameworks.

    Screenshot showing different renderings of Adaptive Cards.

    The cards are created using an open card exchange format enabling developers to exchange UI content in a common and consistent way. Adaptive Cards can be rendered natively in a host application such as Outlook, Microsoft Teams, Microsoft Windows, and even custom applications.

    Goals of Adaptive Cards

    The goals for Adaptive Cards are:

    • Portable: To any app, device, and UI framework
    • Open: Libraries and schema are open source and shared
    • Low cost: Easy to define, easy to consume
    • Expressive: Targeted at the long tail of content that developers want to produce
    • Purely declarative: No code is needed or allowed
    • Automatically styled: To the Host application UX and brand guidelines

    Benefits of Adaptive Cards

    Adaptive Cards offer plenty of benefits to card authors and experience owners.

    For card authors

    Adaptive Cards are great for card authors:

    • One schema: You get a single format, minimizing the cost of creating a card and maximizing the number of places it can be used.
    • Richer expression: Your content can more closely align with want you want to say because you have a richer palette to paint with.
    • Broad reach: Your content will work across a broader set of applications without you having to learn new schemas.
    • Input controls: Your card can include input controls for gathering information from the user that is viewing the card.
    • Better tooling: An open card ecosystem means better tooling that is shared by everyone.

    For experience owners

    If you’re an app developer who wants to tap into an ecosystem of third-party content, you’ll love Adaptive Cards because:

    • Consistent user experience: You guarantee a consistent experience for your users, because you own the style of the rendered card.
    • Native performance: You get native performance as it targets your UI framework directly.
    • Safe: Content is delivered in safe payloads so you don’t have to open up your UI framework to raw markup and scripting.
    • Easy to implement: You get libraries to easily integrate on any platform you support
    • Free documentation: You save time because you don’t have to invent, implement, and document a proprietary schema.
    • Shared tooling: You save time because you don’t have to create custom tooling.

    Adaptive Card schema

    The current version of the Adaptive Card schema is v1.5. All elements in the Adaptive Card Schema Explorer display the version when they were introduced to the schema. Developers should note what elements are supported in specific schema versions because some application hosts may not currently support the latest version of the schema.

    The schema is broken up into multiple categories:

    • Cards
    • Card elements
    • Containers
    • Actions
    • Inputs
    • Types

    Each category contains multiple elements.

    https://lernix.com.my/oracle-siebel-crm-training-courses-malaysia

  • Document an API by using Swashbuckle

    Swashbuckle is a NuGet package that provides a way to automatically generate Swagger documentation for ASP.NET Web API projects. Swagger is a tool that helps developers design, build, document, and consume RESTful APIs. With Swashbuckle, you can easily add Swagger documentation to your Web API project by annotating your code with attributes that describe your API endpoints, parameters, and responses. Swashbuckle then uses this information to generate a Swagger JSON file, which can be used to generate interactive API documentation, client SDKs, and more.

    There are three main components to Swashbuckle:

    • Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.
    • Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. It’s typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.
    • Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.

    The following dotnet add command installs the Swashbuckle NuGet package:

    .NET CLICopy

    dotnet add <name>.csproj package Swashbuckle.AspNetCore -v 6.5.0
    

    Add and configure Swagger middleware

    Add the Swagger generator to the services collection in Program.cs.

    C#Copy

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    

     Note

    The call to AddEndpointsApiExplorer shown in the previous example is only required for minimal APIs.

    Enable the middleware for serving the generated JSON document and the Swagger UI, also in Program.cs:

    C#Copy

    app.UseSwagger();
    if (app.Environment.IsDevelopment())
    {
        app.UseSwaggerUI();
    }
    

    The default endpoint for the Swagger UI is http:<hostname>:<port>/swagger.

     Note

    SwaggerUI is very useful in your development environment. It can be enabled in production, but you should consider any security requirements for your specific application before doing so.

    Customize and extend the Swagger documentation

    Swagger provides options for documenting the object model and customizing the UI. The configuration action passed to the AddSwaggerGen method can include additional information through the OpenApiInfo class.

    The following code sample shows how to add information to display in the API documentation.

    C#Copy

    // Add using statement for the OpenApiInfo class
    using Microsoft.OpenApi.Models;
    
    builder.Services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "Fruit API",
            Description = "API for managing a list of fruit their stock status.",
            TermsOfService = new Uri("https://example.com/terms")
        });
    });
    
    

    The Swagger UI displays the version and the added information:

    Screenshot showing additional descriptive information added to an API.

    You can group operations in your API with the .WithTags option. You can also add descriptive text describing the operation with the .WithSummary option. The following sample code shows using .WithTags to group the POST operation into both a post group, and a fruit group. It also adds the summary specified in the .WithSummary option to the operation.

    C#Copy

    app.MapPost("/fruits", async (Fruit fruit, FruitDb db) =>
    {
        db.Fruits.Add(fruit);
        await db.SaveChangesAsync();
    
        return Results.Created($"/{fruit.Id}", fruit);
    })
        .Produces<Fruit>(201)
        .WithTags("post", "fruits")
        .WithSummary("Create a new fruit");
    

    The Swagger UI displays the specified grouping and summary description.

    Screenshot of the Swagger UI displaying the post operation in two groups with a summary description.

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

  • Bind controls to data in Blazor applications

    Blazor lets you bind HTML controls to properties so that changing values are automatically displayed in the user interface (UI).

    Suppose you’re developing a page that collects information from customers about their pizza preferences. You want to load the information from a database and enable customers to make changes, such as recording their favorite toppings. When there’s a change from the user or an update in the database, you want the new values to display in the UI as quickly as possible.

    In this unit, you learn how to use data binding in Blazor to tie UI elements to data values, properties, or expressions.

    What is data binding?

    If you want an HTML element to display a value, you can write code to alter the display. You need to write extra code to update the display when the value changes. In Blazor, you can use data binding to connect an HTML element to a field, property, or expression. This way, when the value changes, the HTML element is automatically updated. The update usually happens quickly after the change, and you don’t have to write any update code.

    To bind a control, you would use the @bind directive:

    razorCopy

    @page "/"
    
    <p>
        Your email address is:
        <input @bind="customerEmail" />
    </p>
    
    @code {
        private string customerEmail = "user@contoso.com"
    }
    

    In the preceding page, whenever the customerEmail variable changes its value, the <input> value updates.

     Note

    Controls, such as <input>, update their display only when the component is rendered and not when a field’s value changes. Because Blazor components render after any event handler code executes, in practice, updates are typically displayed quickly.

    Bind elements to specific events

    The @bind directive is smart and understands the controls it uses. For example, when you bind a value to a textbox <input>, it binds the value attribute. An HTML checkbox <input> has a checked attribute instead of a value attribute. The @bind attribute automatically uses this checked attribute instead. By default, the control is bound to the DOM onchange event. For example, consider this page:

    razorCopy

    @page "/"
    
    <h1>My favorite pizza is: @favPizza</h1>
    
    <p>
        Enter your favorite pizza:
        <input @bind="favPizza" />
    </p>
    
    @code {
        private string favPizza { get; set; } = "Margherita"
    }

    https://lernix.com.my/power-bi-training-courses-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." })" />
    

    https://lernix.com.my/prince2-certification-training-courses-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.

    In a Blazor Server app, you can create a registered service to represent a data source and obtain data from it.

     Note

    The sources of data you can use in a Blazor app include relational databases, NoSQL databases, web services, various Azure services, and many other systems. You can use .NET technologies such as Entity Framework, HTTP clients, and ODBC (Open Database Connectivity) to query those sources. These techniques are beyond the scope of this module. Here, you learn how to format and use data that you obtained from one of these sources and technologies.

    The creation of a registered service starts by writing a class that defines its properties. Here’s an example that you might write to represent a pizza:

    C#Copy

    namespace BlazingPizza.Data;
    
    public class Pizza
    {
        public int PizzaId { get; set; }
        
        public string Name { get; set; }
        
        public string Description { get; set; }
        
        public decimal Price { get; set; }
        
        public bool Vegetarian { get; set; }
        
        public bool Vegan { get; set; }
    }
    

    The class defines the pizza’s properties and data types. You must make sure these properties match the pizza schema in the data source. It makes sense to create this class in the Data folder of your project, and use a member namespace called Data. If you prefer, you can choose other folders and namespaces.

    Next, you would define the service:

    C#Copy

    namespace BlazingPizza.Data;
    
    public class PizzaService
    {
        public Task<Pizza[]> GetPizzasAsync()
        {
        // Call your data access technology here
        }
    }
    

    Notice that the service uses an asynchronous call to access data and return a collection of Pizza objects. The data source might be remote from the server where the Blazor code is running. In that case, use an asynchronous call. Then if the data source responds slowly, other code can continue to run as you await the response.

    You would register the service by adding a line to the Add Services to the container section in the Program.cs file:

    C#Copy

    ...
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddServerSideBlazor();
    // Register the pizzas service
    builder.Services.AddSingleton<PizzaService>();
    ...
    

    Using a service to obtain data

    Now you use the service you defined by calling it in a Blazor component and obtaining data. Let’s suppose you have the following component code, and you want to display pizzas in it:

    razorCopy

    @page "/pizzas"
    
    <h1>Choose your pizza</h1>
    
    <p>We have all these delicious recipes:</p>
    

    Injecting the service

    Before you can call the service from the component, you must use dependency injection to add the service. Inject the service by adding the following code after the @page directive:

    razorCopy

    @using BlazingPizza.Data
    @inject PizzaService PizzaSvc
    

    Usually, the component and the service are in different namespace members, so you must include the @using directive. This directive works in the same way as a using statement at the top of a C# code file. The @inject directive adds the service to the current component and initiates an instance of it. In the directive, specify the name of the service class. Follow it by the name you want to use for the instance of the service in this component.

    Override the OnInitializedAsync method

    A good place to call the service and obtain data is in the OnInitializedAsync method. This event fires when the component’s initialization is complete and it receives its initial parameters, but before the page is rendered and displayed to the user. The event is defined on the Blazor component’s base class. You can override it in a code block as in this example:

    C#Copy

    protected override async Task OnInitializedAsync()
    {
        \\ Call the service here
    }
    

    Call the service to obtain data

    When you call the service, use the await keyword because the call is asynchronous:

    C#Copy

    private Pizza[] todaysPizzas;
    
    protected override async Task OnInitializedAsync()
    {
        todaysPizzas = await PizzaSvc.GetPizzasAsync();
    }
    

    Displaying data to the user

    After getting some data from the service, you’ll want to display it to the user. In the pizzas example, we expect the service to return a list of pizzas that the users can choose from. Blazor includes a rich set of directives that you can use to insert this data into the page that the user sees.

    Checking for data

    First, we determine what the page displays before the pizzas are loaded by checking whether the todaysPizzas collection is null. To run conditional rendering code in a Blazor component, use the @if directive:

    razorCopy

    @if (todaysPizzas == null)
    {
        <p>We're finding out what pizzas are available today...</p>
    }
    else
    {
        <!-- This markup will be rendered once the pizzas are loaded -->
    }
    

    The @if directive renders the markup in its first code block only if the C# expression returns true. You can also use an else if code block to run other tests and render markup if they’re true. Finally, you can specify an else code block to render code if none of the previous conditions returned true. By checking for null in the @if code block, you ensure that Blazor doesn’t try to display pizza details before data is obtained from the service.

     Note

    Blazor also includes the @switch directive for rendering markup based on a test that might return multiple values. The @switch directive works in a similar way to the C# switch statement.

    Rendering a collection of objects

    If Blazor executes the else statement in the preceding code, you know that some pizzas were obtained from the service. The next task is to display these pizzas to the user. Let’s look at how to display the data in a simple HTML table.

    We don’t know how many pizzas are available when we code this page. We can use the @foreach directive to loop through all the objects in the todaysPizzas collection and render a row for each one:

    razorCopy

    <table>
     <thead>
      <tr>
       <th>Pizza Name</th>
       <th>Description</th>
       <th>Vegetarian?</th>
       <th>Vegan?</th>
       <th>Price</th>
      </tr>
     </thead>
     <tbody>
      @foreach (var pizza in todaysPizzas)
      {
       <tr>
        <td>@pizza.Name</td>
        <td>@pizza.Description</td>
        <td>@pizza.Vegetarian</td>
        <td>@pizza.Vegan</td>
        <td>@pizza.Price</td>
       </tr>
      }
     </tbody>
    </table>
    

    https://lernix.com.my/python-programming-training-courses-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.

     Note

    There are two hosting models for code in Blazor apps:

    • Blazor Server: In this model, the app is executed on the web server within an ASP.NET Core app. On the client side, UI updates, events, and JavaScript calls, are sent through a SignalR connection between the client and the server. In this module, we discuss and code for this model.
    • Blazor WebAssembly: In this model, the Blazor app, its dependencies, and the .NET runtime are downloaded and run on the browser.

    In Blazor, you build the UI from self-contained portions of code called components. Each component can contain a mix of HTML and C# code. Components are written by using Razor syntax, in which code is marked with the @code directive. Other directives can be used to access variables, bind to values, and achieve other rendering tasks. When the app is compiled, the HTML and code are compiled into a component class. Components are written as files with a .razor extension.

     Note

    Razor syntax is used for embedding .NET code into webpages. You can use it in ASP.NET MVC (Model-View-Controller) applications, where files have a .cshtml extension. Razor syntax is used in Blazor to write components. These components have the .razor extension instead, and there’s no strict separation between controllers and views.

    Here’s a simple example of a Blazor component:

    razorCopy

    @page "/index"
    
    <h1>Welcome to Blazing Pizza</h1>
    
    <p>@welcomeMessage</p>
    
    @code {
      private string welcomeMessage = "However you like your pizzas, we can deliver them blazing fast!";
    }
    

    In this example, the code sets the value of a string variable, named welcomeMessage. That variable is rendered within <p> tags in the HTML. We examine more complex examples later in this unit.

    Create Blazor components

    When you create a Blazor app by using the blazor template in the dotnet command-line interface (CLI), several components are included by default:

    BashCopy

    dotnet new blazor -o BlazingPizzaSite
    

    The default components include the Index.razor home page and the Counter.razor demo component. Both of these components are placed in the Pages folder. You can either modify these views to fit your needs, or delete them and replace them with new components.

    To add a new component to an existing web app, use this command:

    BashCopy

    dotnet new razorcomponent -n PizzaBrowser -o Pages
    
    • The -n option specifies the name of the component to add. This example adds a new file named PizzaBrowser.razor.
    • The -o option specifies the folder that you want to contain the new component.

     Important

    The name of a Blazor component must begin with an uppercase character.

    After you create the component, you can open it to be edited with Visual Studio Code:

    BashCopy

    code Pages/PizzaBrowser
    

    Write code in a Blazor component

    When you build a UI in Blazor, you mix static HTML and CSS markup with C# code, often in the same file. To differentiate these types of code, you use Razor syntax. Razor syntax includes directives, prefixed with the @ symbol, that delimit C# code, routing parameters, bound data, imported classes, and other features.

    Let’s consider this example component again:

    razorCopy

    @page "/index"
    
    <h1>Welcome to Blazing Pizza</h1>
    
    <p>@welcomeMessage</p>
    
    @code {
      private string welcomeMessage = "However you like your pizzas, we can deliver them fast!";
    }
    

    You can recognize the HTML markup with <h1> and <p> tags. This markup is the static framework of the page, into which your code inserts dynamic content. The Razor markup consists of:

    • The @page directive: This directive provides a route template to Blazor. At runtime, Blazor locates a page to render by matching this template to the URL that the user requested. In this case, it might match a URL of the form http://yourdomain.com/index.
    • The @code directive: This directive declares that the text in the following block is C# code. You can put as many code blocks as you need in a component. You can define component class members in these code blocks and set their values from calculation, data lookup operations, or other sources. In this case, the code defines a single component member called welcomeMessage and sets its string value.
    • Member access directives: If you want to include the value of a member in your rendering logic, use the @ symbol followed by a C# expression, such as the name of the member. In this case, the @welcomeMessage directive is used to render the value of the welcomeMessage member in the <p> tags.

    https://lernix.com.my/red-hat-certified-architect-rhca-malaysia

  • Use the SQLite database provider with EF Core

    In the previous unit, you learned how to persist data to an in-memory database. Persisting data to an in-memory database is useful in development. But, because all data is lost when the application is restarted, it isn’t suitable for production. In production, you should persist data to a database like SQL Server, MySQL, PostgreSQL, or SQLite.

    Database providers abstract database access from the application code

    One of the benefits of performing database access through an abstraction layer like Entity Framework (EF) Core is that it decouples your application from the database provider. You can change the database provider without rewriting your database access code. You shouldn’t expect to be able to switch database providers without any effect to your application code, but the changes will be minimized and localized.

    A related advantage of using EF Core is that you can reuse your code, experience, and data access libraries to work with any other EF Core database provider.

    For this tutorial, you’ll use SQLite database, but you might also use one that works better for you. EF Core currently supports more than 20 Database Providers.

    Steps to add a new database provider

    In general, you’ll use the following steps to implement a new database provider:

    1. Add one or more NuGet packages to your project to include the database provider.
    2. Configure the database connection.
    3. Configure the database provider in the ASP.NET Core services.
    4. Perform database migrations.

    In the next unit, you’ll walk through the steps to add the SQLite database provider. Similar steps will apply for other database providers.

    https://lernix.com.my/red-hat-certified-engineer-rhce-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; }
      }
    }
    

    The context class

    This application has only one entity class, but most applications have multiple entity classes. The context class is responsible for querying and saving data to your entity classes, and for creating and managing the database connection.

    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();
    

    Use the EF Core in-memory database

    EF Core includes an in-memory database provider that can be used to test your application. The in-memory database provider is useful for testing and development, but it shouldn’t be used in production. In the next unit, you’ll use the in-memory database provider to create a database and perform CRUD operations on it.

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

  • 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.

    Framework-dependent deployment

    An animation showing how a framework-dependent deployment depends on the presence of the .NET runtime on the target machine.

    A framework-dependent deployment includes only your app’s files and dependencies. It doesn’t include the .NET runtime. Instead, the target machine must have the .NET runtime installed in order to run the app. This type of deployment is the default for .NET apps.

    Self-contained deployment

    An animation showing how a self-contained deployment includes the .NET runtime with the app.

    A self-contained deployment includes your app’s files, dependencies, and the .NET runtime. The .NET runtime is included with the app, so the target machine doesn’t need to have the .NET runtime installed in order to run the app. Including the runtime makes self-contained deployments larger than framework-dependent deployments, but it also makes them more portable. It also makes it easier to run multiple versions of the .NET runtime side by side on the same machine.

    Choosing a deployment type

    The deployment type you choose depends on your app’s requirements and the target environment. Consider the following factors when choosing a deployment type:

    Deployment Type

    Advantages

    Disadvantages

    Framework-dependent

    • Smaller deployment size
    • Faster deployment times
    • Uses the .NET runtime installed on the target machine, regardless of operating system
    • Requires the .NET runtime to be installed on the target machine
    • Requires managing the .NET runtime versions installed on the target machine

    Self-contained

    • No need to install .NET runtime on the target machine
    • Easier to run multiple versions of .NET side by side
    • Larger deployment size
    • Slower deployment times
    • .NET runtime updates must be deployed with the app

    Where to deploy your app

    Once you’ve published your app, you can deploy it to any environment that supports ASP.NET Core. Here are a few options:

    Kestrel

    By default, ASP.NET Core apps run in ASP.NET Core’s built-in web server, Kestrel. Kestrel is cross-platform and tuned for high performance. It supports all modern web server features, including HTTPS, HTTP/2, HTTP/3, and WebSockets. It’s also customizable and extensible, so you can configure it to meet your app’s needs. Kestrel is the recommended web server for ASP.NET Core apps.

    Since Kestrel is built into ASP.NET Core, you can deploy your app to any machine capable of running .NET, including Windows, macOS, and Linux. Kestrel works great by itself, but apps running on Kestrel are often deployed behind a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. The reverse proxy server handles incoming requests from the internet and forwards them to Kestrel. This allows you to take advantage of the reverse proxy server’s features, such as load balancing, caching, and SSL termination.

    Internet Information Services (IIS)

    If you’re deploying to Windows, you can host your ASP.NET Core app in IIS. To do this, you need to install the ASP.NET Core Module for IIS. The module forwards requests from IIS to Kestrel, which runs your app. This allows you to take advantage of IIS’s features, such as process management, logging, and security.

    Containers

    If you’re deploying to a containerized environment, you can package your ASP.NET Core app as a Docker container. This allows you to run your app in any container runtime that supports Docker, such as Docker Desktop, Docker Enterprise, or Kubernetes. Containers are portable and scalable, so you can run your app on any machine that supports Docker, regardless of the underlying operating system.

    Azure

    If you’re deploying to Azure, you can host your ASP.NET Core app in Azure App Service or Azure Container Apps. Various tools make it easy to deploy your app to Azure from the command line. These tools include:

    • Azure Tools extension for Visual Studio Code
    • Visual Studio
    • Azure CLI
    • Azure Developer CLI (azd)

    https://lernix.com.my/red-hat-certified-specialist-in-deployment-and-systems-management-malaysia

  • 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.

    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>
    

    The following code sample shows how to use a combination of .NET code and HTML to create the body of a table from a data model. The @foreachstatement iterates through the Model.FruitModels data model and generates a table row containing the fruit name and if it’s available.

    razorCopy

    @* Code is truncated for readability. *@
    <tbody>
        @foreach (var obj in _fruitList ?? [])
        {
            <tr>
                <td>@obj.name</td>
                <td>@obj.instock</td>
            </tr>
        }
    </tbody>

    https://lernix.com.my/red-hat-certified-specialist-in-red-hat-enterprise-linux-diagnostics-and-troubleshooting-malaysia