Building a Crypto News Website in C# using the Microsoft Azure App Service and MongoDB Atlas

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Community Hub.

Who said creating a website has to be hard? Writing the code, persisting news, hosting the website. A decade ago this might have been a lot of work. These days, thanks to Microsoft Blazor, Microsoft Azure App Service, and MongoDB Atlas you can get started in minutes. And finish it equally fast!

 

In this tutorial I will walk you through:

 

  • setting up a new Blazor project,
  • creating a new page with a simple UI,
  • creating data in MongoDB Atlas,
  • showing those news on the website and
  • making the website available by using Azure App Service to host it.

 

All you need is this tutorial and the following pre-requisites, but if you prefer to just read along for now, check out the GitHub repository for this tutorial where you can find the code and the tutorial.

 

Pre-requisites for this tutorial

 

Before we get started, here is a list of everything you need while working through the tutorial.

I recommend getting everything set up first so that you can seamlessly follow along.

 

 

Creating a new Microsoft Blazor project that will contain our Crypto News Website

 

Now that the pre-requisites are out of the way, let's start by creating a new project.

 

denverbrittain_0-1680798036034.jpeg

 

 

Search for `Blazor Server App` and click `Next`.

 

 

denverbrittain_1-1680798036044.jpeg

 

 

Choose a `Project name` and `Location` of your liking.

I like to have the solution and project in the same directory, but you don't have to.

 

 

denverbrittain_2-1680798036048.jpeg

 

 

Choose your currently installed .NET framework (as described in `Pre-requisites`) and leave the rest on default.

 

Click Create and you are good to go!

 

 

denverbrittain_3-1680798036050.jpeg

 

 

Adding the MongoDB Driver to the project to connect to the database

 

Before we start getting into the code, we need to add one NuGet package to the project,

the MongoDB DriverThe Driver is a library that let's you easily access your MongoDB Atlas cluster and work with your database.

 

Click on Project -> Manage NuGet Packages... and search for MongoDB.Driver.

 

 

denverbrittain_4-1680798036057.jpeg

 

 

During this process you might have to install additional components like the ones shown in the following screenshot. Confirm this installation as we will need some of those as well.

 

 

denverbrittain_5-1680798036060.jpeg

 

 

Another message you come across might be the following license agreements which you need to accept to be able to work with those libraries.

 

 

denverbrittain_6-1680798036064.jpeg

 

 

Creating a new MongoDB Atlas cluster and database to host our Crypto News

 

Now that we've installed the driver, let's go ahead and create a cluster and database to connect to. 

 

When you register a new account you will be presented with the selection of a cloud database to deploy. Open the Advanced Configuration OptionsFor this tutorial we only need the forever-free shared tier. Since the website will later be deployed to Azure, we also want the Atlas cluster deployed in Azure. And we also want both to reside in the same region. This way we decrease the chance of having an additional latency as much as possible. Here you can choose any region, just make sure to choose the same one later on when deploying the website to Azure. The remaining options can be left on their defaults.

 

 

denverbrittain_7-1680798036073.jpeg

 

 

 

denverbrittain_8-1680798036084.jpeg

 

 

The final step of creating a new cluster is to think about security measures by going through the Security Quickstart.

 

 

denverbrittain_9-1680798036092.jpeg

 

 

Choose a Username and Password for the database user that will access this cluster during the tutorial. For the Access List we need add 0.0.0.0/0 since we do not know the IP address of our Azure deployment yet. This is ok for development purposes and testing but in production you should restrict the access to the specific IPs accessing Atlas.

 

Atlas also supports the use of network peering and private connections using the major cloud providers. This includes Azure Private Link or Azure Virtual Private Connection

(VPC) if you are using an M10 or above cluster.

 

Now Click Finish and Close.

 

Creating a new shared cluster happens very, very fast and you should be able to start within minutes. As soon as the cluster is created, you'll see it in your list of Database Deployments.

 

Let's add some sample data for our website! Click on Browse Collections now.

 

 

denverbrittain_10-1680798036102.jpeg

 

If you've never worked with Atlas before, here are some vocabularies to get your started:

 

  • A cluster consists of multiple nodes (for redundancy).
  • A cluster can contain multiple databases (which are replicated onto all nodes).
  • Each database can contain many collections, which are similar to tables in a relational database.
  • Each collection can then contain many documents. Think rows, just better!
  • Documents are super-flexible because each document can have its own set of properties. They are easy to read and super flexible to work with JSON-like structures that contain our data.

 

Creating some test data in Atlas

 

Since there is no data yet, you will see an empty list of databases and collections.

Click on Add My Own Data to add the first entry.

 

denverbrittain_11-1680798036110.jpeg

 

The database name and collection name can be anything but to be in line with the code we'll see later, call them crypto-news-website and news respectively and hit Create.

 

denverbrittain_12-1680798036112.jpeg

 

This should lead to a new entry that looks like this:

 

denverbrittain_13-1680798036113.jpeg

 

 

Next, click on INSERT DOCUMENT.

 

There are a couple things going on here. The _id has already been created automatically.

Each document contains one of those and they are of type ObjectId. It uniquely identifies the document.

 

By hovering over the line count on the left, you'll get a pop-op to add more fields.

Add one called title and set its value to whatever you like, the screenshot shows an example you can use. Choose String as the type on the right. Next, add a date and choose Date as the type on the right.

 

denverbrittain_14-1680798036116.jpeg

 

Repeat the above process a couple times to get as much example data in there as you like.

You may also just continue with one entry though if you like and fill up your news when you are done.

 

Creating a connection string to access your MongoDB Atlas cluster

 

The final step within MongoDB Atlas is to actually create access to this database so that the MongoDB Driver we installed into the project can connect to it.

This is done by using a connection string.

 

 

A connection string is a URI that contains username, password and the host address of the database you want to connect to.

 

Click on Databases on the left to get back to the cluster overview. This time, hit the Connect button and then Connect Your ApplicationIf you haven't done so before, choose a username and password for the database user accessing this cluster during the tutorial. Also, add 0.0.0.0/0 as the IP address so that the Azure deployment can access the cluster later on. Copy the connection string that is shown in the pop-up.

 

denverbrittain_15-1680798036124.jpeg

 

Creating a new Blazor page

 

If you have never used Blazor before, just hit the Run button and have a look at the template that has been generated. It's a great start and we will be re-using same parts of it later on.

 

Let's add our own page first though. In your Solution Explorer you'll see a Pages folder.

Right-click it and add a Razor Component. Those are files that combine the HTML of your page with C# code.

 

denverbrittain_16-1680798036129.jpeg

 

denverbrittain_17-1680798036133.jpeg

 

Now, replace the content of the file with the following code. Explanations can be read inline in the code comments.

 

