Building and Deploying Micro Services with Azure Kubernetes Service (AKS) and Azure DevOps – Part-2

Reference Architecture for Docker containerized applications

Here is the workflow for deploying Micro Services into Azure Kubernetes using Azure DevOps:

s1

  1. Change application source code
  2. Commit Application Code
  3. Continuous integration triggers application build, container image build and unit tests
    • Container image pushed to Azure Container Registry
  4. Continuous deployment trigger orchestrates deployment of application artifacts with environment specific parameters
  5. Deployment to Azure Kubernetes Service
    • Container is launched using Container Image from Azure Container Registry
  6. Application Insights collects and analyses health, performance and usage data
    • Review health, performance and usage information

The above reference architecture has two loops:

  1. Inner-loop development workflow for Docker apps
  2. DevOps outer-loop workflow for Docker applications with Microsoft Tools

Inner-loop development workflow for Docker apps

It all starts from each developer’s machine where a developer using his/her preferred languages/platforms, and testing it locally. In this specific workflow you are always developing and testing Docker containers, but first, we do development and debug locally.

Picture2

The container or instance of a Docker image will contain these components:

  • An operating system selection (e.g., a Linux distribution or Windows)
  • Files added by the developer (e.g., app binaries, etc.)
  • Configuration (e.g., environment settings and dependencies) Instructions for what processes to run by Docker

The inner-loop development workflow that utilizes Docker can be set up as the following process. Take into account that the initial steps to set up the environment is not included, as that has to be done just once.

Workflow for building a single ASP.NET Core Web app inside a Docker container using Visual Studio

An app will be developed using  some code plus additional libraries (Dependencies).

The following steps are the basic steps usually needed when building a Docker app, as illustrated in the below Figure.

Picture12

Before, you start developing your application, you must first start your local Docker, i.e. already installed in your local machine. After that, you have to switch local Docker from Windows containers to Linux containers. To learn more Docker Settings, see Docker Settings.

Picture7

Step 1. Start coding in VS 2017 for Creating ASP.NET Core Web Application

The way you develop your application is pretty similar to the way you do it without Docker. The difference is that while developing, you are deploying and testing your application or services running within Docker containers placed in your local environment (like a Linux VM or Windows).

This step explains how to create ASP.NET Core Web application.

Before the proceeding to create the ASP.NET core applications, you must have the following prerequisites in your development machine.

  • Visual Studio Enterprise 2017
  • Docker for windows
  • Install latest version of .Net Core 2.0 SDK

If you are not having the above prerequisites in your development machine, please follow the below steps:

Set up a local environment for Dockers

Set up Development environment for Docker apps

Create an ASP.NET Core web app
  1. Open your Visual Studio 2017

    s3

  2. From Visual Studio, select File > New > Project.

    s4

  3. Complete the New Project dialog:
    • In the left pane, tap .NET Core
    • In the center pane, tap ASP.NET Core Web Application (.NET Core)
    • Name the project “WebApplication” (It’s important to name the project    “WebApplication ” so when you copy code, the namespace will match.)
    • Name the solution “AKSDemo”
    • Tap OK

      s5

Step 2. Add Docker support to an web app

                1. Complete the New ASP.NET Core Web Application (.NET Core)WebApplication dialog:
                  • In the version selector drop-down box select ASP.NET Core 2.0
                  • Select Web Application(Model-View-Controller)
                  • Check the option as Enable Docker support checkbox
                  • Choose OS as Linux from dropdown list
                  • Tap OK.
                    s6
                2. Now the Solution Explorer in your Visual Studio 2017 will be looks like below figure.

                  s9
                  When you add Docker support to a service project in your solution, Visual Studio is not just adding a DockerFile file to your project, and it also is adding a service section in your solution’s docker-compose.yml files (or creating the files if they didn’t exist). It’s an easy way to begin composing your multi container solution; you then can open the docker-compose.yml files and update them with additional features.

                  This action not only adds the DockerFile to your project, it also adds the required configuration lines of code to a global docker-compose.yml set at the solution level.

                  After you add Docker support to your solution in Visual Studio, you also will see a new node tree in Solution Explorer with the added docker-compose.yml files, as depicted in the below Figure.

                  s7

Docker assets overview

  • .dockerignore: Contains a list of file and directory patterns to exclude when generating a build context.
  • docker-compose.yml: The base Docker Compose file used to define the collection of images to be built and run with docker-compose build and docker-compose run, respectively.
  • docker-compose.override.yml: An optional file, read by Docker Compose, containing configuration overrides for services. Visual Studio executes docker-compose -f “docker-compose.yml” -f “docker-compose.override.yml” to merge these files.

A Dockerfile, the recipe for creating a final Docker image, is added to the project root. Refer to Dockerfilereference for an understanding of the commands within it. This particular Dockerfile uses a multi-stage build containing four distinct, named build stages:

s12

The Dockerfile is based on the microsoft/aspnetcore image. This base image includes the ASP.NET Core NuGet packages, which have been pre-jitted to improve startup performance.

The docker-compose.yml file contains the name of the image that’s created when the project runs:

s13

In the preceding example, image: webapplication generates the image webapplication:dev when the app runs in Debug mode. The webapplication:latest image is generated when the app runs in Release mode.

Prefix the image name with the Docker Hub username (for example, dockerhubusername/webapplication) if the image will be pushed to the registry. Alternatively, change the image name to include the private registry URL (for example, privateregistry.domain.com/webapplication) depending on the configuration.

Right click on your docker-compose project, then select Set as StartUp Project option.

s21

Next, Go to Build menu then click on Build Solution option or Press Ctrl+Shift+B.

s22

After that you will see the Output window in your visual studio will be looks like below figure.
s23

The above Output window contains the following process:

Whenever you Build the Solution, then internally it will create a Docker image with the name “webapplication:dev” (“dev” is a tag, like a specific version). You can take this step for each custom image you need to create for your composed Docker application with several containers.

You can find the existing images in your local repository (your dev machine) by Run the docker images command in the Package Manager Console (PMC) or Command Prompt window. The images on the machine are displayed:

s17

Step 3. Run your Docker app

Right click on your docker-compose project, then select Set as StartUp Project option then it will automatically Docker is selected in the toolbar.

s24

Debug
Go to Debug menu then click on Start Debugging or Press F5 to start app in debugging mode. After few seconds the Docker view of the Output window shows the following actions taking place:

    • The microsoft/aspnetcore runtime image is acquired (if not already in the cache).
    • The microsoft/aspnetcore-build compile/publish image is acquired (if not already in the cache).
    • The ASPNETCORE_ENVIRONMENT environment variable is set to Development within the container.
    • Port 80 is exposed and mapped to a dynamically-assigned port for localhost. The port is determined by the Docker host and can be queried with the docker ps command.
    • The app is copied to the container.
    • The default browser is launched with the debugger attached to the container using the dynamically-assigned port like this below image.

      s25

The resulting Docker image is the dev image of the app with the microsoft/aspnetcore images as the base image. Run the docker images command in the Package Manager Console (PMC) or Command Prompt window. The images on the machine are displayed:

s17

Note: The dev image lacks the app contents, as Debug configurations use volume mounting to provide the iterative experience. To push an image, use the Release configuration.

Run the docker ps command in Command Prompt. Notice the app is running using the container:

s18

CONTAINER ID

IMAGE

COMMAND

CREATED

STATUS

PORTS

NAMES

 

d9af4b5f2ee3

webapplication:dev

“tail -f /dev/null”

51 seconds ago

Up 47 seconds

0.0.0.0:32769->80/tcp

dockercompose15545145863402767022_webapplication_1

Edit and continue

Changes to static files and Razor views are automatically updated without the need for a compilation step. Make the change, save, and refresh the browser to view the update.

Modifications to code files requires compiling and a restart of Kestrel within the container. After making the change, use CTRL + F5 to perform the process and start the app within the container. The Docker container isn’t rebuilt or stopped. Run the docker ps command in Command Prompt. Notice the original container is still running as of 10 minutes ago:

s19

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

 

d9af4b5f2ee3 webapplication:dev “tail -f /dev/null” 10 minutes ago Up 10 minutes 0.0.0.0:32769->80/tcp dockercompose15545145863402767022_webapplication_1

(Optional) Publish Docker images

Once the develop and debug cycle of the app is completed, the Visual Studio Tools for Docker assist in creating the production image of the app. Change the configuration drop-down to Release and build the app. The tooling produces the image with the latest tag, which can be pushed to the private registry or Docker Hub.

Run the docker images command in Command Prompt to see the list of images:

REPOSITORY TAG IMAGE ID CREATED SIZE
webapplication latest 66d9e9e623a11 9 seconds ago 391MB
webapplication dev 66d9e9e623a1 About an hour ago 389MB
microsoft/aspnetcore 2.0   cdc2d48122e4 40 hours ago 389MB

Note

The docker images command returns intermediary images with repository names and tags identified as <none> (not listed above). These unnamed images are produced by the multi-stage build Dockerfile. They improve the efficiency of building the final image—only the necessary layers are rebuilt when changes occur. When the intermediary images are no longer needed, delete them using the docker rmi command.

There may be an expectation for the production or release image to be smaller in size by comparison to the dev image. Because of the volume mapping, the debugger and app were running from the local machine and not within the container. The latest image has packaged the necessary app code to run the app on a host machine. Therefore, the delta is the size of the app code.

Step 4. Test your Docker application (locally, in your local pc)

This step will vary depending on what your app is doing.

The above .NET Core application named as WebApplication deployed as a single container/service, you’d just need to access the service by providing the TCP port specified in the Dockerfile, as in the following simple example.

Open a browser on the Docker host and navigate to that site, and you should see your app/service running.

s26

Note that it is using the port 80.

Run your .NET Core Web app without Docker

Visual Studio used a default template for the MVC project you just created. This is a basic starter project, and it’s a good place to start,

Go to Solution Explorer, then Right click on your project > Choose Set as StartUp Project option.

s10

Next, Tap F5 to run the app in debug mode or Ctrl-F5 in non-debug mode.

s11

  1. Visual Studio starts IIS Express and runs your app. Notice that the address bar shows localhost:port# and not something like example.com. That’s because localhost is the standard hostname for your local computer. When Visual Studio creates a web project, a random port is used for the web server. In the image above, the port number is 52376. The URL in the browser shows localhost: 52736. When you run the app, you’ll see a different port number.
  2. Launching the app with Ctrl+F5 (non-debug mode) allows you to make code changes, save the file, refresh the browser, and see the code changes. Many developers prefer to use non-debug mode to quickly launch the app and view changes.
  3. You can launch the app in debug or non-debug mode from the Debug menu item:

    s14

  4. You can debug the app by tapping the IIS Express button.

    s15

The default template gives you working Home, About and Contact links. The browser image above doesn’t show these links. Depending on the size of your browser, you might need to click the navigation icon to show them.

s16

If you were running in debug mode, tap Shift-F5 to stop debugging.

Reference Links

Build, Debug, Update and Refresh apps in a local Docker container:

https://azure.microsoft.com/en-us/documentation/articles/vs-azure-tools-docker-edit-and-refresh/

Deploy an ASP.NET container to a remote Docker host:

https://azure.microsoft.com/en-us/documentation/articles/vs-azure-tools-docker-hosting-web-apps-in-docker/

Workflow for building a single ASP.NET Core Web API inside a Docker container using Visual Studio

An app will be made up from you own services plus additional libraries (Dependencies).

The following steps are the basic steps usually needed when building a Docker app, as illustrated in the below Figure.

Picture12

Step 1. Start coding in VS 2017 for Creating ASP.NET Core Web API Application

The way you develop your application is pretty similar to the way you do it without Docker. The difference is that while developing, you are deploying and testing your application or services running within Docker containers placed in your local environment (like a Linux VM or Windows).

This step explains how to create ASP.NET Core Web API application.

