C-SharpCorner MVP Award 2020 🏆🏆🏆🏆🏆


The 5th Consecutive year I am getting MVP Award from C-SharpCorner Technical Community. As a IT professional we are learning new technologies in entire life. Continue your passion and one day it will help to achieve your goal. Thank you all for your support.

C# Corner MVP's 2020

C# Corner MVP’s 2020

Congrats to all other MVP’s : C# Corner Q1, 2020 MVPs Announced

Get started with Blazor Apps


Introduction

We have developed many Single Page Application using Angular,  Aurelia, React, etc. Finally the microsoft has introduced Blazor Apps and It is a programming framework to build client side rich web application with dotnet using c#. What ? Is it possible to create a Single Page Application using C# without using JavaScript ? Yes we can create a rich interactive User Interface ( UIs ) using C# instead of JavaScript and also the client and server code logic has written in the app using .Net. The Innovations are the major concerns of every era, So as a dotnet developer we can develop a Single Page Application ( SPA ) using Microsoft C#.

Blazor app have five different editions and two are now available in the Visual Studio and three editions are in a planing stage.

  • Blazor WebAssembly
  • Blazor Server
  • Blazor Progressive Web Apps (PWAs)
  • Blazor Hybrid
  • Blazor Native

The following are the currently available Blazor apps.

Blazor WebAssembly

Blazor WebAssembly is a single-page app framework for building interactive client-side web apps with .NET ( dotnet ). Blazor is running client-side in the browser on WebAssembly and the client side code has been written in C# instead of using javascript. So the .Net code is running inside the browser with the help of Webassembly(abbreviated wasm). Yes , It will work all the modern web browsers and including mobile browsers. There’s no .NET server-side dependency but the app is fully functional  after downloading the .Net runtime to the client. This will create a client-side dependency and Serverless deployment scenarios are possible because ASP.NET Core web server doesn’t required to host the app.

As per the Microsoft information “Blazor WebAssembly” is still in preview and expect to live by may 2020. So it is clear that Blazor WebAssembly is not ready for the production use and currently in a development stage.  If you’re looking for a production solution, then you can choose “Blazor Server” and it is recommended by Microsoft.

Blazor Server

Blazor Server provides support for hosting Razor components on the server in an ASP.NET Core app that means Blazor can run your client logic on the server.  The UI updates, event handling, and JavaScript calls are handled over with the help of “SignalR” ( a real-time messaging framework. ) connection. The download size is smaller than Blazor Server Comparing to Blazor WebAssembly app because those are handling in server side and the app loads much faster. Serverless deployment is not possible because an ASP.NET Core server is required to serve the app.

As daniel mentioned in the document “We have expect to have official previews of support for Blazor PWAs and Blazor Hybrid apps using Electron in the .NET 5 time frame (Nov 2020). There isn’t a road map for Blazor Native support yet. The following are the Blazor App planning editions”.

Blazor PWAs ( Progressive Web Apps )

Blazor PWAs ( Progressive Web Apps  ) are web apps that support the latest web standards to provide a more native-like experience. It will work offline and online scenarios and support push notifications, OS integrations, etc.

Blazor Hybrid

Native .Net readers to Electron and Blazor Hybrid apps don’t run on WebAssembly but instead uses a native .NET runtime like .NET Core or Xamarin. It will work offline or online scenarios.

Blazor Native

Same programming model but rendering non-HTML UI.

Note :  The application is tested in .NET Core 3.1 SDK & Visual Studio 2019 16.4 version and all the steps depend on the respective versions.

Prerequisites

  1. Install Visual Studio 2019 16.4 or later with the ASP.NET and web development workload.
  2. Install the .NET Core 3.1 SDK.

1.  Create a new project in Visual Studio 2019 ( version 16.4 ) and It lists the available project templates. So we have to  choose “Blazor App” template for development.

Create a new project

Create a new project

2. Configure new project name, solution name and location in our system.

Configure new project

3.  Based on the selected Blazor template ( Step 1 ) It will display the two available Blazor app in Visual Studio. So we have selected “Blazor Server App” from the list.

Output

We can run the application and see the first output of our Blazor Server App.

Reference

Summary

From this article we have learned the basics of microsoft Blazor Apps With Visual Studio 2019. I hope this article is useful for all the Blazor ASP.NET Core beginners.

C# Corner One Million Readers Club


Thank you all my readers !!! Thanks for the gift Atul Gupta , Praveen Kumar and C# corner team. #MVP #CsharpCorner

Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019


Introduction

There are more challenges we are facing for consuming a Web API because it contains  various methods such as GET,POST,PUT,DELETE. All these methods  contain various types of parameters like model,string,int,etc. Exactly we don’t know what property we need to pass in the model parameter and what are the relevant ones. These are the major challenges for a developer and so we need a proper documentation to solve this problem. That’s why we choose Swagger also known as OpenAPI and It  will provide all such benefits like interactive documentation, client SDK generation, and API discoverability. In this article we are explaining a lit bit basic configurations of Swagger in ASP.NET Core application. We can add more additional features on the Web API using swagger for that just read the reference document that we have mentioned in the Reference section.

