Complete the challenge

Code challenges throughout these modules will reinforce what you’ve learned and help you gain some confidence before continuing on.

Challenge: Write code in the .NET Editor to display two messages

  1. Select all of the code in the .NET Editor, and press Delete or Backspace to delete it.
  2. Write code that produces the following output:OutputCopyThis is the first line. This is the second line. In the previous unit, you learned how to display a message in just one line of code, and you learned how to display a message using multiple lines of code. Use both techniques for this challenge. It doesn’t matter which technique you apply to which line, and it doesn’t matter how many ways you split one of the messages into multiple lines of code. That’s your choice.No matter how you do it, your code should produce the specified output.

Whether you get stuck and need to peek at the solution or you finish successfully, continue to the next unit to view a solution to this challenge.

microsoft system center certification training courses malaysia

How did your code work?

Let’s focus on the following line of code you wrote:

C#Copy

Console.WriteLine("Hello World!");

When you ran your code, you saw that the message Hello World! was printed to the output console. When the phrase is surrounded by double-quotation marks in your C# code, it’s called a literal string. In other words, you literally wanted the characters Hello, and so on, sent to the output.

The Console part is called a class. Classes “own” methods; or you could say that methods live inside of a class. To visit the method, you must know which class it’s in. For now, think of a class as a way to represent an object. In this case, all of the methods that operate on your output console are defined inside of the Console class.

There’s also a dot (or period) that separates the class name Console and the method name WriteLine(). The period is the member access operator. In other words, the dot is how you “navigate” from the class to one of its methods.

The WriteLine() part is called a method. You can always spot a method because it has a set of parentheses after it. Each method has one job. The WriteLine() method’s job is to write a line of data to the output console. The data that’s printed is sent in between the opening and closing parenthesis as an input parameter. Some methods need input parameters, while others don’t. But if you want to invoke a method, you must always use the parentheses after the method’s name. The parentheses are known as the method invocation operator.

Finally, the semicolon is the end of statement operator. A statement is a complete instruction in C#. The semicolon tells the compiler that you’ve finished entering the command.

Don’t worry if all of these ideas and terms don’t make sense. For now, all you need to remember is that if you want to print a message to the output console:

  • Use Console.WriteLine("Your message here");
  • Capitalize ConsoleWrite, and Line
  • Use the correct punctuation because it has a special role in C#
  • If you make a mistake, just spot it, fix it and re-run

 Tip

Create a cheat sheet for yourself until you’ve memorized certain key commands.

Understand the flow of execution

It’s important to understand the flow of execution. In other words, your code instructions were executed in order, one line at a time, until there were no more instructions to execute. Some instructions will require the CPU to wait before it can continue. Other instructions can be used to change the flow of execution.

Now, let’s test what you’ve learned. Each module features a simple challenge, and if you get stuck, you’ll be supplied with a solution. In the next unit, you’ll get a chance to write some C# on your own.

visual studio net training courses malaysia

Introduction

The C# programming language allows you to build many types of applications, like:

  • Business applications to capture, analyze, and process data
  • Dynamic web applications that can be accessed from a web browser
  • Games, both 2D and 3D
  • Financial and scientific applications
  • Cloud-based applications
  • Mobile applications

But how do you begin to write an application?

Applications are all made up of many lines of code that work together to achieve a task. By far, the best way to learn how to code is to write code. It’s encouraged that you write code along with the exercises in this module and the others in this learning path. Writing code yourself in each exercise and solving small coding challenges will accelerate your learning.

You’ll also begin learning small foundational concepts and build on them with continual practice and exploration.

In this module, you’ll:

  • Write your first lines of C# code.
  • Use two different techniques to print a message as output.
  • Diagnose errors when code is incorrect.
  • Identify different C# syntax elements like operators, classes, and methods.

By the end of this module, you’ll be able to write C# code to print a message to the standard output of a console, like the Windows Terminal. These lines of code will give you your first look at the C# syntax, and immediately provide invaluable insights.

ai and machine learning training courses malaysia

Exercise – Create an ASP.NET Core web app project from a template

Choose an Integrated Development Environment (IDE) or the shell

In this exercise, you will:

  • Create an ASP.NET Core web app project from a template.
  • Examine the structure of the created project.

Create an ASP.NET Core web app using a template

In Visual Studio Code, create a new project:

  1. Select the Explorer view:Screenshot of selecting the Explorer view.
  2. Select the Create .NET Project button. Alternatively, you can bring up the Command Palette using Ctrl+Shift+P, and then type “.NET” to find and select the .NET: New Project command.Screenshot of selecting Create .NET Project.
  3. Select the ASP.NET Core Empty project template from the list.
  4. In the Project Location dialog, create a folder named MyWebApp to contain the project.
  5. In the Command Palette, name the project MyWebApp, including matching the capitalization. Using this exact project name is important to ensure that the namespaces for code in this instruction match yours.
  6. Select Create project from the Command Palette.