@* The `page` attribute defines how this page can be opened. *@ @page "/news" @* The `MongoDB` driver will be used to connect to your Atlas cluster. *@ @using MongoDB.Driver @* `BSON` is a file format similar to JSON. MongoDB Atlas documents are BSON documents. *@ @using MongoDB.Bson @* You need to add the `Data` folder as well. This is where the `News` class resides. *@ @using CryptoNewsApp.Data @using Microsoft.AspNetCore.Builder @* The page title is what your browser tab will be called. *@ <PageTitle>News</PageTitle> @* Let's add a header to the page. *@ <h1>News</h1> @* And then some data. *@ @* This is just a simple table containing news and their date. *@ @if (_news != null) { <table class="table"> <thead> <tr> <th>News</th> <th>Date</th> </tr> </thead> <tbody> @* Blazor takes this data from the `_news` field that we will fill later on. *@ @foreach (var newsEntry in _news) { <tr> <td>@newsEntry.Title</td> <td>@newsEntry.Date</td> </tr> } </tbody> </table> } @* This part defines the code that will be run when the page is loaded. It's basically *@ @* what would usually be PHP in a non-Blazor environment. *@ @code { // The `_news` field will hold all our news. We will have a look at the `News` // class in just a moment. private List<News>? _news; // `OnInitializedAsync()` gets called when the website is loaded. Our data // retrieval logic has to be placed here. protected override async Task OnInitializedAsync() { // First, we need to create a `MongoClient` which is what we use to // connect to our cluster. // The only argument we need to pass on is the connection string you // retrieved from Atlas. Make sure to replace the password placeholder with your password. var mongoClient = new MongoClient("YOUR_CONNECTION_STRING"); // Using the `mongoCLient` we can now access the database. var cryptoNewsDatabase = mongoClient.GetDatabase("crypto-news-database"); // Having a handle to the database we can furthermore get the collection data. // Note that this is a generic function that takes `News` as it's parameter // to define who the documents in this collection look like. var newsCollection = cryptoNewsDatabase.GetCollection<News>("news"); // Having access to the collection, we issue a `Find` call to find all documents. // A `Find` takes a filter as an argument. This filter is written as a `BsonDocument`. // Remember, `BSON` is really just a (binary) JSON. // Since we don't want to filter anything and get all the news, we pass along an // empty / new `BsonDocument`. The result is then transformed into a list with `ToListAsync()`. _news = await newsCollection.Find(new BsonDocument()).Limit(10).ToListAsync(); // And that's it! It's as easy as that using the driver to access the data // in your MongoDB Atlas cluster. } }

 

In the above, you've noticed the News class which still needs to be created.

In the Data folder, add a new C# class, call it News and use the following code.

 

using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace CryptoNewsApp.Data { public class News { // The attribute `BsonId` signals the MongoDB driver that this field // should used to map the `_id` from the Atlas document. // Remember to use the type `ObjectId` here as well. [BsonId] public ObjectId Id { get; set; } // The two other fields in each news are `title` and `date`. // Since the C# coding style differs from the Atlas naming style, we have to map them. // Thankfully there is another handy attribute to achieve this: `BsonElement`. // It takes the document field's name and maps it to the classes field name. [BsonElement("title")] public String Title { get; set; } [BsonElement("date")] public DateTime Date { get; set; } } }

 

Now it's time to look at the result. Hit Run again.

 

The website should open automatically, just add /news to the URL to see your new News page.

 

denverbrittain_18-1680798036137.jpeg

 

If you want to learn more about how to add the news page to the menu on the left, you can have a look at another Blazor specific tutorial.

 

Deploying the website to Azure App Service

 

So far so good. Everything is running locally. Now to the fun part, going live! Visual Studio makes this super easy. Just click onto your project and choose Publish....

 

denverbrittain_19-1680798036141.jpeg

 

The Target is Azure, the Specific target is Azure App Service (Windows).

 

denverbrittain_20-1680798036144.jpeg

 

denverbrittain_21-1680798036148.jpeg

 

When you registered for Azure earlier, a free subscription should have already been created and chosen here. By clicking on Create new on the right you can now create a new App Service.

 

denverbrittain_22-1680798036151.jpeg

 

The default settings are all totally fine. You can however choose a different region here if you want to. Finally, click Create and then Finish.

 

denverbrittain_23-1680798036155.jpeg

 

denverbrittain_24-1680798036158.jpeg

 

When ready, the following pop-up should appear and by clicking Publish you can start the actual publishing process. It eventually shows the result of the publication.

 

denverbrittain_25-1680798036162.jpeg

 

denverbrittain_26-1680798036164.jpeg

 

 

The above summary will also show you the URL which was created for the deployment.

My example: https://cryptonewsapp20230124021236.azurewebsites.net/

 

Again, add /news to it to get to the News page.

 

denverbrittain_27-1680798036167.jpeg

 

 

What's next?

 

Go ahead and add some more data. Add more fields or style the website a bit more than this default table.

 

The combination of using Microsoft Azure and MongoDB Atlas makes it super easy and fast to create websites like this one. But it is only the start. You can learn more about Azure on the Learn platform and about Atlas on the MongoDB University.

 

And if you have any questions, please reach out to MongoDB at the MongoDB Forums or tweet @dominicfrei.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.