Create a ASP.NET Core Web API Application
  1. Right click on your AKSDemo solution i.e. created in previous steps>Click Add>Choose New Project option.
  2. Complete the New Project dialog:
    • In the left pane, tap .NET Core
    • In the center pane, tap ASP.NET Core Web Application (.NET Core)
    • Name the project “APIApplication” (It’s important to name the project “APIApplication”   so when you copy code, the namespace will match.)
    • Tap OK
Step 2. Add Docker support to an Web API
  1. Complete the New ASP.NET Core Web Application (.NET Core)APIApplication dialog:
    • In the version selector drop-down box select ASP.NET Core 2.0
    • Select Web API
    • Check the option as Enable Docker support checkbox
    • Choose OS as Linux from dropdown list
    • Tap OK.

s29

2. Now the Solution Explorer in your Visual Studio 2017 will be looks like below figure.

s30

When you add Docker support to a service project in your solution, Visual Studio is not just adding a DockerFile file to your project, and it also is adding a service section in your solution’s docker-compose.yml files (or creating the files if they didn’t exist). It’s an easy way to begin composing your multi container solution; you then can open the docker-compose.yml files and update them with additional features.

This action not only adds the DockerFile to your project, it also adds the required configuration lines of code to a global docker-compose.yml set at the solution level.

After you add Docker support to your solution in Visual Studio, you will also see the updated files in docker-compose project at solution level.

s7

A Dockerfile, the recipe for creating a final Docker image, is added to the project root. Refer to Dockerfilereference for an understanding of the commands within it. This particular Dockerfile uses a multi-stage build containing four distinct, named build stages:

s31

The Dockerfile is based on the microsoft/aspnetcore image. This base image includes the ASP.NET Core NuGet packages, which have been pre-jitted to improve startup performance.

The docker-compose.yml file contains the name of the images that’s created when the project runs:

s32

In the preceding example, image: webapplication generated the image webapplication:dev and image: apiapplication generated the image apiapplication:dev, when the app runs in Debug mode. The webapplication:latest and apiapplication:latest images are generated when the app runs in Release mode.

Right click on your docker-compose project, then select Set as StartUp Project option.

s265

Next, Go to Build menu then click on Build Solution option or Press Ctrl+Shift+B.

s22

After that you will see the Output window in your visual studio will be looks like below figure.

s33

The above Output window contains the following process:

Whenever you Build the Solution, then internally it will create Docker images with the name “webapplication:dev” and “apiapplication:dev”(“dev” is a tag, like a specific version). You can take this step for each custom image you need to create for your composed Docker application with several containers.

You can find the existing images in your local repository (your dev machine) by Run the docker images command in the Package Manager Console (PMC) or Command Prompt window. The images on the machine are displayed:

s35

Step 3. Run your Docker app

Right click on your docker-compose project, then select Set as StartUp Project option then it will automatically Docker is selected in the toolbar.

s266

Debug
Go to Debug menu then click on Start Debugging or Press F5 to start app in debugging mode. After few seconds the Docker view of the Output window shows the following actions taking place:

  • The microsoft/aspnetcore runtime image is acquired (if not already in the cache).
  • The microsoft/aspnetcore-build compile/publish image is acquired (if not already in the cache).
  • The ASPNETCORE_ENVIRONMENT environment variable is set to Development within the container.
  • Port 80 is exposed and mapped to a dynamically-assigned port for localhost. The port is determined by the Docker host and can be queried with the docker ps command.
  • The apps are copied to the containers.
  • The default browser is launched with the debugger attached to the containers using the dynamically-assigned port like this below images.

 

By default the browser will launch the web application only.

WebApplication:

s36

So, you can manually run the API application URL on your favourite browser, for that you can see the port number of your .net core API application running inside the Docker then you can run docker ps command in the command prompt. Now you will see the port number of your .net core API application.

s38

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

 

935ebf0ec20b apiapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32771->80/tcp dockercompose15545145863402767022_apiapplication_1
384d892368ed webapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32772->80/tcp dockercompose15545145863402767022_webapplication_1

After that, enter http://localhost:<port number>/api/ToDoItems URL in your favourite browser, then you will see the list To-Do Items.

APIApplication:

Whenever the default browser is launched with the debugger attached to the API app container using the dynamically-assigned port, then you must add the api/values at the end of default URL like this below image.

s37

The resulting Docker images are the dev image of the app with the microsoft/aspnetcore images as the base image. Run the docker images command in the Package Manager Console (PMC) or Command Prompt window. The images on the machine are displayed:

s35

Note: The dev image lacks the app contents, as Debug configurations use volume mounting to provide the iterative experience. To push an image, use the Release configuration.

Run the docker ps command in Command Prompt. Notice the app is running using the container:

s38

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

 

935ebf0ec20b apiapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32771->80/tcp dockercompose15545145863402767022_apiapplication_1
384d892368ed webapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32772->80/tcp dockercompose15545145863402767022_webapplication_1
Edit and continue

Changes to static files and Razor views are automatically updated without the need for a compilation step. Make the change, save, and refresh the browser to view the update.

Modifications to code files requires compiling and a restart of Kestrel within the container. After making the change, use CTRL + F5 to perform the process and start the app within the container. The Docker container isn’t rebuilt or stopped. Run the docker ps command in Command Prompt. Notice the original container is still running as of 20 minutes ago:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

 

935ebf0ec20b apiapplication:dev “tail -f /dev/null” 20 minutes ago Up 20 minutes 0.0.0.0:32771->80/tcp dockercompose15545145863402767022_apiapplication_1
384d892368ed webapplication:dev “tail -f /dev/null” 20 minutes ago Up 20 minutes 0.0.0.0:32772->80/tcp dockercompose15545145863402767022_webapplication_1

Step 4. Test your Docker application (locally, in your local pc)

This step will vary depending on what your app is doing.

The above .NET Core application named as APIApplication deployed as a single container/service, you’d just need to access the service by providing the TCP port specified in the Dockerfile, as in the following simple example.

Open a browser on the Docker host and navigate to that site, and you should see your app/service running.

s37

Note that it is using the port 80.

Run your ASP.NET Core API Application without Docker

Go to Solution Explorer, then Right click on your project named as APIApplication> Choose Set as StartUp Project option.

s39