Examine the structure of the project

The MyWebApp project folder contents are displayed in the Visual Studio Code Explorer:

Screenshot of the project files in the Visual Studio Code Explorer.

The MyWebApp project folder contents are displayed in the Visual Studio Code Explorer:

Screenshot of the project files in the Visual Studio Code Explorer.

The following sections contain an overview of the main project folders and files of the empty ASP.NET Core project:

The MyWebApp.csproj project file

The .csproj project file is used to:

  • Configure how to build the project
  • Specify which version of .NET to target
  • Manage project dependencies

The .sln solution file

When an ASP.NET Core project is created or opened in Visual Studio Code (with the C# Dev Kit extension), it creates a [project name].sln solution file. The [project name].sln solution file contains information for one or more related projects, including build information, settings, and any miscellaneous files that aren’t associated with just one particular project.

The obj folder

The obj folder contains intermediate files that are used by the build system, including compiled object files generated from the source files. The final build output is placed in a bin folder created during the build process.

The Properties/launchSettings.json file

The Properties/launchSettings.json file contains configuration data for how the app is launched during development. These settings include the applicationUrl property, which specifies the root URL the app uses, such as https://localhost:{port}, where {port} is a random local port number assigned when the project is created.

The launchSettings.json file contains the following configuration:

JSONCopy

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5218",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7140;http://localhost:5218",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

The Program.cs file

The Program.cs file serves as the entry point for an ASP.NET Core app and has several key purposes, which include:

  • Host configuration: Configures the host, including setting up the web server.
  • Service registration: Adds services to the app’s functionality, such as database contexts, logging, and specialized services for specific frameworks.
  • Middleware pipeline configuration: Defines the app’s request handling pipeline as a series of middleware instances.
  • Environment configuration: Sets up environment-specific settings for development, staging, and production.

In the new empty ASP.NET Core project you created, the Program.cs file contains the following minimal code:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

The following lines of code in this file create a WebApplicationBuilder with preconfigured defaults, and builds the app:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

The app.MapGet() method directly defines an endpoint that handles HTTP GET requests:

C#Copy

app.MapGet("/", () => "Hello World!");

app.MapGet("/"): Defines a route for the HTTP GET request. The / indicates this route responds to the requests made to the root URL of the app. For example, http://localhost:{port}/, where {port} is a randomly assigned port number assigned in the Properties/launchSettings.json file at project creation.

() => "Hello World!": A lambda expression that serves as the request handler. When a GET request is made to the root URL, this lambda expression is executed, and it returns the string “Hello World!”

lean six sigma certification training courses malaysia

Introduction

In this module, you create your first ASP.NET Core web app with .NET and C#.

Example scenario

You’re just getting started with ASP.NET Core. You want to understand how to quickly build your first web app and get familiar with the structure of a basic project. You want to understand how to run and serve a minimal web app on your local machine to view it in a browser.

What will we be doing?

In this module, you:

  • Review ASP.NET Core default project templates available in the .NET SDK.
  • Create an ASP.NET Core web app project from a template.
  • Examine the structure of the created project.
  • Run your web app locally and view it in a browser.
  • Review how the web app is served.
  • Make code changes during local development.

agile and scrum training courses malaysia 2

Build your first ASP.NET Core web app

Learn how to build your first web app with ASP.NET Core.

Learning objectives

By the end of this module, you’ll be able to:

  • Understand what the ASP.NET Core default project templates are.
  • Create an ASP.NET Core web app project from a template.
  • Understand the basic structure of an ASP.NET Core project.
  • Run a web app locally and view it in a browser.
  • Understand how the web app is served.
  • Make code changes during local development.

Prerequisites

  • Knowledge of what ASP.NET Core is and why it’s used
  • Basic knowledge of web app concepts
  • C# and .NET experience at the beginner level

adroid training courses malaysia

When to use ASP.NET Core

ASP.NET Core is a cross-platform, high-performance framework for building modern web applications. Whether ASP.NET Core is the right web development framework for you depends on many factors.

When to use ASP.NET Core

ASP.NET Core for web development is ideal when your web app has any of these requirements:

  • Rich user interfaces: You want to build interactive and dynamic web applications. With support for Blazor and popular front-end JavaScript frameworks, ASP.NET Core allows you to create rich user interfaces.
  • API development: You need to develop robust API services. ASP.NET Core supports both RESTful APIs and gRPC, providing flexibility for different communication needs.
  • Microservices architecture: You’re building a microservices-based architecture. ASP.NET Core’s lightweight and modular design is well-suited for microservices.
  • High performance: Your application demands high performance and scalability. ASP.NET Core is designed to handle high traffic and large-scale applications efficiently.
  • Modern development practices: You prefer modern development practices such as dependency injection, asynchronous programming, and modular architecture. ASP.NET Core supports these practices out of the box.
  • Cross-platform requirements: You need to develop applications that run on Windows, macOS, Linux and Docker. ASP.NET Core’s cross-platform capabilities make it an excellent choice for diverse environments.
  • Cloud integration: You plan to deploy your applications to the cloud. ASP.NET Core integrates seamlessly with Azure and other cloud platforms, simplifying deployment and management.
  • Security and compliance: You require strong security features and compliance with industry standards. ASP.NET Core provides built-in support for HTTPS, data protection, and other security best practices.

When ASP.NET Core might not be a good fit

ASP.NET Core might not be a good fit for your web development needs when your web app has any of these requirements:

  • Minimal requirements: Your application is a simple static page site.
  • Specific language preferences: Your team prefers working with languages other than C#. While ASP.NET Core supports multiple languages, it’s primarily designed for C# development.

agile and scrum training courses malaysia

How ASP.NET Core works

An ASP.NET Core app is essentially a .NET app with a Program.cs file that sets up the web app component features you need and gets it running.

The most basic ASP.NET Core app’s Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

With the previous code:

  • A basic ASP.NET Core web application is set up that listens for HTTP GET requests at the root URL (“/”) and responds with “Hello World!”.
  • The app is initialized, configures a single route, and starts the web server.

Blazor

You can build interactive web UI with ASP.NET Core using Blazor. Blazor is a component-based web UI framework integrated with ASP.NET Core, used for building interactive web UIs using HTML, CSS, and C#.

A reusable Blazor component, such as the following Counter component is defined in a Counter.razor file:

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++;
    }
}

