.NET Core Console Applications On Mac OS X, Ubuntu 14.04 And Windows 10 - Part Four

Introduction

This article demonstrates how to create console applications on Mac OS X (10.12.3), Ubuntu 14.04 and Windows 10 using .NET Core. This article gives the details of OS versions, Tools set and a demo. We will create a multiple project solution using Visual Studio Code, which contains two Console Applications and 4 Library Projects. We will learn how to add Project Reference and Package Reference. We will also see how to configure and execute two console applications within the same solution. Please refer to (Part 3) my previous article which creates multiple project solutions with single console application (.NET Core Console Applications On Mac OS X, Ubuntu 14.04 And Windows 10 - Part Three). Also please refer to Part 1 & 2 of the article to give the basics. The main use case is that development teams are working on the same code base with the same tool set, and the key is different Operating System.

The code tested on below Operating System Versions,

  • Mac OS X (10.12.3)
  • Ubuntu 14.04
  • Windows 10

Tools Set

  • .NET Core 1.0.4
  • .NET Command Line Interface (cli) Tools
  • Visual Studio Code (1.12.2)
  • Git

Source Code Link.

Demo 1 - Multiple Projects [2 Console Application and 4 Library projects] using terminal, cli, and Visual Studio Code

  • Introduction to the solution
    This solution will contain 6 projects. 

  • DataCore.csproj
    This project contains the data model. This will be used to hold the metadata of the libraries (StringLibrary, ArrayLibrary).

  • CoreLibrary.csproj
    This project contains two interfaces. IRunner and IProcessor.

  • ArrayLibrary.csproj
    This project contains an ArrayDemo.cs class, which will accept an array and prints the array in reverse.

  • StringLibrary.csproj
    This project contains two classes. PalindromicString.cs displays whether a given string is Palindrome or not. ToggleString.cs toggles each alphabet.

  • LogicPrograms.csproj
    This is the console application project. It consumes both StringLibrary.csproj and ArrayLibrary.csproj. It will read the metadata from appsettings.json and executes the methods from each class using Metadata. It uses reflection.

  • StringPrograms.csproj
    This is the console application project. It consumes only StringLibrary.csproj. It will read the metadata from appsettings.json and executes the methods from each class using Metadata. It uses reflection.

Please refer to the image to get a better picture.

.NET Core

Mac OS X (10.12.3)

Get the latest version of code from GitHub.

git pull

.NET Core

Create a Folder called MultiLibMultiApps. Copy and Paste the five (DataCore, CoreLibrary, ArrayLibrary, StringLibrary, LogicPrograms) Projects which we created in MultiLibraryApp. Please refer Part 3 of the article.

.NET Core

.NET Core

Open MultiLibMultiApps folder in Visual Studio. Your solution should look similar to the image below.

.NET Core

Select Program.cs inside LogicPrograms folder. Visual Studio Code will display a dialog box for creation .vscode folder with launch.json and tasks.json. Please select “Yes”.

.NET Core

Also change the console type inside launch.json to “integratedTerminal”, so that we will be able to input the data to the program.

  1.     // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window  
  2.     "console""integratedTerminal",  
  3.     "stopAtEntry"false,  
  4.     "internalConsoleOptions""openOnSessionStart"  
  5. },  

.NET Core

Execute the solution, it should work and invoke the methods from 3 three classes.

.NET Core

Within the integrated terminal execute the below mentioned commands to create new console application within existing solution.

mkdir StringPrograms

cd StringPrograms

dotnet new console

dotnet restore

.NET Core

Now we have two console applications. We have to instruct Visual Studio Code to execute which particular console application. For this we have to modify launch.json and tasks.json.

Launch.json

We should add Launch configuration for each application that should be executed. In the below code we have two configurations, one for LogicPrograms and another for StringPrograms. The “program” element should point to the binary of that console application which will be launched. In our case LogicPrograms.dll and StringPrograms.dll.

  1. {  
  2.     "name"".NET Core Launch (LogicPrograms)",  
  3.     "type""coreclr",  
  4.     "request""launch",  
  5.     "preLaunchTask""build",  
  6.     // If you have changed target frameworks, make sure to update the program path.  
  7.     "program""${workspaceRoot}/LogicPrograms/bin/Debug/netcoreapp1.1/LogicPrograms.dll",  
  8.     "args": [],  
  9.     "cwd""${workspaceRoot}/LogicPrograms",  
  10.     // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window  
  11.     "console""integratedTerminal",  
  12.     "stopAtEntry"false,  
  13.     "internalConsoleOptions""openOnSessionStart"  
  14. },  
  15. {  
  16.     "name"".NET Core Launch (StringPrograms)",  
  17.     "type""coreclr",  
  18.     "request""launch",  
  19.     "preLaunchTask""build",  
  20.     // If you have changed target frameworks, make sure to update the program path.  
  21.     "program""${workspaceRoot}/StringPrograms/bin/Debug/netcoreapp1.1/StringPrograms.dll",  
  22.     "args": [],  
  23.     "cwd""${workspaceRoot}/StringPrograms",  
  24.     // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window  
  25.     "console""integratedTerminal",  
  26.     "stopAtEntry"false,  
  27.     "internalConsoleOptions""openOnSessionStart"  
  28. }   

Once we navigate to debug mode, we will be able to see all the configuration items which was defined in the launch.json. In our case we have added two Launch configuration items for both console applications.

.NET Core

Note

  • ${workspaceRoot} the path of the folder opened in VS Code
  • ${fileDirname} the current opened file's dirname
  • ${cwd} the task runner's current working directory on startup

Tasks.json

Build command runs from ${workspaceRoot}. But in our case we have two separate executable under different folders. Also the “args” element will specify which project to compile.

  1. "tasks": [  
  2.     {  
  3.         "taskName""build",  
  4.         "args": [  
  5.             "${workspaceRoot}/LogicPrograms/LogicPrograms.csproj"  
  6.         ],  
  7.         "isBuildCommand"true,  
  8.         "problemMatcher""$msCompile"  
  9.     }   

We need to make two changes. We need to remove the arguments/path of the project from “args” element. Also need to include “options” element with “cmd” element. 

  1. {  
  2.     "version""0.1.0",  
  3.     "command""dotnet",  
  4.     "isShellCommand"true,  
  5.     "args": [],  
  6.     "options": {  
  7.         "cwd""${fileDirname}"  
  8.     },  
  9.     "tasks": [  
  10.         {  
  11.             "taskName""build",  
  12.             "args": [ ],  
  13.             "isBuildCommand"true,  
  14.             "problemMatcher""$msCompile"  
  15.         }  
  16.     ]  
  17. }  

.NET Core

Select the Program.cs within StringPrograms project. In the Debug Mode select “.NET Core Launch (StringPrograms)” and execute the program, you should see “Hello World” as output.

.NET Core

Select the Program.cs within LogicPrograms project. In the Debug Mode select “.NET Core Launch (LogicPrograms)” and execute the program, it should invoke the methods from ArrayLibrary and StringLibrary classes.

.NET Core

Till now we have created 2nd console application. Configured to execute each console applications.

Windows 10

Now will be update StringProgram to consume only StringLibrary project. Get the latest code from GitHub.

git pull

.NET Core

Update the dependencies of all the projects.

dotne restore

.NET Core

StringPrograms.csproj

Create a new file called appsettings.json and paste the below mentioned code. 

  1. [  
  2.     {  
  3.     "AssemblyName""StringLibrary",  
  4.     "MethodName""Process"  
  5.     }  
  6. ]   

Add two Project Reference (Library within solution) and one Package Reference (Base Class Library/Nuget) to StringPrograms.csproj. 

  1. <Project Sdk="Microsoft.NET.Sdk">  
  2.   <PropertyGroup>  
  3.     <OutputType>Exe</OutputType>  
  4.     <TargetFramework>netcoreapp1.1</TargetFramework>  
  5.   </PropertyGroup>  
  6.   <ItemGroup>  
  7.     <PackageReference Include="System.Runtime.Serialization.Json">  
  8.       <Version>*</Version>  
  9.     </PackageReference>  
  10.     <ProjectReference Include="../DataCore/DataCore.csproj" />  
  11.     <ProjectReference Include="../StringLibrary/StringLibrary.csproj" />  
  12.   </ItemGroup>  
  13. </Project>   

As we have updated StringPrograms.csproj, we need to restore the dependencies by executing dotnet restore.

dotnet restore

.NET Core

Open Program.cs and replace with the below code. 

  1. using static System.Console;  
  2. using System.Reflection;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Runtime.Serialization.Json;  
  6. using DataCore;  
  7.   
  8. namespace StringPrograms  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             var metadata = GetMetadata("appsettings.json");  
  15.   
  16.             foreach (var current in metadata)  
  17.             {  
  18.                 ExecuteMethods(current);  
  19.             }  
  20.   
  21.             WriteLine("\n\nPress any key ...");  
  22.             ReadKey();  
  23.         }  
  24.  
  25.         #region Private Methods.  
  26.         private static void ExecuteMethods(Metadata currentAssembly)  
  27.         {  
  28.             var programsAssembly = Assembly.Load(new AssemblyName(currentAssembly.AssemblyName));  
  29.             foreach (var currentClass in programsAssembly.GetTypes())  
  30.             {  
  31.                 var currentMethod = currentClass.GetMethod(currentAssembly.MethodName);  
  32.                 WriteLine($"{currentClass.Name} ....");  
  33.                 currentMethod.Invoke(System.Activator.CreateInstance(currentClass), null);  
  34.             }  
  35.         }  
  36.   
  37.         static List<Metadata> GetMetadata(string metadataFilePath)  
  38.         {  
  39.             var metadataFileStream = File.Open(metadataFilePath, FileMode.Open);  
  40.             var serializer = new DataContractJsonSerializer(typeof(List<Metadata>));  
  41.             return (List<Metadata>)serializer.ReadObject(metadataFileStream);  
  42.         }  
  43.         #endregion  
  44.     }  
  45. }   

Select the Program.cs within StringPrograms project. In the Debug Mode select “.NET Core Launch (StringPrograms)” and execute the program, you should see method from both the classes in StringLibrary are called successfully.

.NET Core

We can use the integration Git within Visual Studio Code to push the code to GitHub.

Ubuntu 14.04

Get the latest code from GitHub. Open Visual Studio Code with MultiLibMultiApps opened.

.NET Core
.NET Core

We need to restore the dependencies by executing dotnet restore for all the 6 projects.

dotnet restore

.NET Core

Select the Program.cs within LogicPrograms project and add a comment and check in the code into GitHub. 

  1. namespace StringPrograms  
  2. {  
  3.     /// <summary>  
  4.     /// Project created in Mac OS X.  
  5.     /// Updated in Windows 10.    
  6.     /// Commented in Ubuntu 14.04.  
  7.     /// </summary>  
  8.     class Program   

Select the Program.cs within StringPrograms project. In the Debug Mode select “.NET Core Launch (StringPrograms)” and execute the program, you should see method from both the classes are called successfully. You should be able to input the data using integrated Terminal.

.NET Core

Summary

In this article, I discussed how we can create console applications using .net code and C#. We also saw how to create these in Mac OS X (10.12.3), Ubuntu 14.04 and Windows 10. We also saw the same code works on Mac OS X (10.12.3), Ubuntu 14.04 and Windows 10.


Similar Articles