We have tested the swagger documentation application in the latest VS 2019. So please check the following steps to kick start the initial process of installation.

1) Open Visual Studio 2019 and Click on “Create a new project”


2) Click on ASP.NET Core Web Application


3) Provision your new project and give the appropriate name and the location to be saved.


4) Choose API and Click on the Create button on the right side.


5) Open “Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution…” and click on Browse tab and search “Swashbuckle.AspNetCore” in the search bar and install it.

Model

We are going to create a Employee model for the demo purpose.

namespace SwaggerDocumentation.Model
{
    public class Employee
    {

        public int id { get; set; }
		
		public string Name { get; set; }
		
		public string Adress { get; set; }

		public string Department { get; set; }

    }
}

API Version Separation

In future if we are planning to release multiple versions of API, then, for the better readability purpose we can create a version folder for the API creation. This will help us to differentiate multiple versions in the API side and Swagger documentation. In the following screenshot we have created two folders one is “v1” ( Version 1 ) and another one is “v2” ( Version 2 ). obviously v2 will contain the latest version comparing to v1.

API Controller

We have created “EmployeeController” as the API controller in our application. Here we can see at the route level api path is set as “api/v1/[controller]” because when you hit the swagger it will first check the controller level then what will happen it will take two identical controller name as “Employee”. This will create ambiguous issue in the http request controller level, for that reason we have added two different request path for both versions v1 & v2.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SwaggerDocumentation.Model;

namespace SwaggerDocumentation.Controllers.v1
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        // GET: api/v1/Employee
        [HttpGet]
        public List<Employee> EmployeesDetails()
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees;
        }

        // GET: api/v1/Employee/5
        [HttpGet("{id}", Name = "Get")]
        public Employee EmployeeDetailsInformation(int id)
        {
            List<Employee> employees = new List<Employee>
            {
               new Employee
               {
                   id = 1,
                   Name = "Rajeesh",
                   Department = "Development",
                   Adress = "Menoth Parambil"
               },

               new Employee
               {
                   id = 2,
                   Name = "Arokia",
                   Department = "R/D",
                   Adress = "Trichy Central"
               },

               new Employee
               {
                   id = 3,
                   Name = "Vijay",
                   Department = "Cloud",
                   Adress = "MP Gowliyar"
               },

            };

            return employees.Find(x => x.id == id);
        }

        // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

        // PUT: api/v1/Employee/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/v1/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

IControllerModelConvention

In the ASP.NET Core MVC we have application model and it will define convention abstractions that provide a simpler way to customize the behavior of the models without overriding the entire model. In simpler way we are modifying our app to follow different conventions from the default MVC behavior. The following method is clearly describing that it will take the last name of the “namespace” and it consider as the group name of the API Version. So in this case we can easily separate out versions when we  maintain multiple version of API’s in the application. The “GroupName”  can be declared as globally and locally, but in multiple API version case we can go with global scenario.

public class ApiExplorerVersionConvention : IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.v1"
            var apiVersion = controllerNamespace.Split('.').Last().ToLower();

            controller.ApiExplorer.GroupName = apiVersion;
        }
    }

The following way we can declare group name  locally but in this scenario you need to add the following decorator for each API method .

 // POST: api/v1/Employee
        [HttpPost]
        [ApiExplorerSettings(GroupName = "v1")]
        public void Post([FromBody] string value)
        {
        }

Middleware

We need to inject swagger service in the ASP.NET Core application using the middleware in startup class. Then only we can access the entire swagger service in our application.

ConfigureServices ( Inside the Startup.cs )

ConfigureServices method gets called by the runtime so we can use this method to register the services to the container  in the application. First of all we need to add “ApiExplorerVersionConvention” convention in the MVC service like the following way.

services.AddMvc(x => x.Conventions.Add(new ApiExplorerVersionConvention()));

The following code will register the swagger in our Application. There are many properties we use in the following code like “v1” & “v2” consider as GroupName , Title is displayed as “Swagger Documentation” and “Version 1.0” & “Version 2.0” is the version separation.

// Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Swagger Documentation", Version = "Version 1.0" });
                c.SwaggerDoc("v2", new Info { Title = "Swagger Documentation", Version = "Version 2.0" });
            });

Configure ( Inside the Startup.cs )

Configure method gets called by the runtime and use this method to configure the HTTP request pipeline. We are going to enable the generated Swagger as a JSON endpoint in the middleware and it will serve to the request.

app.UseSwagger();

The swagger UI and json endpoint we can mention in the following way.

app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
            });

launchSettings.json

