Create a C# and MongoDB Project Using .NET

Introduction

Pronounced “C Sharp”, C# is a general purpose programming language developed by Microsoft. C# is an object-oriented programming language useful for creating websites, mobile apps, video games and virtual reality environments. Visual Studio Code is an editor used for creating web and cloud applications. The Microsoft .NET SDK, or Software Development Kit, Framework gives developers the ability to build applications on x64 platforms. This tutorial will cover the steps needed to install Visual Studio Code and the .NET SDK framework for creating a C and MongoDB application.

Prerequisites

  • The .NET Core SDK must be download and installed the local dev machine to create a C and MongoDB application. The best way to compile and run C# is using an IDE with a built-in compiler, such as Visual Studio Code or Mono.

  • The examples in this tutorial assume using VS Code. The interactive installer for VS Code must be downloaded if running MacOS or Windows. For a Linux distro’s package repository, install VS Code via the terminal command line.

Install VS Code

For Windows or MacOS, download the interactive installer for Visual Studio code here and then double click the downloaded package and follow the installation instructions. For MacOS, the archive must be unzipped and then installed in the Visual Studio Code.app file.

Install Visual Studio code on Ubuntu

The VS Code can be installed with the APT-GET repository, if running a Debian flavor of Linux.

If it has not already been done, the first step is to add the apt-transport-https package to the repository with the following command:

sudo apt-get install apt-transport-https

Now update the local repository packages with apt-get update and then install code using the following commands:

sudo apt-get update -y && sudo apt-get install code

Install VS Code

Install the .NET Core

Download the .NET Core SDK framework from Microsoft’s Dotnet website, as shown here:

Screenshot of Dot NET Core installing on macOS for a C# and MongoDB project

To be safe, restart the machine once the installation has finsihed.

Install the .NET Core on Linux

For Linux, the .NET Core will have to be installed using terminal commands. If using a Debian flavor of Linux like Ubuntu, execute the following wget command to download the DEB archive:

wget -q https://packages.microsoft.com/config/ubuntu/19.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb

When finished downloading, be certain to run the following command from the same directory as the .deb package to install Microsoft’s .NET Core:

sudo dpkg -i packages-microsoft-prod.deb

Install the .NET SDK on Linux

If it has not already been done, update the local APT-GET repository with the sudo apt-get update command and then install the dotnet-sdk-3.1 package by executing the following command:

sudo apt-get install dotnet-sdk-3.1

Install the ASP.NET Core framework with the following command:

sudo apt-get install aspnetcore-runtime-3.1

Install the .NET SDK with snap

If the snap package manager is installed, the following command can also be used to install the .NET SDK:

sudo snap install dotnet-sdk --classic

Install MongoDB

The MongoDB service must also be installed and running before building a C# app for Mongo in Visual Studio Code.

Install MongoDB on Ubuntu

If running an Ubuntu flavor of Linux, such as Ubuntu 18 or Linux Mint, execute the following wget command to obtain the key for the MongoDB package:

wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -

Executing the above command should return a response of OK.

Now use echo to add the repository to Ubuntu’s sources.list.d file:

echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

Finally, install the DEB package for version 4.2 of MongoDB Community Edition by updating the local packages with the following command:

sudo apt-get update

The results should resemble the following:

Screenshot of installing MongoDB on Ubuntu for a C# MongoDB project

Now use the following command to start the MongoDB server:

sudo service mongod start

Install MongoDB on macOS

Homebrew can be used if building the C# MongoDB app on MacOS.

First, the brew repository must be updated and given a health check with the following brew doctor command:

brew update && brew doctor

Once it has finished updating, execute the following brew install command to install MongoDB Community Edition:

brew install mongodb

Now execute the following Homebrew command to start the MongoDB server:

brew services start mongodb

Verify that MongoDB is installed

When MongoDB has finished installing and the service has started, execute the following command to obtaining the version number and verify the service is working:

mongo --version

Install NuGet

Microsoft’s NuGet package manager must also be installed in order for the C# driver for MongoDB to work in the local development environment.

Install the NuGet package manager on Ubuntu

The NuGet service is installed with the APT repository on Ubuntu. Execute the following command to update the APT packages and then install NuGet:

sudo apt update && sudo apt install nuget

Install NuGet on macOS with Homebrew

A Mono library, called mono-libgdiplus, must be installed to make the macOS GDI+ (graphics device interface) compatible. Execute the following command to install the Mono library:

brew install mono-libgdiplus

The Nuget package manager can now be installed with the following command:

brew install nuget

NOTE: This will be used later to install the C# driver for MongoDB using the nuget command.

Install the C# MongoDB driver

Download the NuGet driver for MongoDB here. Alternatively, the following command can be executed in the project’s VS Code terminal to install the C# driver for MongoDB:

dotnet add package MongoDB.Driver --version 2.10.0

The following nuget command can also be used in a UNIX terminal to install the C# driver for MongoDB on MacOS or Linux:

nuget install mongoDB.Driver && nuget install mongocsharpdriver

The results should resemble the following:

Install C# driver for MongoDB using the dotnet add package command

Create a .NET project

Now create a new .NET project folder for the C# and MongoDB application.

Create a new VS Code project folder

Open the Visual Studio Code application and click the VS code folder icon in the left sidebar. A modal pop-up window should appear with the title New Folder and a prompt to name the project, as shown here:

Screenshot of a new VS Code folder for the C# and MongoDB project

Clicking the blue -kbd-Create-/kbd- button will generate all of the necessary .NET files and dependencies for the C# project.

NOTE: Make sure the name doesn’t have any spaces, underscores (_) or hyphens (-). Typically .NET project names use PascalCase or UpperCamelCase, where the first letter of each word is capitalized.

Install the C# extension for VS Code

Now the VS Code C# extension must be installed in the Code Extension Marketplace. As shown on the below screenshot, click the Extension Marketplace icon in the left-hand sidebar to load the marketplace. Next type c# in the input field to search for the extension. Make sure to install the official Microsoft extension.

Screenshot of the Visual Studio Code Extension Marketplace installing the C# extension

Build and restore the .NET project

At this point the project files should be visable in the sidebar. However, the project must be initilized using VS Code’s built-in terminal.

To open the terminal panel, press -kbd-CTRL-/kbd-+-kbd-`-/kbd- to open the terminal panel from the bottom. Alternatively, as shown below, navigate to ‘View’ in the main menu and then click ‘Terminal’ in the drop-down menu.

Screenshot of a C# MongoDB project opening VS code terminal from View menu

Use the ‘dotnet’ command to start the project

Now the dotnet command can be used in the VS terminal to initialize the .NET project for the C# and MongoDB application by executing the following command:

dotnet new console

The system should return the following response:

Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs
Write your first app: https://aka.ms/first-net-core-app

Now the following restore command can be used to restore the project dependencies:

dotnet restore

The results should resemble the following:

dotnet new console command in a VS Code terminal for a C# and MongoDB project

Finally, execute the following run command to compile and run the C# code for the project:

dotnet run

The console should display a Hello, world response that indicates the application working.

C# code for MongoDB

Delete all of the contents in the Program.cs script. Now paste the following C# code into it so it will return a string containing all of the MongoDB database names:

using System;
using MongoDB.Driver;

namespace MongoProject
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connString = "mongodb://127.0.0.1:27017";
                MongoClient client = new MongoClient(connString);

                // List all the MongoDB databases
                var allDatabases = client.ListDatabases().ToList();

                Console.WriteLine("MongoDB db array type: " + allDatabases.GetType());
                Console.WriteLine("MongoDB databases:");
                Console.WriteLine(string.Join(", ", allDatabases));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.Message);
            }
        }
    }
}

NOTE: Make sure to modify the above connString variable to match the domain and port of the MongoDB server. Use 127.0.0.1:27017 if running MongoDB on a localhost server using the default MongoDB port of 27017.

Now execute the above code using the following run command:

dotnet run

The project application should return something that resembles the following VS Code in the terminal:

{ "name" : "admin", "sizeOnDisk" : 40960.0, "empty" : false },
{ "name" : "config", "sizeOnDisk" : 110592.0, "empty" : false },
{ "name" : "local", "sizeOnDisk" : 40960.0, "empty" : false }

Screenshot of C# MongoDB returning an array of MongoDB databases in a Dotnet VS Code project

Conclusion

This tutorial explained the steps required to install Visual Studio Code and the .NET SDK framework for creating a C and MongoDB application. This comprehensive tutorial covered how to install VS Code and how to download and install the .NET Core SDK framework. The article explained how to install MongoDB and confirm the installation, how to install Microsoft’s NuGet and its package manager and how to install the C# MongoDB driver. The tutorial also covered how to create a .NET project and a new VS Code project folder, how to install the C# extension for VS Code, build and restore the .NET project and run the C# code for MongoDB. Remember to be sure to modify the connString variable to match the domain and port of the MongoDB server.

Just the Code

using System;
using MongoDB.Driver;

namespace MongoProject
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connString = "mongodb://127.0.0.1:27017";
                MongoClient client = new MongoClient(connString);

                // List all the MongoDB databases
                var allDatabases = client.ListDatabases().ToList();

                Console.WriteLine("MongoDB db array type: " + allDatabases.GetType());
                Console.WriteLine("MongoDB databases:");
                Console.WriteLine(string.Join(", ", allDatabases));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.Message);
            }
        }
    }
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.