With the previous code:

  • A component is created that displays a counter.
  • The @code block contains the component’s logic using C#, including a method to increment the counter.
  • The counter value is displayed and updated each time the button is clicked.
  • A component approach allows for code reuse across different parts of the application and has the flexibility to be run either in the browser or on the server in a Blazor app.

The Counter component can be added to any web page in the app by adding the <Counter /> element.

razorCopy

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

<Counter />

APIs

ASP.NET Core provides frameworks for building APIs, gRPC services, and real-time apps with SignalR to instantly push data updates to clients.

Basic Minimal API:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/hello", () => "Hello, World!");

app.Run();

With the previous code:

  • A minimal API is set up that listens for HTTP GET requests at the /hello URL and responds with “Hello, World!”.
  • The WebApplicationBuilder is used to configure the app.
  • The MapGet method defines a route and a handler for GET requests.

Middleware

ASP.NET Core uses a pipeline of middleware components to handle HTTP requests and responses. This modular approach provides flexibility, allowing you to customize and extend your application’s functionality by adding or removing middleware components as needed.

The middleware pipeline processes HTTP requests in a sequential manner, ensuring that each component can perform its designated task before passing the request to the next component in the pipeline.

Adding built-in middleware in the Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();

app.UseRouting();

app.MapStaticAssets();

app.UseAuthentication();

app.UseAuthorization();

app.MapGet("/", () => "Hello World!");

app.Run();

In the previous code, several common middleware components were added:

  • UseHttpsRedirection: Redirects HTTP requests to HTTPS.
  • UseRouting: Enables routing to map requests to endpoints.
  • MapStaticAssets: Optimizes the delivery of static files such as HTML, CSS, JavaScript, images and other assets.
  • UseAuthentication: Adds authentication capabilities.
  • UseAuthorization: Adds authorization capabilities.
  • app.MapGet: This is a simple endpoint to demonstrate that the application is running.

Dependency Injection

ASP.NET Core includes built-in support for dependency injection (DI) for configuring services that are used by the app and its various framework components.

For example, you might want to centrally configure a service using a framework like EntityFramework Core that other parts of your app depend on to access a database. You can configure a database context from EntityFramework Core as a service using dependency injection like this:

C#Copy

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
    
    public DbSet<Product> Products { get; set; } = default!;
}

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.Run();

With the previous code:

  • DbContext is configured as a service using dependency injection.
  • The WebApplicationBuilder is used to configure the app.
  • The AddDbContext method registers the DbContext with the dependency injection container.
  • The connection string is retrieved from the configuration and used to set up the database context.

Configuration

ASP.NET Core supports accessing configuration data from a variety of sources, like JSON files, environment variables, and command-line arguments.

Configuring a connection string in an appsetting.json file:

JSONCopy

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"
  }
}

In the Program.cs file:

C#Copy

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

app.Run();

With the previous code:

  • The connection string is configured in the appsettings.json file.
  • The WebApplicationBuilder is used to configure the app.
  • The AddDbContext method registers the DbContext with the dependency injection container.
  • The connection string is retrieved from the configuration and used to set up the database context.

Monitoring and diagnostics

ASP.NET Core provides a comprehensive suite of tools for monitoring and maintaining the health and performance of your applications. These features can be easily added to your application as middleware components, integrating specific functionalities into your project:

  • Built-in metrics: ASP.NET Core includes built-in metrics that track various aspects of your application’s performance, such as request rates, response times, and error rates.
  • Flexible logging framework: A flexible logging framework is built in, and supports various logging providers, including console, debug, and event source. This helps in capturing detailed logs for diagnostics and monitoring.
  • Tracing: ASP.NET Core supports distributed tracing, which helps you track the flow of requests across different services and components. This is useful for diagnosing performance issues and understanding the interactions between different parts of your application.
  • OpenTelemetry: ASP.NET Core integrates with OpenTelemetry, an open-source observability framework for cloud-native software. OpenTelemetry provides standardized APIs and instrumentation for collecting metrics, logs, and traces, enabling you to monitor and diagnose your applications more effectively.
  • Health Checks: The health checks API allows you to monitor the health of your application and its dependencies. You can configure health checks to report the status of various components, such as databases, external services, and more.
  • Diagnostics Tools: ASP.NET Core provides various diagnostic tools, such as dotnet-trace, dotnet-dump, and dotnet-gcdump, which help you collect and analyze diagnostic data from your application.

ai artificial intelligence training courses malaysia

What is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance framework for building modern web applications. This open-source framework allows developers to create web applications, services, and APIs that can run on Windows, macOS, and Linux. It is built for large-scale app development and can handle any size workload, making it a robust choice for enterprise-level applications.

Full stack web development

ASP.NET Core is a full stack web framework that seamlessly integrates front-end and back-end development needs within a single consistent framework:

  • For front-end development, ASP.NET Core includes Blazor, a component-based web UI framework based on C# that supports both server-side rendering and client-side rendering via WebAssembly.
  • Alternatively, ASP.NET Core can be integrated with JavaScript front-end frameworks like Angular, React, and Vue.

API development

ASP.NET Core is a powerful framework for API development:

  • It supports creating JSON-based APIs, gRPC services, and real-time services using SignalR.
  • With built-in OpenAPI support, developers can easily generate and visualize API documentation, simplifying the design and consumption of APIs.
  • You can use ASP.NET Core to build back-end APIs for a variety of apps, including web apps and native mobile apps.

Modular architecture

ASP.NET Core’s modular architecture offers a flexible approach to modern web development:

  • This architecture includes support for dependency injection, middleware, configuration, and logging.
  • Middleware components can be configured to handle requests and responses, including built-in middleware for authentication, routing, session management, and static file serving.
  • The dependency injection design pattern enhances testability and maintainability.

Security built-in

ASP.NET Core helps you build secure applications thanks to its robust built-in security features for authentication and authorization. These features help applications manage user identities and protect sensitive data effectively.

Increased productivity

Overall, ASP.NET Core provides a productive development experience, enabling developers to build high-quality full stack web apps efficiently and effectively.

cloud computing training courses malaysia

Introduction

Building modern web applications involves managing a complex stack of technologies and ensuring seamless integration between the front-end and back-end. Developers need a framework that provides robust tools for creating scalable, high-performance web applications while simplifying the development process. ASP.NET Core is a comprehensive framework within the .NET ecosystem designed for modern web development that effectively and efficiently addresses these challenges.

In this module, you discover what ASP.NET Core is, gain an overview of how it works, and learn when to use it.

Scenario

Imagine you and your team are asked to create a web app for an online store. Your team might be expected to provide any number of the following modern web app features:

  • Customer browsing and search options to navigate a wide selection of goods.
  • Authentication, authorization, profile management, and order tracking.
  • Secure customer payment interaction for purchases.
  • Real-time interactive chat with the store’s customer service team.
  • App logging and health monitoring.
  • Cloud-ready, environment-based configuration.

ASP.NET Core provides the tools and libraries needed to implement these features and more, efficiently and seamlessly, ensuring a high-quality user experience and robust application performance.

What is the main goal?

By the end of this session, you’ll know:

  • What ASP.NET Core features will help you successfully meet modern web app demands.
  • An overview of how ASP.NET Core works.
  • When to use ASP.NET Core.

kubernetes containarization training courses malaysia