How to Build Your First .NET Core Application with MongoDB Atlas

So you’re a .NET Core developer or you’re trying to become one and you’d like to get a database included into the mix. MongoDB is a great choice and is quite easy to get started with for your .NET Core projects.

In this tutorial, we’re going to explore simple CRUD operations in a .NET Core application, something that will make you feel comfortable in no time!

The Requirements

To be successful with this tutorial, you’ll need to have a few things ready to go.

  • .NET Core installed and configured.
  • MongoDB Atlas cluster, M0 or better, deployed and configured.

Both are out of the scope of this particular tutorial, but you can refer to this tutorial for more specific instructions around MongoDB Atlas deployments. You can validate that .NET Core is ready to go by executing the following command:

dotnet new console --output MongoExample

We’re going to be building a console application, but we’ll explore API development in a later tutorial. The “MongoExample” project is what we’ll use for the remainder of this tutorial.

Installing and Configuring the MongoDB Driver for .NET Core Development

When building C# applications, the common package manager to use is NuGet, something that is readily available in Visual Studio. If you’re using Visual Studio, you can add the following:

Install-Package MongoDB.Driver -Version 2.14.1

However, I’m on a Mac, use a variety of programming languages, and have chosen Visual Studio Code to be the IDE for me. There is no official NuGet extension for Visual Studio Code, but that doesn’t mean we’re stuck.

Execute the following from a CLI while within your project directory:

dotnet add package MongoDB.Driver

The above command will add an entry to your project’s “MongoExample.csproj” file and download the dependencies that we need. This is valuable whether you’re using Visual Studio Code or not.

If you generated the .NET Core project with the CLI like I did, you’ll have a “Program.cs” file to work with. Open it and add the following code:

using MongoDB.Driver;
using MongoDB.Bson;

MongoClient client = new MongoClient("ATLAS_URI_HERE");

List<string> databases = client.ListDatabaseNames().ToList();

foreach(string database in databases) {
    Console.WriteLine(database);
}

The above code will connect to a MongoDB Atlas cluster and then print out the names of the databases that the particular user has access to. The printing of databases is optional, but it could be a good way to make sure everything is working correctly.

If you’re wondering where to get your ATLAS_URI_HERE string, you can find it in your MongoDB Atlas dashboard and by clicking the connect button on your cluster.

MongoDB Atlas Connection String

The above image should help when looking for the Atlas URI.

Building a POCO Class for the MongoDB Document Model

When using .NET Core to work with MongoDB documents, you can make use of the BsonDocument class, but depending on what you’re trying to do, it could complicate your .NET Core application. Instead, I like to work with classes that are directly mapped to document fields. This allows me to use the class naturally in C#, but know that everything will work out on its own for MongoDB documents.

Create a “playlist.cs” file within your project and include the following C# code:

using MongoDB.Bson;

public class Playlist {

    public ObjectId _id { get; set; }
    public string username { get; set; } = null!;
    public List<string> items { get; set; } = null!;

    public Playlist(string username, List<string> movieIds) {
        this.username = username;
        this.items = movieIds;
    }

}

In the above Playlist class, we have three fields. If you want each of those fields to map perfectly to a field in a MongoDB document, you don’t have to do anything further. To be clear, the above class would map to a document that looks like the following:

{
    "_id": ObjectId("61d8bb5e2d5fe0c2b8a1007d"),
    "username": "nraboy",
    "items": [ "1234", "5678" ]
}

However, if you wanted your C# class field to be different than the field it should map to in a MongoDB document, you’d have to make a slight change. The Playlist class would look something like this:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Playlist {

    public ObjectId _id { get; set; }

    [BsonElement("username")]
    public string user { get; set; } = null!;

    public List<string> items { get; set; } = null!;

    public Playlist(string username, List<string> movieIds) {
        this.user = username;
        this.items = movieIds;
    }

}

Notice the new import and the use of BsonElement to map a remote document field to a local .NET Core class field.

There are a lot of other things you can do in terms of document mapping, but they are out of the scope of this particular tutorial. If you’re curious about other mapping techniques, check out the documentation on the subject.

Implementing Basic CRUD in .NET Core with MongoDB

Since we’re able to connect to Atlas from our .NET Core application and we have some understanding of what our data model will look like for the rest of the example, we can now work towards creating, reading, updating, and deleting (CRUD) documents.

We’ll start by creating some data. Within the project’s “Program.cs” file, make it look like the following:

using MongoDB.Driver;

MongoClient client = new MongoClient("ATLAS_URI_HERE");

var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");

List<string> movieList = new List<string>();
movieList.Add("1234");

playlistCollection.InsertOne(new Playlist("nraboy", movieList));

In the above example, we’re connecting to MongoDB Atlas, getting a reference to our “playlist” collection while noting that it is related to our Playlist class, and then making use of the InsertOne function on the collection.

If you ran the above code, you should see a new document in your collection with matching information.

So let’s read from that collection using our C# code:

// Previous code here ...

FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");

List<Playlist> results = playlistCollection.Find(filter).ToList();

foreach(Playlist result in results) {
    Console.WriteLine(string.Join(", ", result.items));
}

In the above code, we are creating a new FilterDefinition filter to determine which data we want returned from our Find operation. In particular, our filter will give us all documents that have “nraboy” as the username field, which may be more than one because we never specified if the field should be unique.

Using the filter, we can do a Find on the collection and convert it to a List of our Playlist class. If you don’t want to use a List, you can work with your data using a cursor. You can learn more about cursors in the documentation.

With a Find out of the way, let’s move onto updating our documents within MongoDB.

We’re going to add to our “Program.cs” file with the following code:

// Previous code here ...

FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");

// Previous code here ...

UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");

playlistCollection.UpdateOne(filter, update);

results = playlistCollection.Find(filter).ToList();

foreach(Playlist result in results) {
    Console.WriteLine(string.Join(", ", result.items));
}

In the above code, we are creating two definitions, one being the FilterDefinition that we had created in the previous step. We’re going to keep the same filter, but we’re adding a definition of what should be updated when there was a match based on the filter.

To clear things up, we’re going to match on all documents where “nraboy” is the username field. When matched, we want to add “5678” to the items array within our document. Using both definitions, we can use the UpdateOne method to make it happen.

There are more update operations than just the AddToSet function. It is worth checking out the documentation to see what you can accomplish.

This brings us to our final basic CRUD operation. We’re going to delete the document that we’ve been working with.

Within the “Program.cs” file, add the following C# code:

// Previous code here ...

FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");

// Previous code here ...

playlistCollection.DeleteOne(filter);

We’re going to make use of the same filter we’ve been using, but this time in the DeleteOne function. While we could have more than one document returned from our filter, the DeleteOne function will only delete the first one. You can make use of the DeleteMany function if you want to delete all of them.

Need to see it all together? Check this out:

using MongoDB.Driver;

MongoClient client = new MongoClient("ATLAS_URI_HERE");

var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");

List<string> movieList = new List<string>();
movieList.Add("1234");

playlistCollection.InsertOne(new Playlist("nraboy", movieList));

FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");

List<Playlist> results = playlistCollection.Find(filter).ToList();

foreach(Playlist result in results) {
    Console.WriteLine(string.Join(", ", result.items));
}

UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");

playlistCollection.UpdateOne(filter, update);

results = playlistCollection.Find(filter).ToList();

foreach(Playlist result in results) {
    Console.WriteLine(string.Join(", ", result.items));
}

playlistCollection.DeleteOne(filter);

The above code is everything that we did. If you swapped out the Atlas URI string with your own, it would create a document, read from it, update it, and then finally delete it.

Conclusion

You just saw how to quickly get up and running with MongoDB in your .NET Core application! While we only brushed upon the surface of what is possible in terms of MongoDB, it should put you on a better path for accomplishing your project needs.

If you’re looking for more help, check out the MongoDB Community Forums and get involved.

A video version of this tutorial can be found below.

Original article source at: https://www.thepolyglotdeveloper.com/

#mongodb #dotnet 

What is GEEK

Buddha Community

How to Build Your First .NET Core Application with MongoDB Atlas
Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

Query of MongoDB | MongoDB Command | MongoDB | Asp.Net Core Mvc

https://youtu.be/FwUobnB5pv8

#mongodb tutorial #mongodb tutorial for beginners #mongodb database #mongodb with c# #mongodb with asp.net core #mongodb

Install MongoDB Database | MongoDB | Asp.Net Core Mvc

#MongoDB
#Aspdotnetexplorer

https://youtu.be/cnwNWzcw3NM

#mongodb #mongodb database #mongodb with c# #mongodb with asp.net core #mongodb tutorial for beginners #mongodb tutorial

Asp.Net Core MVC Bangla Tutorials - 38 (Complete eCommerce Application)

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework