Category: Uncategorized

  • 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

  • Interfaces and dependency injection

    To avoid dependencies on a specific service implementation, you can instead configure a service for a specific interface and then depend just on the interface. This approach gives you the flexibility to swap out the service implementation, which makes the code more testable and easier to maintain.

    Consider an interface for the PersonService class:

    C#Copy

    public interface IPersonService
    {
        string GetPersonName();
    }
    

    This interface defines the single method, GetPersonName, that returns a string. This PersonService class implements the IPersonService interface:

    C#Copy

    internal sealed class PersonService : IPersonService
    {
        public string GetPersonName()
        {
            return "John Doe";
        }
    }
    

    Instead of registering the PersonService class directly, you can register it as an implementation of the IPersonService interface:

    C#Copy

    var builder = WebApplication.CreateBuilder(args);
        
    builder.Services.AddSingleton<IPersonService, PersonService>();
    var app = builder.Build();
    
    app.MapGet("/", 
        (IPersonService personService) => 
        {
            return $"Hello, {personService.GetPersonName()}!";
        }
    );
        
    app.Run();
    contact

  • Understand dependency injection

    ASP.NET Core apps often need to access the same services across multiple components. For example, several components might need to access a service that fetches data from a database. ASP.NET Core uses a built-in dependency injection (DI) container to manage the services that an app uses.

    Dependency injection and Inversion of Control (IoC)

    The dependency injection pattern is a form of Inversion of Control (IoC). In the dependency injection pattern, a component receives its dependencies from external sources rather than creating them itself. This pattern decouples the code from the dependency, which makes code easier to test and maintain.

    Consider the following Program.cs file:

    C#Copy

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using MyApp.Services;
    
    var builder = WebApplication.CreateBuilder(args);
        
    builder.Services.AddSingleton<PersonService>();
    var app = builder.Build();
    
    app.MapGet("/", 
        (PersonService personService) => 
        {
            return $"Hello, {personService.GetPersonName()}!";
        }
    );
        
    app.Run();
    

    And the following PersonService.cs file:

    C#Copy

    namespace MyApp.Services;
    
    public class PersonService
    {
        public string GetPersonName()
        {
            return "John Doe";
        }
    }
    

    To understand the code, start with the highlighted app.MapGet code. This code maps HTTP GET requests for the root URL (/) to a delegate that returns a greeting message. The delegate’s signature defines an PersonService parameter named personService. When the app runs and a client requests the root URL, the code inside the delegate depends on the PersonService service to get some text to include in the greeting message.

    Where does the delegate get the PersonService service? It’s implicitly provided by the service container. The highlighted builder.Services.AddSingleton<PersonService>() line tells the service container to create a new instance of the PersonService class when the app starts, and to provide that instance to any component that needs it.

    Any component that needs the PersonService service can declare a parameter of type PersonService in its delegate signature. The service container will automatically provide an instance of the PersonService class when the component is created. The delegate doesn’t create the PersonService instance itself, it just uses the instance that the service container provides.

    https://lernix.com.my/g-add-m
  • Retrieve application log files

    Log files are a great resource for a Web developer, but only if you know how to find and use the logged information. Here, you look at the methods you can use to retrieve logged information for offline analysis.

    Log file storage locations

    The Azure infrastructure used to run Azure Web Apps in Windows isn’t the same as for Linux apps, and log files aren’t stored in the same locations.

    Windows app log files

    For Windows apps, file system log files are stored in a virtual drive that is associated with your Web App. This drive is addressable as D:\Home, and includes a LogFiles folder; within this folder are one or more subfolders:

    • Application – Contains application-generated messages, if File System application logging is enabled.
    • DetailedErrors – Contains detailed Web server error logs, if Detailed error messages are enabled.
    • http – Contains IIS-level logs, if Web server logging is enabled.
    • W3SVC<number> – Contains details of all failed http requests, if Failed request tracing is enabled.

    Where storage to a Blob container is enabled, logs are stored in year, month, date, and hour folders, for example:Copy

    2019
      01
       10
        08 - log entries for the period 08:00:00 to 08:59:59 on January 10th 2019
        09 - log entries for the period 09:00:00 to 09:59:59 on January 10th 2019
    

    Within the hour folder, there are one or more CSV files containing messages saved within that 60-minute period.

    Linux app log files

    For Linux Web Apps, the Azure tools currently support fewer logging options than for Windows apps. Redirections to STDERR and STDOUT are managed through the underlying Docker container that runs the app, and these messages are stored in Docker log files. To see messages logged by underlying processes, such as Apache, you need to open an SSH connection to the Docker container.

    Methods for retrieving log files

    How you retrieve log files depends on the type of log file, and on your preferred environment. For file system logs, you can use the Azure CLI or the Kudu console. Kudu is the engine behind many features in Azure App Service related to source control based deployment.

    php and mysql training courses malaysia
  • View live application logging with the log streaming service

    In this unit, you look at how to view a live app log stream, and how live log streams can help during Web app development.

    What is live log streaming?

    Live log streaming is an easy and efficient way to view live logs for troubleshooting purposes. Live log streaming provides a quick view of all the messages sent to the app logs in the file system, without having to go through the process of locating and opening the logs. To use live logging, you connect to the live log service from the command line, and you can then see text being written to the app’s logs in real time.

    What logs can be streamed?

    The log streaming service adds a redirect from the file system logs, so that you see the same information that is saved to the log files. So, if you enable verbose logging for ASP.NET Windows apps, for example, the live log stream shows all your logged messages.

    Screenshot of Azure portal live log stream pane showing output from the asp logs container.

    Typical scenarios for using live logging

    Live logging is a useful tool for initial debugging. Real time log messages give you immediate feedback for code or server issues. You can then make a change, redeploy your app, and instantly see the results.

    The live log stream connects to a single app instance, so it’s not useful if you have a multi-instance app. Live logging is also of limited use as you scale up your apps. In these scenarios, it’s better to ensure that messages are saved to log files that can be opened and studied offline.

    red hat openstack training courses malaysia

  • ASP.NET

    ASP.NET apps only run on Windows app services. To log information to the app diagnostics log, use the System.Diagnostics.Trace class. There are four trace levels you can use, that correlate with the error, warning, information, and verbose logging levels shown in the Azure portal:

    • Trace.TraceError(“Message”); // Writes an error message
    • Trace.TraceWarning(“Message”); // Writes a warning message
    • Trace.TraceInformation(“Message”); // Writes an information message
    • Trace.WriteLine(“Message”); // Writes a verbose message

    ASP.NET Core apps

    ASP.NET Core apps can run on either Windows or Linux. To log information to Azure app logs, use the logger factory class, and then use one of six-log levels:

    • logger.LogCritical(“Message”); // Writes a critical message at log level 5
    • logger.LogError(“Message”); // Writes an error message at log level 4
    • logger.LogWarning(“Message”); // Writes a warning message at log level 3
    • logger.LogInformation(“Message”); // Writes an information message at log level 2
    • logger.LogDebug(“Message”); // Writes a debug message at log level 1
    • logger.LogTrace(“Message”); // Writes a detailed trace message at log level 0

    For ASP.NET Core apps on Windows, these messages relate to the filters in the Azure portal in this way:

    • Levels 4 and 5 are error messages.
    • Level 3 is a warning message.
    • Level 2 is an information message.
    • Levels 0 and 1 are verbose messages.

    For ASP.NET Core apps on Linux, only error messages (levels 4 and 5) are logged.

    Node.js apps

    For script-based Web apps, such as Node.js apps on Windows or Linux, app logging is enabled using the console() method:

    • console.error(“Message”); // Writes a message to STDERR.
    • console.log(“Message”); // Writes a message to STDOUT.

    Both types of message are written to the Azure app service error level logs.

    microsoft system center certification training courses malaysia
  • Enable and configure App Service application logging

    In this unit, we look at how app logging can help with your Web apps, and show you how to enable app logs.

    What are app logs?

    Azure provides built-in diagnostics with app logging. App logs are the output of runtime trace statements in app code. For example, you might want to check some logic in your code by adding a trace to show when a particular function is being processed. Or, you might only want to see a logged message when a particular level of error occurs. App logging is primarily for apps in preproduction and for troublesome issues, because excessive logs can carry a performance hit and quickly consume storage. For this reason, logging to the file system is automatically disabled after 12 hours.

    App logging has scale limitations, primarily because files are being used to save the logged output. If you have multiple instances of an app, and the same storage is shared across all instances, messages from different instances might be interleaved, making troubleshooting difficult. If each instance has its own log file, then there are multiple logs, again making it difficult to troubleshoot instance-specific issues.

    The types of logging available through the Azure App Service depends on the code framework of the app, and on whether the app is running on a Windows or Linux app host.

    visual studio net training courses malaysia
  • Scale up a web app

    Scaling out enables you to run more instances of a web app. The pricing tier determines resources available to each instance used by the App Service plan that hosts the web service. Each pricing tier specifies the computing power provided, together with the memory and maximum number of instances that can be created.

    If you initially deploy a web app using a relatively cheap pricing tier, you might find the resources are sufficient to start with. But the resources might become too limited if demand for your web service grows, or if you add features that require more power. In this case, you can scale up to a more powerful pricing tier.

    In the hotel reservation system, you notice a steady increase in the number of visitors, beyond the variations caused by special offers or events. Your company is adding more features to the web app that require more resources. You’re nearing the scale-out limits of your current App Service plan pricing tier, so you need to scale up to a tier that provides more instances and more powerful hardware.

    In this unit, you learn how to scale up the web app to meet the increasing resource requirements.

    ai and machine learning training courses malaysia
  • Scale a web app manually

    By manually scaling out and back in again, you can respond to expected increases and decreases in traffic. Scaling out has the extra benefit of increasing availability because of the increased number of instances of the web app. A failure of one instance doesn’t make the web app unavailable.

    In the hotel reservation system, you can scale out before an anticipated seasonal influx. You can scale back in when the season is over and the number of booking requests is reduced.

    In this unit, you learn how to manually scale out a web app and how to scale it back in.

    App Service plans and scalability

    A web app that runs in Azure typically uses Azure App Service to provide the hosting environment. App Service can arrange for multiple instances of the web app to run. It load balances incoming requests across these instances. Each instance runs on a virtual machine.

    An App Service plan defines the resources available to each instance. The App Service plan specifies the operating system (Windows or Linux), the hardware (memory, CPU processing capacity, disk storage, and so on), and the availability of services like automatic backup and restore.

    Azure provides a series of well-defined App Service plan tiers. This list summarizes each of these tiers, in increasing order of capacity and cost:

    • The Free tier provides 1 GB of disk space and support for up to 10 apps, but only a single shared instance and no SLA for availability. Each app has a compute quota of 60 minutes per day. The Free service plan is suitable for app development and testing rather than production deployments.
    • The Shared tier provides support for more apps (up to 100) also running on a single shared instance. Apps have a compute quota of 240 minutes per day. There’s no availability SLA.
    • The Basic tier supports an unlimited number of apps and provides more disk space. Apps can be scaled out to three dedicated instances. This tier provides an SLA of 99.95% availability. There are three levels in this tier that offer varying amounts of computing power, memory, and disk storage.
    • The Standard tier also supports an unlimited number of apps. This tier can scale to 10 dedicated instances and has an availability SLA of 99.95%. Like the Basic tier, this tier has three levels that offer an increasingly powerful set of computing, memory, and disk options.
    • The Premium tier gives you up to 20 dedicated instances, an availability SLA of 99.95%, and multiple levels of hardware.
    • The Isolated tier runs in a dedicated Azure virtual network, which gives you a network and computes isolation. This tier can scale out to 100 instances and has an availability SLA of 99.95%.
    lean six sigma certification training courses malaysia