Next, Tap F5 to run the app in debug mode or Ctrl-F5 in non-debug mode.

Add the api/values at the end of default URL on the browser.

s40

Visual Studio starts IIS Express and runs your app. Notice that the address bar shows localhost:port# and not something like example.com. That’s because localhost is the standard hostname for your local computer. When Visual Studio creates an API project, a random port is used for the API server. In the image above, the port number is 61753. The URL in the browser shows localhost: 61753. When you run the app, you’ll see a different port number.

Launching the app with Ctrl+F5 (non-debug mode) allows you to make code changes, save the file, refresh the browser, and see the code changes. Many developers prefer to use non-debug mode to quickly launch the app and view changes.

You can launch the app in debug or non-debug mode from the Debug menu item:

s14

You can debug the app by tapping the IIS Express button

s15

The default template gives the functionality of Values API.

If you were running in debug mode, tap Shift-F5 to stop debugging.

Reference Architecture for Database Application

s4

Inner-loop development workflow for Database Application

Before triggering the outer-loop workflow spanning the whole DevOps cycle, it all starts from each developer’s machine working coding the app itself, using his preferred languages/platforms, and testing it locally. But in every case, you will have with a very important point in common no matter what language/framework/platforms you choose. In this specific workflow you are always developing and testing Database project, but locally.

Picture14

Workflow for building a Database Application using Visual Studio

The following steps are the basic steps usually needed when building a Database application, as illustrated in the below Figure.

Picture6

Create Database application using State based Approach

Before creating the Database application you must have the following prerequisites:

Prerequisites

Note:

Before installing SSDT for Visual Studio 2017 (15.7.0), uninstall “Microsoft Analysis Services Projects” and “Microsoft Reporting Services Projects” extensions if they are already installed. And close all VS instances.

After Install the SSDT tools then open your previous VS Solution i.e AKSDemo.sln

Step 1. Create SQL Server Database Project
  1. Right click on your AKSDemo solution i.e. created in previous steps>Click Add>Choose New Project option.
    s27
  2. Complete the New Project dialog:
    • In the left pane, tap SQL Server
    • In the center pane, tap SQL Server Database Project
    • Name the project “DatabaseApplication” (It’s important to name the project “DatabaseApplication” so when you copy code, the namespace will match.)
    • Tap OK
      s41
  3. Now the Solution Explorer in your Visual Studio 2017 will be looks like below figure.
    s42
  4. Next thing is you need to right click on database project and click Add. Here you can add many things like Table, View, Script, Stored Procedure, table valued function, Scaler valued function, etc.
  5. Right click on database project i.e DatabaseApplication and click Add >> select New Folder and enter the name as dbo like this below figure.
    s43
  6. Right click on dbo folder click Add >> select New Folder and enter the name as Tables.
    s44
Step 2. Create Table
  1. Right click on your Tables folder >> select Add then choose Table option.
    s45
  2. Complete the Add New Item dialog:
    • In the left pane, tap Tables and Views
    • In the center pane, tap Table
    • Name the table “ToDoItem”
    • Tap Add
      s46
  3. Once you done with adding table, you will see the following design like, here you can add columns with datatype.
    s47
  4. This is my table script for example ToDoItem.sql.
    s48
  5. Close the Table designer window. And you have done to edit the code in the Database project.
(Optional) Publish Database Project to SQL Server 2016/2017 from VS2017
Create Empty Database
  1. Before publish the database project to SQL Server 2016. First you need to create empty database for example DockersDemoDB.
  2. To open SQL Server Management Studio (SSMS), Search for SSMS, select SQL Server Management Studio in the search results, and click it (or hit Enter).
    s267
  3. Next, SSMS will be open like this below figure.
    s268
  4. Click on Connect > Database Engine.
  5. Next, a new Connect to Server window will open, in that you have to choose the Server name and Authentication like this below figure.
    s59
  6. Finally click on Connect button.
  7. Now you see the list of databases by expanding Databases folder under the specified server.
  8. Right click on Databases folder then choose New Database option.
    s60
  9. Complete New Database Dialog:
    · Enter the Database name as DockersDemoDB
    ·
    Click on OK Button
    s61
  10. Finally a new empty Database is created under the Databases folder.
    s62
Publish Database Project
    1. Right click on Database project i.e. DatabaseApplication> then click on Set as StartUp Project option.
      s49
    2. Right click on Database project then choose Properties option.
      s50
    3. In the Properties windows, click on Project Settings on the left pane, then Change Target platform to SQL Server 2016.
      s51
    4. Save the change and Close the Properties window.
    5. Right click on Database project i.e. DatabaseApplication > Click on Publish option.
      s52
    6. Complete the Publish Database Wizard:

        • Click on Edit button under the Target Database Settings.

        • Next a new Connect dialog will be open like this below figure.
          s53
        • Click on Browse in the above Connect dialog then expand the
          Local, now you will see the list of SQL Servers installed in your local
          machine.
        • Choose any of the SQL Server, select Authentication type as
          Windows Authentication and select the Database from drop down list
          for example DockersDemoDB.
          s54
        • Click on Test Connection to validate SQL Server connection.
          s55
        • If the Test Connection succeeded the click on OK button.
          s56

  1. After that you will see the Target database connection, Database name under Publish Database dialog.
    s63
  2. Click on Publish button.
  3. Now your Database project is published into DockersDemoDB successfully.
    s64
Test your Database
  1. Go to SSMS> choose your Database i.e. DockersDemoDB> expand Tables folder, then you will see the ToDoItem table.
    s65
  2. Right click on your Database i.e. DockersDeomDB > choose New Query option. In that New query window you have to write the insert query for inserting some data into ToDoItem table.
    s66
    Note:
    The database generates the Id when a TodoItem is created/inserted. So, you don’t need to provide Id value explicitly while inserting the data into database.
  3. Click on Execute option, for executing the insert query on target database.
  4. If you want to see the inserted data of the ToDoItem table. Right click on dbo.ToDoItem> choose Select Top 1000 Rows, then you will see the Data inside it.
    s67
  5. Now, you have the Database with some data in your local machine.
Step 3. Publish Database Project to Microsoft Azure SQL Database V12 from VS2017
Log in to the Azure portal

Log in to the Azure portal.

Create a SQL Database

An Azure SQL database is created with a defined set of compute and storage resources. The database is created within an Azure resource group and in an Azure SQL Database logical server.

Follow these steps to create a SQL database.

  1. Click Create a resource in the upper left-hand corner of the Azure portal.
  2. Select Databases from the New page, and select Create under SQL Database on the New page.
    s5
  3. Fill out the SQL Database form with the following information, as shown on the preceding image:

    Setting Suggested value Description
    Database name KZEU-AKSDMO-SB-DEV-SDB-01 For valid database names, see Database Identifiers.
    Subscription Your subscription For details about your subscriptions, see Subscriptions.
    Resource group For example:
    KZEU-AKSDMO-SB-DEV-RGP-02
    For valid resource group names, see Naming rules and restrictions.
    Select source Blank database It creates empty Database.
  4. Under Server, click Configure required settings and fill out the SQL server (logical server) form with the following information, as shown on the following image:
    s6

    Setting Suggested value Description
    Server name Any globally unique name For valid server names, see Naming rules and restrictions.
    Server admin login Any valid name For valid login names, see Database Identifiers.
    Password Any valid password Your password must have at least 8 characters and must contain characters from three of the following categories: upper case characters, lower case characters, numbers, and non-alphanumeric characters.
    Subscription Your subscription For details about your subscriptions, see Subscriptions.
    Resource group For example: KZEU-AKSDMO-SB-DEV-RGP-02 For valid resource group names, see Naming rules and restrictions.
    Location Any valid location For information about regions, see Azure Regions.
  5. When you have completed the form, click Select.
  6. Click Pricing tier to specify the service tier, the number of DTUs, and the amount of storage. Explore the options for the amount of DTUs and storage that is available to you for each service tier
  7. For this scenario, select the Basic service tier.
    s7
  8. After selecting the server tier, click Apply.
  9. Now that you have completed the SQL Database form, click Create to provision the database. Provisioning takes a few minutes.
  10. On the toolbar, click Notifications to monitor the deployment process.
    s72
Reference Link

If you want to configure the server-lever firewall rule, please go through this link.

Publish Database Project
  1. Right click on Database project then choose Properties option.
  2. In the Properties windows, click on Project Settings on the left pane, then Change Target platform to SQL Server 2016.
    s73
  3. Save the change and Close the Properties window.
  4. Right click on Database project i.e. DatabaseApplication > Click on Publish option.
    s52
  5. Complete the Publish Database Wizard:
    • Click on Edit button under the Target Database Settings.
    • Next a new Connect dialog will be open like this below figure.
      s53
    • Click on Browse in the above Connect dialog.
    • Enter the Server Name, select Authentication type as SQL Server Authentication, enter User Name, Password and select the Database from drop down list for example KZEU-AKSDMO-SB-DEV-SDB-01.
      Note:
      If you have not seen your Databases from drop down list, you have to configure the server level firewall rules by following this link.
      s8
    • Click on Test Connection to validate SQL Server connection.
      s55
    • If the Test Connection succeeded the click on OK button.
      s9
  6. After that you will see the Target database connection, Database name under Publish Database dialog.
    s10
  7. Click on Publish button.
  8. Now your Database project is published into Azure SQL Database i.e. KZEU-AKSDMO-SB-DEV-SDB-01 successfully.
Step 4. Test your Database
  1. Login to the Azure portal
  2. Open your Azure SQL Database i.e. created in previous steps.
  3. Click on Query editor (preview) on the left pane then click login button on top of the right pane.
    Picture8
  4. Next, enter your SQL Server login details.
    s11
  5. After login succeeded, Expand the Tables on the left pane then you have to see the dbo.ToDoItem table.
    s12
  6. In that New query window you have to write the insert query for inserting some data into ToDoItem table.
    s13
  7. Click on Run option, for executing the insert query on target database.
  8. If you want to see the inserted data of the ToDoItem table. See the below figure.
    s81
  9. Now, you have the Azure SQL Database with some data in Azure Cloud.

Add the custom code in ASP.NET Core Web API Application

Here you can add the .net core code for getting the list of To-Do items from the database i.e created in the previous steps.

Add a Model class

A model is an object representing the data in the app. In this case, the only model is a ToDoItem.

  1. In Solution Explorer, right-click the project i.e. APIApplication. Select Add > New Folder. Name the folder Models
    s82
  2. Right click on Models folder, then click on Add and Choose Class option.
    s83
  3. Complete the Add New Item dialog:
    • Give the Name of the class i.e. ToDoItem.cs
    • Click on Add option.
      s84
  4. Update the TodoItem class with the following code:
    namespace APIApplication.Models
    
    {
    
    public class ToDoItem
    
    {
    
    public int Id { get; set; }
    
    public string Item { get; set; }
    
    }
    
    }
    
  5. Build the project to verify you don’t have any errors. You now have a Model in your .NET Core Web API app.

Note:
the model classes can go anywhere in the project. The Models folder is used by convention for model classes.

Add a Controller

  1. Right click on Controllers folder, then click on Add and Choose New Scaffolded Item option.
    s85
  2. Complete the Add Scaffold dialog:
    • In the left pane, tap API
    • In the center pane, tap API Controller with read/write actions
    • Click on Add button.
      s86
  3. Whenever you click on Add button, then immediately a new popup will open like this below. In that enter the name of the controller for example ToDoItemsController
    s87
  4. Now a new controller will added under the Controllers folder of APIApplication with default functionality.

Handling settings and Environment Variables of your .NET Core 2 application hosted in a Docker container during development

Environment Variables and settings during development

If you configure secret settings in your settings files (appsettings.json), the secrets can be seen by everyone who has access to your Docker container. How to use secrets then during development? You can configure Environment Variables in Visual Studio in the launchSettings.json file.

  1. Expand the Properties folder of your API Application > open launchSettings.json file, then add the below lines of code under the environmentVariables of profiles section.
    “ConnectionStrings_DBConnection”: “Server=tcp:XXXXX.database.windows.net,1433;Initial Catalog=KZEU-AKSDMO-SB-DEV-SDB-01;Persist Security Info=False;User ID=XXXX;Password=XXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;”
  2. After added the above lines of code in launchSettings.json file, then it should be like this below figure.
    s14