In launchSettings.json we can setup swagger as the launch URL. This is not mandatory to give because for the demo purpose we have given launch URL as swagger. Otherwise In middleware we have SwaggerEndpoint  “/swagger/v1/swagger.json” so you can enter in the browser like “http://localhost:44392/api/swagger&#8221;.

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:62460",
      "sslPort": 44392
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "SwaggerDocumentation": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

 

Output

Reference

Summary

From this article we have learned the Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019. I hope this article is useful for all the ASP.NET Web API beginners.

C# Corner Featured Community Leader 2019


 

Thanks a lot Mahesh Chand Sir making this wonder full video. Thank you for all the support C# Corner Team.

C-SharpCorner MVP Award 2019 🏆🏆🏆🏆


Everyday is a new beginning here in our C# Corner Community.We learn new things day by day and share the knowledge to the entire world. I as an individual had improved a lot in my technical aspects from this community. And thanks a lot for awarding me MVP for the fourth consecutive year. It is a great privilege to receive this award from the veterans. On this context I would like to thank my family and friends for staying with me during my ups and downs.

Thank you all !!

Congrats to all other MVP’s :  Q1 C# Corner MVP’s 2019

Getting Started With Angular Routing Using Angular CLI – Part Three


Introduction

In this article we are going to learn the basic routing concepts in Angular 6 using Angular CLI( Command Line Interface ). So before reading this article, you must read the following articles for more knowledge.

Routing in Application

In every application we do a minimal number of route concepts. For Eg While clicking the menu page it will redirect into child page or different page,etc. How can we do this in Angular ? Yes, There are few basic stuff we need to configure before the routing implementation in Angular.

Creating a Routing Module

By using command line parameter "--routing" we’re able to create a routing module in the Angular application. So by using any of the following command we can create routing module in Angular with the default routing setup. We have given “app-routing” as our routing module name.

ng generate module app-routing --flat --module=app
ng g m app-routing --flat --module=app

Note :

--flat puts the file in src/app instead of its own folder.
--module=app tells the CLI to register it in the imports array of the AppModule

The following code is generated after the above command execution.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: []
})
export class AppRoutingModule { }

Import Router in the Application

Angular Router is an optional service and it is not a part of "@angular/core" and Router Modules are the part of "@angular/router" library package.  So we need to import “RouterModule” and “Routes” from "@angular/router" library package.

import { RouterModule , Routes } from '@angular/router';

Add Routes

A very simple explanation in Angular docs is “Routes” tell the router which view to display when a user clicks a link or pastes a URL into the browser address bar. So the scenario is whether a click or paste a URL into the browser !!

const routes: Routes = [{}];

We have created a empty routes in our routing module, Now we need to add redirect page, default page , 404 page , etc. For this just type “a-path” inside the “{}” and It will display the possible routing options in the routing module.

Now we have added path and component name in the Routes.

const routes: Routes = [{ path: 'customer', component: CustomerComponent }];

We already know “app component” is our default launching  page in Angular application. So we need to setup a routing configuration in the app component.

RouterModule.forRoot()

We first initialize and import the router setup and it start listening the browser location changes.Whatever routes we have mentioned earlier will be injected into the forRoot().

@NgModule({
  exports: [RouterModule] ,
  imports: [
    CommonModule, [RouterModule.forRoot(routes)]
  ],
  declarations: []
})

RouterModule.forChild()

forChild() is used for the submodules and lazy loaded submodules as the following way.

@NgModule({
  exports: [RouterModule] ,
  imports: [
    CommonModule, [RouterModule.forChild(routes)]
  ],
  declarations: []
})

Router outlet

RouterOutlet  acts as a placeholder and it looks like a component. So when you place this outlet in an app component then it will be dynamically filled based on the current router state.

<router-outlet></router-outlet>

Navigation

The navigation we have added in the same app component page and while clicking on the “/customer” string content in “routerLink” then  It will redirect into the respective page. We can add more functionality in the anchor tag like active,binding array of links,etc

The Router Output

 

Page Not Found – 404 Error !!

If user is trying to access different page in the application and that is not part of the routing configuration then we need to display an Error message page called as Page Not Found. Any of the following command will create a “Page Not Found” page with using inline template.

ng generate component PageNotFound --inline-template
ng g c PageNotFound -t

We have modified the PageNotFound typescript file.

If you want to add bootstrap style in the application then import the following reference link in the style.css.

@import url('https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css');

We have updated the router URL as “PageNotFoundComponent” with path mentioned as “**” in the last route is a wildcard. if the requested URL doesn’t match any paths for routes defined in the following configuration. This will help us to displaying a “404 – Not Found” page or redirecting to another route.

const routes: Routes = [{ path: '', component: EmployeeComponent },
{ path: 'customer', component: CustomerComponent },
{ path: '**', component: PageNotFoundComponent }];

Output

Download :

Reference

Summary

From this article we have learned the basic routing concepts of  Angular CLI. I hope this article is useful for all the Angular CLI beginners.

%d bloggers like this: