Introduction
Unlike Windows app development, building apps in Mac environment is bit different because we will be dealing with the new commands, tools, and the file structure. To put it in other words, I’m not that familiar with the MAC environment and it’s a real P.I.T.A. This article aims to guide developers like me who aren’t familiar with MAC OSX and want to jump on .NET Core, or for folks who want to try out .NET Core on MAC environment.
Docker-ing your life Since we don't currently have the Microsoft SQL Server engine available for MacOS, I had to use Docker in order to install Linux's MS SQL Server in a container and although this may sound complicated at first, there's a really awesome post written by @reverentgeek that can teach you exactly how to do it and even more! Commandline 'dotnet run' Your website is really a dotnet console app, that self-hosts a website using a tiny webserver called Kestrel. (There's a lot to unpack in that sentence, but just let it wash over you for now) You can run it, from the console, by calling dotnet run from the folder that contains the project.json file. How to run the project. Now, let’s run and debug the source in the VS Code editor. To run the source, we can either: Use command line tool with the command dotnet run.; Use inbuilt run option in. I've created a.NET Core console application. I want to build the app so that I can execute it on Windows or MacOS without dotnet core being installed on the machine.
While there are a bunch of resources on the web that demonstrate how to build and run .NET Core apps in docker, it seems to me that there are only limited resources on doing it on MAC. This article will walk you through on building your first ASP.NET Core app with Web API, EF, PostgreSQL and running it on Docker.
Getting Started
Before we get our hands dirty, let’s go ahead and install the required tools needed for us to build and run the application. If you already have installed the prerequisites mentioned below, then you may skip it and proceed.
Prerequisites
NET Core
.NET Core gives us the dotnet command line tools for us to build and run .net core apps without any IDE. Download and follow the installation steps for .NET Core in MAC here.
Visual Studio Code
Visual Studio Code is a lightweight, yet powerful code editor which runs on MAC, Linux and Windows. We’ll be using VSCode to write our C# code and HTML markup. Download and install Visual Studio Code here.
NodeJS and NPM
We’ll be needing NodeJS because we are going to use Yeoman to scaffold ASP.NET Core Web App template and we will be using NPM to install packages. Install NodeJs and NPM, you can get the latest installer here.
Creating the .NET Core Application
Open the terminal and let’s start by installing Yeoman and Bower. Run the following command:
Once you’ve done that, run the following command to install the ASP.NET Core template generator:
Hey there r/MacApps, I've jammed on this app for a couple years now that lets you assign names to Spaces via the menubar and offers glanceable app-usage stats (with a bunch of pretty graphs/charts). The app also lets you jump directly to your named Spaces via its dropdown menu or via global hotkeys. Because Apple lets you have up to 16 Spaces per screen, this is handy in navigating between them. Mac timer app reddit.
The
-g
flag installs the generator globally, so that it can be used from any path.Now, we are ready to create our ASP.NET Core application. First, we need to create a directory for our project. To do that, run following command:
The command above creates the folder scr/dotnetcoreapp within my user account. Now let’s run the ASP.NET generator for yo:
Now, you might be asked to report usage statistics to improve the tool, just key in Y/N to answer that. In my case, I’ve chosen Y (yes). After that, it should provide you with the following result:
The generator displays a list of items for us to select the project type. For this demo, we are going to select the Empty Web Application project template. Tap enter and then type-in the project name. For this case, we are going to name the project as 'dotnetcorehello'. Tap enter to generate the project with the default files as shown in the figure below:
The generator displays a list of items for us to select the project type. For this demo, we are going to select the Empty Web Application project template. Tap enter and then type-in the project name. For this case, we are going to name the project as 'dotnetcorehello'. Tap enter to generate the project with the default files as shown in the figure below:
As we can see, the generator creates an ASP.NET Core project. This newly created project can be loaded into Visual Studio Code or use the command line to run the application.
Restore, Build and Run the Application
To ensure that we are on the right track, we will test the app by running the project. Now change the directory of the command line to point to our newly created project. In this case, do:
then run the following command:
The resulting command should result to something like this:
Then we can build the application using the following command:
Then we can build the application using the following command:
and then run it using the following command:
Now open your browser and then try to browse the the following URL:
http://localhost:5000
. When everything is good, then you should be able to see the following output:Cool! We just had our first .NET Core application running on MAC. It’s time for us to move further and create a simple Web API that exposes some methods and explore Docker on MAC.
Installing and Running the Application on Docker
Go ahead and install Docker for MAC here.
Now, let’s try to run our .NET Core application within docker. The first thing to do is open Visual Studio Code and then install the C# Extension.
After that, open the project that we have just created earlier. You will notice that the project already contains the 'Dockerfile' just like in the figure below:
The
Dockerfile
contains the instruction to build the docker image. For more information, see: Dockerfile ReferenceOpen startup.cs and under
Configure()
method, let’s modify the output to something like this:To ensure that our changes will be reflected, then do a build again by running the following command:
Now let’s take a look at how to build and run the docker image. Open the terminal and then make sure that the directory is pointing to the root where your
project.json
is located. Once you’re set, run the following command below:If the build is successful, you should be presented with something like this:
Cool, let’s verify if the image was created successfully within our Docker machine by running the following command:
As you can see, our newly created image named 'dockerdotnetcore' was listed. Awesome, now we are ready to run the application. Type the following command.
Running the command above will result in something like this.
To see all the running images, run the following command.
Let’s run off to the browser and append port 5000 to our local IP. The output should result to something like this.
Awesome! we now have a .NET Core running on Docker. Our next step is to integrate EF Core, PostgreSQL and create a basic Web API methods that will serve some data.
Integrating EF Core and PostgreSQL
Entity Framework Core now supports a variety of database providers. In this particular demo, we will take a look at how to integrate PostgreSQL in our .NET Core application.The easiest way to install Postgres is using Homebrew which should be included upon installing the .NET Core SDK. Now run the following command to download and install PostreSQL:
If the installation went well, then the database manager should be installed. Now, let's launch the PostgreSQL service container by running the following command:
The
-d
option runs a container in the background and prints the container ID. The --name
assigns a name to the container, in this case we named our container as 'pg-db'. The -e
allow us to set the environment variables, which in this case, we’ve set a password to 'supersecret' for our Postgres image using the POSTGRES_PASSWORD
variable.Running the command above will expose the postgres port
5432
which allow a standard container to be available to the linked containers. The initdb
will also be generated with default user and database.Again, to verify that our PostgresSQL Docker container is up and running do:
To test the connection, you can do:
Integrating Entity Framework Core and MVC
It’s time for us to integrate EF and its dependencies so we can run migrations against the database. Migration enables us to create our models in our code (Code-First approach), and create the database base from our model. Open
project.json
and then add the following references within the dependencies node:then add the following reference under the tools node:
Make sure to save the file, or simply type the command
dotnet restore
from the terminal to restore the packages and tools that we’ve added.Creating the Entity Model
Create the following class within your application:
and then create another class for our
DbContext
:The
Band
class serves as our model that houses some properties. This model is just a simple POCO
object. The BandDbContext
typically used to customize the model and to expose DbSet<T>
’s which are used to query the database.Configuring the ConnectionString
![App App](https://switchfocus.com/pictures/75fc0db8c12d9726964207015f1555db.jpg)
Now that we have our model and DB context ready, the next thing that we are going to do is to setup the connection string for us to be able to run a migration against our database. Add the following configuration within your
appsettings.json
file:Configuring Services
We need to inject our
BandDbContext
and enable MVC service. Open Startup.cs
file and append the following code below within the ConfigureServices()
method:Finally, we need to update the
Configure()
method so it would look like this:EF Core does not do the migration automatically, that’s why we need the pieces of configuration above for us to use Code-First migrations. The
Database.Migrate()
method piece is responsible for two things: (1) The creation of database in PostgreSQL if it does not exist yet. (2) Migrating the database schemas to the latest version.Generate Migrations
As you may have already guessed, we will be using EF Core tools to scaffold our migration and of course updating the database. We’ll be using the command line (dotnet CLI) to run our migrations.
Though the migration process will build your app first, we can also build the app ahead just to ensure that our application doesn’t have errors by running the following command:
When successful, run the following command to generate migrations:
The
ef migration add
is the command to add migrations. When the migration is successful, you should be able to see a new folder named 'Migrations' that contains the migration files.The files generated above will be used to create the database on initial run.
Creating the Web API
Okay, it’s time for us to create a simple Web API methods to work with simple
GET
and POST
requests. Add a new class and copy the following code:Nothing really fancy there, the code above just contains a few basic methods that communicates to our PostgreSQL database. Notice that we’ve injected an instance of our
BandDbContext
in the Controller’s constructor, so we can interact with our database, and use the it for querying the database.Running the Application on Docker
At this point, we are ready to deploy the application on Docker. First let’s build the app by running the following command:
The command above will generate a new instance of image within our docker machine. You can check the list of image by running
docker images
in the command line.Now, run the following command to ensure that our PostgreSQL database image is up and running:
Now, let’s run our .NET Core application and link the database that we’ve created using the following command:
Testing the Application
Here are some of the screenshots for the test that I’ve made, using Postman.
POST:
http:<Your IP>:5000/api/band
GET:
http:<Your IP>:5000/api/band
GET:
http:<Your IP>:5000/api/band/<id>
That's it! I hope you will find this article useful.
Summary
In this article, we’ve learned the basics on setting up .NET Core on MAC environment and learned how to create a simple ASP.NET Core application with Web API, EF, PostgreSQL and running it on Docker.
References
https://docs.docker.com/docker-for-mac/
https://docs.docker.com/docker-for-mac/docker-toolbox/
https://getcarina.com/docs/tutorials/run-docker-image/
https://hub.docker.com/r/proudmonkey30/netcoredemo/
https://medium.com/trafi-tech-beat/running-net-core-on-docker-c438889eb5a#.8a9aini0b
https://hahoangv.wordpress.com/2016/08/05/docker-for-net-developers-net-core-ef-core-and-postresql-in-docker/
http://blog.thoward37.me/articles/where-are-docker-images-stored/
https://docs.docker.com/engine/examples/postgresql_service/
http://andrewlock.net/adding-ef-core-to-a-project-on-os-x/
Docker Commands: https://docs.docker.com/engine/reference/commandline/run/
https://docs.docker.com/docker-for-mac/docker-toolbox/
https://getcarina.com/docs/tutorials/run-docker-image/
https://hub.docker.com/r/proudmonkey30/netcoredemo/
https://medium.com/trafi-tech-beat/running-net-core-on-docker-c438889eb5a#.8a9aini0b
https://hahoangv.wordpress.com/2016/08/05/docker-for-net-developers-net-core-ef-core-and-postresql-in-docker/
http://blog.thoward37.me/articles/where-are-docker-images-stored/
https://docs.docker.com/engine/examples/postgresql_service/
http://andrewlock.net/adding-ef-core-to-a-project-on-os-x/
Docker Commands: https://docs.docker.com/engine/reference/commandline/run/
# How YOU can get started with .NET Core and C# in VS Code
Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris
This article covers your first steps using .NET Core, the cross-platform version of .NET. We will be creating a solution, a library, a console app and also a test project. Of course, we will be taught how to execute our tests, all this from the terminal
.NET has been around since 2001 and a lot of developers have cut their teeth on using Visual Basic .NET or C# with Visual Studio. They were using Windows at the time. Times have changed, cross-platform is a must nowadays and .NET as well as Visual Studio exists on both Windows, Linux, and Mac.
In this article we will cover:
- Installing .NET Core and some nice extensions like C#
- Scaffold a solution
- Add a class library and add it to the solution
- Add a test project and run our tests
- Add a Console program and use our library
- Improve our IDE with vscode-solution-explorer extension
what commands we were taught and what to look at next like ASP, Docker, Cloud
# Resources
- Host a .NET Core appThere are many ways to host a .NET Core app, Windows, Azure etc.
- Publish you .NET Core app to the CloudLet's learn how to publish our .NET Core app to the Cloud and Azure.
- Sign up for a free Azure accountTo be able to use Azure you will need a free Azure account
- Hello world tutorial - console appThis shows a simple Hello World console application
- Containerize a .NET Core AppThis explains how to Dockerize your app, how to author the Dockerfile etc.
- Unit testing in .NET CoreThere is more than one choice for unit testing
- dotnet CLI - all commandsThere are so many commands for the
dotnet
tool. Did you know that you can scaffold a .NET project with a React frontend for example? - Create a new web app with ASP and .NET CoreGreat tutorial for creating your first Web app in .NET Core
## Install and Set up
The first thing you want to do is to install .NET Core. Head over to this page:
Once it's installed you should have access to a command-line tool you can invoke in the terminal called
dotnet
. You can easily see what commands are available by typing:Quite a few commands as you can see above. We will explore some of these commands for creating solutions and projects.
Because we will be working with C# and VS Code I recommend downloading VS Code
https://code.visualstudio.com/download
Once you got VS Code on your system go and install the C# extension. Type
C#
, it should look like so:Good, now we are set up and ready code ?
# Creating a solution
The first we will do is to create a solution. A solution is something we use to keep track of all related projects. As an old .NET developer you might be used to do this via Visual Studio but we will actually do this via the terminal.
We will take the following steps:
- Create a directory for our solution
- Invoke the command generating a solution
First things first, let's create a directory:
You can name your directory anything you want,
app
was just an example.Next, let's create a solution. We do this with the following command:
sln
is short for solution
, this will generate a new solution. Because we are standing in the app
directory this generates an app.sln
file.## Create a libraryNext up we will generate a library. Now a library is not an executable program but more a set of files we include in other projects.
To create a library we will need to type the following in the terminal (we are still in the
app
directory):Above we can see that our general command is
dotnet new
, followed by the type, which in this case is classlib
, then we use the flag -o
and the last argument is the name of the project.Let's have a look at what we got:
We see that the directory
library
was created. We also see that we got the file Class1.cs
, the project file library.csproj
and a directory obj
. At this point, lets switch to VS Code and look at our files. Looking att Class1.cs
, it looks like this:It doesn't do much but it's valid C# code.
Let's finish this section by adding to the solution:
This adds the following entry to
app.sln
:For now, we are not going to spend so much time thinking about this other than we have a solution that knows about our library.
# Updating our library
Dotnet Publish Mac
Ok, we need to add some code to our library project. We will do the following:
- Download a NuGet package from a NuGet repository
- Reference our NuGet package in our library code
- Build our code
# Download and use a package from the NuGet repository
https://www.nuget.org/
Is a big (160k + libraries) repository where all NuGet libraries live. Anything that lives here can be downloaded by a simple command. For this part, we will grab a specific library called
Newtonsoft.Json
. This will allow us to parse JSON back and forth. To make this library part of our solution we can type:The above means we are adding the package
Newtonsoft.Json
to the project library
. The command should be read like this:Sometimes you might be working on an existing project or you might have grabbed the latest changes. Regardless of which, you might be missing some packages that your project or solution needs to run properly. At that point, you can run the command
Dotnet Run Urls
This will grab the packages specified as package references in your projects
csproj
file.# Update our library code
In your library project, change the file
Class1.cs
to Thing.cs
and add the following code to it:### Build
Next up we need to compile our code. This will, if successful, generate a so-called
.dll
file. This is the format used by .NET for libraries and stands for dynamic link library.So let's compile our code with the command:
My messages app on my mac is not opening. Fix iMessage Not Syncing with iCloud Issue on iPhone, iPad, and Mac. So, how are we going to get. Mail not launching since macOS Catalina update. This is one of the most common problems people. If you try to open a version of the Mail app that can’t be used on your Mac, an alert message is displayed. Make sure the version of Mail you’re trying to open is located in the Applications folder. In the Finder, click Applications in the sidebar, then double-click Mail. If the problem continues, contact Apple Support. See also Troubleshoot email problems in Mail on Mac. Reboot iMessage by going to Settings Messages and turning off iMessage, then turn off your iPhone by pressing and holding the on/off switch, slide to power off, and then wait for your iPhone to. Problems viewing messages and mailboxes. If a mailbox is offline. If searching doesn’t find the right emails. If emails aren’t displayed or look strange. If emails appear to be missing. If you can’t open Mail. If messages are in a Recovered Messages mailbox.
As indicated in the above image, we get a
library.dll
Success!
# Creating a test library
Next up we will create a test project. All codes deserve some level of testing and what better way to start than having tests set up early on. To create a test project we need to type the following:
This will create a test project of type
xunit
with the name test-library
.# Adding references
Let's add our project to the solution file as well:
The idea here is to test functionality found in our project called
library
. For this to be possible we need to add a reference to library
in our test-library
project, like so:# Writing a test
When we created our
test-library
we got a file called UnitTest1.cs
created as well. Let's have a look at this file:We use the decorator
[Fact]
to indicate that this is a test method that needs to be evaluated and ran. Let's add some code next to UnitTest.cs
:### Running our test/s
We are now ready to run our test and inspect the outcome.
To run the tests, type:
We use the command
dotnet test
and the last argument is where to find the project file for the test project. So what do we get?We can see from the above image that our test run failed. It clearly indicated
[Fail]
. Let's look at the WHY. Expected the result to be NOT 42. Hmm, let's check the implementation in Thing.cs
in our library
project:We cleary just take
2
input arguments and sum them up. What about the test in UnitTest1.cs
?19
+ 23
to be NOT equal to 42. Wait a minute.. It should be Equal
. Let's change that:and let's rerun the test:
Let's inspect the results and..
This time around the tests is succeeding.
Success! ?
# Console app
Next thing we are going to do is to create a Console App. Why do you ask? Well, we want to show the whole idea of creating a reusable library that we can drop in anywhere, from test projects to console projects.
Let's generate our console project like so:
This gives us a runnable project with a file
Program.cs
that serves as the entry point. Technically the entry point is a method called Main()
:Let's add this project to the solution file, like so:
# Adding and using our library project
Next order of business is to start using our
library
project and make it part of our console-app
project. So we add the dependency like so:Read the above as:
Next up we need to change the code of our
Program.cs
file to the following:Let's run the app next
We got ourselves a running app, using the code from the
library
project.Awesome ?
## DebuggingDebugging. That's one of the great things about using Visual Studio. It was and is outstanding. Personally, I think it's second to none, so what's the situation in VS Code?
Run Dotnet App From Console
Well, let's see how we debug and then reflect on how well it does it.
Now VS Code will ask you for adding a needed resource for debugging if you open a solution missing it. So how do I know what's missing? Well you should have a
.vscode
directory looking like this:![Full Full](/uploads/1/3/4/2/134200812/504976144.png)
That's it?
Well, you might try to select
Debug/Start Debugging
from the menu and you will notice it's running the test-library
if you look at the end of the debug windowNow, you probably want to change that to actually run the
console-app
project when debugging. To make that happen we need to go into launch.json
under the directory .vscode
. Find the entry looking something like this:We need to change the property
'program'
to point to our console app and also the 'cwd'
.It should now look like the below in
launch.json
Then select menu option
Debugging/Start Debugging
and we should see the belowThere we have it, boys and girls, working debugging ?
So, the experience, well the first thing that happened was that I just noticed that when I changed the code in
Program.cs
my breakpoint was not hit properly. This had an explanation. Looking at our entry in launch.json
we see there is a property 'preLaunchTask': 'build'
that points out a task that should run before our debug. This task resides in tasks.json
. Heading over to that file we noticed that it looked like this:YES, you are correct we weren't building the correct project before running the debug again. The way to fix this was to either run
in the terminal OR, fix this task and have it point to our
console-app
, like so:If you were to debug again everything works. Now you know a little bit more how things work in VS Code.
If I were to have an opinion here I would like to have this abstracted away from me as a user. I'd rather want a plugin doing this for me. At this point, I wish for a solution explorer, like the one I have in Visual Studio.
## Improve IDE
If you are like me with more 10+ years on the .NET platform, you are looking for ways to make this into Visual Studio as much as possible. You, of course, welcome new ways of doing things like using the terminal but it feels like you want a UI. Maybe I should use the actual Visual Studio then?
Well, there is a plugin that fixes this. It's called
vscode-solution-explorer
. If you install it your project will suddenly look like this:and right-clicking on a project will give you a menu like this:
My spontaneous reaction is ?
This is not an official extension by Microsoft but it's very nice and well worth a try if you like me enjoy terminal commands but sometimes just want a UI.
# Summary
Ok, let's try to sum this up. We have gotten quite the education on .NET Core. We were taught to use
dotnet
core to do everything from scaffolding different types of project to creating solutions, adding references, building our code to running tests. Quite versatile.Lastly, we also showed a plugin that offers an alternate approach to all our terminal commands. Of course, under the hood, it's running our terminal commands, so there is definitely value to learn the ways of the CLI. ?