Docker Compose and Environment Variables during development

When you debug your .NET Core Web API application itself, the solution above works great. If you have enabled Docker support and debug the docker-compose project, you should specify Environment Variables in Docker compose.

You can add the Environment Variables in docker-compose.override.yaml

version: '3.4'

services:
  webapplication:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - AppSettings_APIURL=http://104.209.160.99/
    ports:
      - "80"

  apiapplication:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "ConnectionStrings_DBConnection=Server=tcp:kzeu-aksdmo-sb-dev-sq-01.database.windows.net,1433;Initial Catalog=KZEU-AKSDMO-SB-DEV-SDB-01;Persist Security Info=False;User ID=XXXXXX;Password=XXXXXXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
    ports:
      - "80"

Validate .yml or .yaml files

If you can validate the code inside .yml files, you can refer this link.

Reference Links

Handling settings and Environment Variables of your .NET Core 2 application hosted in a Docker container during development and on Kubernetes (Helm to the rescue)

https://pascalnaber.wordpress.com/2017/11/29/handling-settings-and-environment-variables-of-your-net-core-2-application-hosted-in-a-docker-container-during-development-and-on-kubernetes-helm-to-the-resque/

Get To-Do Items

  1. To get the To-Do Items, replace the following code in the TodoItemsController class:

    using Microsoft.AspNetCore.Mvc;
    using APIApplication.Models;
    using System.Data.SqlClient;
    using System.Data;
    using Microsoft.Extensions.Configuration;
    using System.Collections.Generic;
    using System;
    using System.Diagnostics;
    using APIApplication.Utils;
    
    namespace APIApplication.Controllers
    {
        [Produces("application/json")]
        [Route("api/ToDoItems")]
        public class ToDoItemsController : Controller
        {
            IConfiguration _iconfiguration;
            string dBConnectionString = string.Empty;
            public ToDoItemsController(IConfiguration iconfiguration)
            {
                _iconfiguration = iconfiguration;
    
                //Reading appsettings.json values
                //dBConnectionString = _iconfiguration.GetValue<string>("ConnectionStrings:DBConnection");
    
                //Reading environment variables in launchSettings.json, docker-compose.override.yml and apiapplication.yaml
                dBConnectionString = _iconfiguration.GetSection("ConnectionStrings_DBConnection").Value;
            }
    
            // GET: api/ToDoItem
            [HttpGet]
            public async System.Threading.Tasks.Task<List<ToDoItem>> GetTodoItems()
            {
                List<ToDoItem> toDoItems = null;
                SqlConnection myConnection = null;
                try
                {                
                    toDoItems = new List<ToDoItem>();
                    SqlDataReader reader = null;
                    myConnection = new SqlConnection();
                    myConnection.ConnectionString = dBConnectionString;
                    SqlCommand sqlCmd = new SqlCommand();
                    sqlCmd.CommandType = CommandType.Text;
                    sqlCmd.CommandText = "Select * from ToDoItem";
                    sqlCmd.Connection = myConnection;
                    myConnection.Open();
                    reader = sqlCmd.ExecuteReader();
                    ToDoItem toDoItem = null;
                    while (reader.Read())
                    {
                        toDoItem = new ToDoItem();
                        toDoItem.Id = Convert.ToInt32(reader.GetValue(0).ToString());
                        toDoItem.Item = reader.GetValue(1).ToString();
                        toDoItems.Add(toDoItem);
                    }
                }
                catch(Exception ex)
                {
                    Debug.WriteLine("Error returned from the service: {0}", ex.Message);
                }
                finally
                {
                    myConnection.Close();
                }
                return toDoItems;
    
            }
    
            // GET: api/ToDoItems/5
            [HttpGet("{id}", Name = "Get")]
            public string Get(int id)
            {
                return "value";
            }
    
            // PUT: api/ToDoItems/5
            [HttpPost]
            public void Put([FromBody]string value)
            {
            }
    
            // POST: api/ToDoItems
            [HttpPost]
            public void Post([FromBody]string value)
            {
            }
    
            // DELETE: api/ToDoItems/5
            [HttpPost]
            public void Delete([FromBody]string value)
            {
            }
    
        }
    }
    
  2. Open the Startup.cs class of your web API application i.e. APIApplication, then replace existing code with below lines of code.

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;
    using APIApplication.Models;
    using Microsoft.Extensions.Configuration;
    using Microsoft.AspNetCore.Hosting;
    using APIApplication.Utils;
    
    namespace APIApplication
    {
        public class Startup
        {
            public Startup(IConfiguration configuration, IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
                Configuration = builder.Build();
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                services.AddSingleton<IConfiguration>(Configuration);
            }
    
            public void Configure(IApplicationBuilder app)
            {
                //app.UseDefaultFiles();
                //app.UseStaticFiles();
                app.UseMvc();
            }
        }
    }
    
  3. Now you are ready to run the above .NET Core API application in both local machine and local Docker.

Launch the ASP.NET Core API Application without Docker

If you don’t know how the application run from visual studio, please follow this steps.

Go to Solution Explorer, then Right click on your project named as APIApplication> Choose Set as StartUp Project option.

In Visual Studio, press CTRL+F5 to launch the app. Visual Studio launches a browser and navigates to http://localhost:<port>/api/values, where <port> is a randomly chosen port number. Navigate to the ToDoItems controller at http://localhost:<port>/api/ToDoItems.

Now you will see the list of To-Do Items available in the ToDoItem table of your database.
image

Run your Docker app

If you run the application inside the local Docker, you can follow this steps.

By default the browser launch the web application only.

WebApplication:

image

So, you can manually run the API application URL on your favourite browser, for that you can see the port number of your .net core API application running inside the Docker then you can run docker ps command in the command prompt. Now you will see the port number of your .net core API application.

image

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

 

935ebf0ec20b apiapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32771->80/tcp dockercompose15545145863402767022_apiapplication_1
384d892368ed webapplication:dev “tail -f /dev/null” 5 minutes ago Up 5 minutes 0.0.0.0:32772->80/tcp dockercompose15545145863402767022_webapplication_1

After that, enter http://localhost:<port number>/api/ToDoItems URL in your favourite browser, then you will see the list To-Do Items.

APIApplication:

image

Add the custom code in ASP.NET Core Web Application

Here you can add the .net core code for displaying the list of To-Do items in .NET Core web application by calling the .NET Core Web API (i.e developed in the previous steps).

The Model-View-Controller (MVC) architectural pattern separates an app into three main components: Model, View, and Controller. The MVC pattern helps you create apps that are more testable and easier to update than traditional monolithic apps. MVC-based apps contain:

  • Models: Classes that represent the data of the app. The model classes use validation logic to enforce business rules for that data. Typically, model objects retrieve and store model state in a database. In this blog/document, a ToDoItem model retrieves to-do-item data from a database, provides it to the view or updates it.
  • Views: Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.
  • Controllers: Classes that handle browser requests. They retrieve model data and call view templates that return a response. In an MVC app, the view only displays information; the controller handles and responds to user input and interaction.

    For example, the controller handles route data and query-string values, and passes these values to the model. The model might use these values to query the database.

    For example, http://localhost:<PortNumber>/Home/About has route data of Home (the controller) and About (the action method to call on the home controller). http://localhost:<PortNumber>/Homoe/ToDoItem is a request to get the To-Do Items using the ToDoItemsController.

The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the app.

The UI logic belongs in the view.

Input logic belongs in the controller.

Business logic belongs in the model.

This separation helps you manage complexity when you build an app, because it enables you to work on one aspect of the implementation at a time without impacting the code of another. For example, you can work on the view code without depending on the business logic code.

Here you can build WebAppication with MVC pattern app. The MVC project contains folders for the Controllers, Models and Views.

Add a Model class

In this section, you’ll add some classes for managing To-Do Items in a database. These classes will be the “Model” part of the MVC app.

A model is an object representing the data in the app. In this case, the only model is a ToDoItem.

The model classes you’ll create are known as POCO classes (from “plain-old CLR objects”) because they don’t have any dependency on database. They just define the properties of the data that will be stored in the database.

  1. Go to Solution Explorer i.e. AKSDemo.sln, then Right click on your project i.e WebApplication > Choose Set as StartUp Project option.
  2. Go to WebApplication, Right click on Models folder, then click on Add and Choose Class option.
    s100
  3. Complete the Add New Item dialog:
    • Give the Name of the class i.e. ToDoItem.cs

    • Click on Add option.
      image

  4. Update the TodoItem class with the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WebApplication.Models
    {
        public class ToDoItem
        {
            public int Id { get; set; }
            public string Item { get; set; }
        }
    }
    
  5. Build the project to verify you don’t have any errors. You now have a Model in your MVC app.

Note:
the model classes can go anywhere in the project. The Models folder is used by convention for model classes.

Handling settings and Environment Variables of your .NET Core 2 application hosted in a Docker container during development

Environment Variables and settings during development

If you configure secret settings in your settings files (appsettings.json), the secrets can be seen by everyone who has access to your Docker container. How to use secrets then during development? You can configure Environment Variables in Visual Studio in the launchSettings.json file.

  1. Expand the Properties folder of your Web Application > open launchSettings.json file, then add the below lines of code under the environmentVariables of profiles section.
    “AppSettings_APIURL”: “<Here you can paste the URL of your API Application. for example http://localhost:25603/>&#8221;
  2. After added the above lines of code in launchSettings.json file, then it should be like this below figure.
    image

Docker Compose and Environment Variables during development

When you debug your .NET Core Web application itself, the solution above works great. If you have enabled Docker support and debug the docker-compose project, you should specify Environment Variables in Docker compose.

You can add the Environment Variables in docker-compose.override.yaml

version: '3.4'

services:
  webapplication:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - AppSettings_APIURL=http://104.209.160.99/
    ports:
      - "80"

  apiapplication:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "ConnectionStrings_DBConnection=Server=tcp:kzeu-aksdmo-sb-dev-sq-01.database.windows.net,1433;Initial Catalog=KZEU-AKSDMO-SB-DEV-SDB-01;Persist Security Info=False;User ID=kishore;Password=iSMAC2016;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
    ports:
      - "80"

Validate .yml or .yaml files

If you can validate the code inside .yml files, you can refer this link.

Reference Links

Handling settings and Environment Variables of your .NET Core 2 application hosted in a Docker container during development and on Kubernetes (Helm to the resque)

https://pascalnaber.wordpress.com/2017/11/29/handling-settings-and-environment-variables-of-your-net-core-2-application-hosted-in-a-docker-container-during-development-and-on-kubernetes-helm-to-the-resque/

Add a Controller

  1. Go to WebApplication, right-click on Controllers > Add > New Scaffolded Item.
    image
  2. Complete the Add Scaffold dialog:
    • In the left pane, tap MVC
    • In the center pane, tap MVC Controller with read/write actions
    • Click on Add button
      image
  3. Whenever you click on Add button, then immediately a new popup will open like this below. In that enter the name of the controller for example ToDoItemController
    image
  4. Now a new controller will added under the Controllers folder of WebApplication with default functionality.
  5. Replace the contents of Controllers/ToDoItemController.cs with the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Newtonsoft.Json;
    using WebApplication.Models;
    using WebApplication.Utils;
    
    namespace WebApplication.Controllers
    {
        public class ToDoItemController : Controller
        {
            string toDoItemResponse = string.Empty;
            IConfiguration _iconfiguration;
            public ToDoItemController(IConfiguration iconfiguration)
            {
                _iconfiguration = iconfiguration;
            }
    
            // GET: ToDoItem/GetToDoItems
            public async Task<ActionResult> GetToDoItems()
            {
                List<ToDoItem> toDoItems = null;
                try
                {
                    using (var client = new HttpClient())
                    {
                        //Reading appsettings.json values
                        //var apiURL = _iconfiguration.GetValue<string>("AppSettings:APIURL");
    
                        //Reading environment variables in launchSettings.json, docker-compose.override.yml and webapplication.yaml
                        var apiURL = _iconfiguration.GetSection("AppSettings_APIURL").Value;
                        //Passing service base url  
                        client.BaseAddress = new Uri(apiURL);
    
                        client.DefaultRequestHeaders.Clear();
                        //Define request data format  
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                  
                        //Sending request to find web api REST service resource GetToDoItem using HttpClient  
                        HttpResponseMessage Res = await client.GetAsync("api/ToDoItems");
    
                        //Checking the response is successful or not which is sent using HttpClient  
                        if (Res.IsSuccessStatusCode)
                        {
                            WebApplication.Utils.ApplicationInsights.StopTrackRequest("api/ToDoItems", Res.StatusCode);
                            //Storing the response details recieved from web api   
                            toDoItemResponse = Res.Content.ReadAsStringAsync().Result;
    
                            //Deserializing the response recieved from web api and storing into the string varaible  
                            toDoItems = JsonConvert.DeserializeObject<List<ToDoItem>>(toDoItemResponse);                      
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return View(toDoItems);
            }
        }
    }
    

Every public method in a controller is callable as an HTTP endpoint. In the sample above, GetToDoItems method return a list of To-Do items. Note the comments preceding each method.

An HTTP endpoint is a targetable URL in the web application, such as http://localhost:<PortNumber>/ToDoItem/GetToDoItems, and combines the protocol used: HTTP, the network location of the web server (including the TCP port): localhost:<Port Number> and the target URI /ToDoItem/GetToDoItems.

The above comment on the GetToDItems method in the ToDoItemController, specifies an HTTP GET method that’s invoked by appending “/ToDoItem/GetToDoItems” to the URL.

The above GetToDoItems method contains the code for calling the .NET Core Web Api like api/ToDoItems, it will gives list of To-Do Items.

Add a View

  1. Views: Views are the components that display the app’s user interface (UI). Generally, this UI displays the model data.
  2. To create the Partial View to Get To-Do Items and display on it, Open the ToDoItemController.cs file, then right click on GetToDoItems method and click on “Add View
    image
  3. Complete Add MVC View dialog:
    • Choose Template as List

    • Choose the Model class for example ToDoItem (WebApplication.Models)

    • Click on Add Button.
      image

  4. Now you have GetToDoItems.cshtml under ToDoItem folder of Views in your Web Application.
    image
  5. Replace the contents of the Views/ToDoItem/GetToDoItems.cshtml Razor view file with the following:
    @model IEnumerable<WebApplication.Models.ToDoItem>
    
    @{
        ViewData["Title"] = "GetToDoItems";
    }
    
    <h2>ToDoItems</h2>
    
    <table class="table">
        <thead>
            <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Id)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Item)
                    </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
    @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Id)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Item)
                </td>
            </tr>
    }
        </tbody>
    </table>
    
  6. Expand the Shared folder under Views folder of your web application, then open the _Layout.cshtml file and add the below lines of code after this line <li><a asp-area=”” asp-controller=”Home” asp-action=”Contact”>Contact</a></li> under the <div class=”navbar-collapse collapse”> section.

    <li><a asp-area=”” asp-controller=”ToDoItem” asp-action=”GetToDoItems”>ToDoItem</a></li>
    image

    @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - WebApplication</title>
    
        <environment include="Development">
            <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
            <link rel="stylesheet" href="~/css/site.css" />
        </environment>
        <environment exclude="Development">
            <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
                  asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
                  asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
            <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
        </environment>
        @Html.Raw(JavaScriptSnippet.FullScript)
    </head>
    <body>
        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">WebApplication</a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                        <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                        <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                        <li><a asp-area="" asp-controller="ToDoItem" asp-action="GetToDoItems">ToDoItem</a></li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; 2018 - WebApplication</p>
            </footer>
        </div>
    
        <environment include="Development">
            <script src="~/lib/jquery/dist/jquery.js"></script>
            <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
            <script src="~/js/site.js" asp-append-version="true"></script>
        </environment>
        <environment exclude="Development">
            <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
                    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                    asp-fallback-test="window.jQuery"
                    crossorigin="anonymous"
                    integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
            </script>
            <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                    crossorigin="anonymous"
                    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
            </script>
            <script src="~/js/site.min.js" asp-append-version="true"></script>
        </environment>
    
        @RenderSection("Scripts", required: false)
    </body>
    </html>
    

     

  7. Open the Startup.cs class of your web application i.e. WebApplication, then replace existing code with below lines of code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using WebApplication.Models;
    using WebApplication.Utils;
    
    namespace WebApplication
    {
        public class Startup
        {
            public Startup(IConfiguration configuration,IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
                Configuration = builder.Build();
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                services.AddSingleton<IConfiguration>(Configuration);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    

Now you have a separate view for displaying the list of To-Do items in your .NET Core Web Application.

Launch the ASP.NET Core API Application and Web Application without Docker

Go to Solution Explorer, then Right click on your solution named as AKSDemo.sln> Choose Set as StartUp Projects option.
image

Next a new window of ‘AKSDemo’ Property Pages will open, for configuring the Multiple startup projects like this below figure.
image

Click on Apply and then click on OK button.

In Visual Studio, press CTRL+F5 to launch the both applications web and API.

Visual Studio launches a browser and navigates to http://localhost:<port>/api/values, where <port> is a randomly chosen port number. Navigate to the ToDoItems controller at http://localhost:<port>/api/ToDoItems.

APIApplication:
image

And also Visual Studio launches a browser and navigates to http://localhost:<port>/, where <port> is a randomly chosen port number. Navigate to the ToDoItem at http://localhost:<port>/ToDoItem/GetToDoItems.

WebApplication:
image

Run your Docker app

If you run the application inside the local Docker, you can follow this steps.

fg
hh

using Microsoft.AspNetCore.Mvc;
using APIApplication.Models;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using APIApplication.Utils;

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s