Create a Restful API with ASP.NET Core and MongoDB

In this article, I will create a web API with ASP.NET Core that performs CRUD (Create, Read, Update, and Delete) operations on a MongoDB NoSQL database.

First, I will start with configuring MongoDB to perform CRUD operations from a web API.

By default, MongoDB is installed at C:\Program Files\MongoDB\Server\4.0\bin.

To access MongoDB Shell, you must add C:\Program Files\MongoDB\Server\4.0\bin to the Path environment variable.

To create a database, use MongoDB Compass Community or MongoDB Shell

For more information about MongoDB Shell commands, you can look at https://docs.mongodb.com/manual/mongo/#working-with-the-mongo-shell

For MongoDB Shell, choose a directory such as C:\Users\casan\Desktop\Files\mongodb.

I created a new folder named mongodb at C:\Users\casan\Desktop\Files on my development machine.

Open a command line, run the following command to connect to MongoDB on default port 27017.

mongod --dbpath <data_directory_path>

Open another command prompt and run the following command to connect to the default test database.

mongo

Run the following command. If testDb database doesn’t exist, it is created.

use testDb

Create a Employees collection by running the following command

db.createCollection('Employees')

Run the following command to insert three documents.

db.Employees.insertMany([{'Name':'Cihan','Salary':10000.00,'Company':'ABC'}, {'Name':'Mike','Salary':7000.00,'Company':'XYZ'}, {'Name':'John','Salary':7500.00,'Company':'DEF'}])

View the documents.

db.Employees.find({}).pretty()

That’s it for the database side

Now, let’s create the ASP.NET Core web API project.

Open Visual Studio 2017 Community

Go to File > New > Project

Select the ASP.NET Core Web Application option.

Select the .NET Core framework and ASP.NET Core 2.1.

Select the API project template. Then click OK.

In Solution Explorer, Right click the Dependencies section and select the Manage NuGet Packages.. option to install .NET Driver for MongoDB.

Install MongoDB.Driver

To add a model, create a folder named Models to the project root as you see below.

Then add a class named Employee.cs with the following code to the Models folder.

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

namespace WebApplication1.Models
{
    public class Employee
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("Name")]
        public string Name { get; set; }

        [BsonElement("Salary")]
        public decimal Salary { get; set; }

        [BsonElement("Company")]
        public string Company { get; set; }

    }
}

[BsonElement] attribute is used to represent the property name in the MongoDB collection

[BsonId] is used to assign the Id property as the primary key.

[BsonRepresentation(BsonType.ObjectId)] is used to pass the parameter as the string type instead of ObjectId.
Mongo handles the conversion.

These are all required to map the Common Language Runtime object to the MongoDB collection.

For CRUD operations, create a folder named Services to the project root and add a class named EmployeeService.cs with the following code to the Services folder that is created.

using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;

namespace WebApplication1.Services
{
    public class EmployeeService
    {
        private readonly IMongoCollection _employees;

        public EmployeeService(IConfiguration config)
        {
            var client = new MongoClient(config.GetConnectionString("testDb"));
            var database = client.GetDatabase("testDb");
            _employees = database.GetCollection("Employees");
        }

        public List Get()
        {
            return _employees.Find(employee => true).ToList();
        }

        public Employee Get(string id)
        {
            return _employees.Find(employee => employee.Id == id).FirstOrDefault();
        }

        public Employee Create(Employee employee)
        {
            _employees.InsertOne(employee);
            return employee;
        }

        public void Update(string id, Employee employeeParam)
        {
            _employees.ReplaceOne(employee => employee.Id == id, employeeParam);
        }

        public void Delete(Employee employeeParam)
        {
            _employees.DeleteOne(employee => employee.Id == employeeParam.Id);
        }

        public void Delete(string id)
        {
            _employees.DeleteOne(employee => employee.Id == id);
        }
    }
}

Add the MongoDB connection string to the appsettings.json file.

{
  "ConnectionStrings": {
    "testDb": "mongodb://localhost:27017"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Register the EmployeeService class with the Dependency Injection system to the ConfigureServices method in the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

IMongoDatabase represents the Mongo database. The generic GetCollection(collection) method is used to gain access to data for a specific collection.

GetCollection(Employee) returns a MongoCollection object to represent the collection

Add a controller class named EmployeesController with the following code to the Controller folder.

using System.Collections.Generic;
using WebApplication1.Models;
using WebApplication1.Services;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : Controller
    {
        private readonly EmployeeService _employeeService;

        public EmployeesController(EmployeeService employeeService)
        {
            _employeeService = employeeService;
        }

        [HttpGet]
        public ActionResult<List> Get()
        {
            return _employeeService.Get();
        }

        [HttpGet("{id:length(24)}", Name = "GetEmployee")]
        public ActionResult Get(string id)
        {
            var employee = _employeeService.Get(id);

            if (employee == null)
            {
                return NotFound();
            }

            return employee;
        }

        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            _employeeService.Create(employee);

            return CreatedAtRoute("GetEmployee", new { id = employee.Id.ToString() }, employee);
        }

        [HttpPut("{id:length(24)}")]
        public IActionResult Update(string id, Employee employeeParam)
        {
            var employee = _employeeService.Get(id);

            if (employee == null)
            {
                return NotFound();
            }

            _employeeService.Update(id, employeeParam);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            var employee = _employeeService.Get(id);

            if (employee == null)
            {
                return NotFound();
            }

            _employeeService.Delete(employee.Id);

            return NoContent();
        }
    }
}

Build and start the app.

Navigate to http://localhost:/api/employees in your browser.

This tutorial also uses Postman to test the web API.

Open Postman and set the Http method to POST.

Set the request URL to http://localhost:<port>/api/employees.

Select the Body tab.

Select the raw radio button.

Set the type to JSON (application/json).

In the request body, enter the following JSON data to register an employee.

{"Name":"Robert","Salary":8000.00,"Company":"UPS"}

Select Send.

In the response headers, copy the value of the location

Select the Headers tab in the Response pane.

Copy the Location header value.

Paste the URI to your browser.

Advertisements

Angular 7 Example

I start this tutorial by installing Angular using Angular CLI

I assume you have installed an Angular CLI

If it’s not in your machine, run the following command.

npm install -g @angular/cli

And then create a boilerplate project by running the following command.

ng new testAngular

go into the project folder

cd testAngular

open the project in your editor. I’m using Visual Studio Code.

code .

Start the project by running the following command.

ng serve --open

Install Bootstrap in your app. Go to your root. Run the following code.

npm add bootstrap

Copy the bootstrap.min.css file from \node_modules\bootstrap\dist\css to \src\assets\css folder.

If the CSS is not there, then create a folder named “css”.

Add the link of that CSS file inside src > index.html as you can see.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TestAngular</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <app-root></app-root>
</body>
</html>

Create two components named “home” and “employees” by running the following command

ng g c home
ng g c employees

Angular automatically update the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    EmployeesComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Modify the app-routing.module.ts file as follows

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'employees', component: EmployeesComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

As you can see, I have the Routes, RouterModule module. I have populated the routes array.

Exporting RouterModule provides router directives.

<router-outlet></router-outlet>

router-outlet is a component that is used to load the different components dynamically based on the activated component. It is inside the app.component.html file.

I define a navbar to display the output of the different routes. Inside the app.component.html file, add the following code.

< div id="app">
  < nav class="navbar navbar-expand-sm bg-light">
      < ul class="navbar-nav">
      < li class="nav-item">
          < a routerLink="/home" class="nav-link">Home</a>
      < /li>
      < li class="nav-item">
          < a routerLink="/employees" class="nav-link">Employees</a>
      < /li>
      < /ul>
  < /nav>
  < div class="container">
      < router-outlet></router-outlet>
  < /div>
< /div>

I will prepare the fake data using a package called json-server. Run the following commandto install the json-server package.

npm install -g json-server

I will create a folder named “data” inside the src directory and create a file named db.json inside that.

{
    "results": [
    {
        "id": "1",
        "name": "Cihan",
        "company": "ABC"
    },
    {
        "id": "2",
        "name": "John",
        "company": "DEF"
    },
    {
        "id": "3",
        "name": "Robert",
        "company": "XYZ"
    }]
}

That’s OK. Start the JSON Server by running the following command.

json-server --watch src/data/db.json --port 3000

http://localhost:3000/results

Angular has HttpClientModule module. Let us configure inside the app.module.ts file.

import { HttpClientModule } from '@angular/common/http';
imports: [
  BrowserModule,
  AppRoutingModule,
  HttpClientModule
]

Create a file named Employee.ts inside the employees folder. Type the following code in that.

export interface Employee {
  id: Number;
  name: String;
  company: String;
}

Create a file named employee.service.ts inside the employees folder. In that file, I’m writing the network request code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class EmployeeService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:3000';
  getEmployees() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

Then I import this file inside the employees.component.ts file. Then I call the service as follows.

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';
import { Employee } from './employee';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {

  employees: Employee[];
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeService.getEmployees().subscribe((data: Employee[])=>{
      this.employees = data;
    });
  }

}

Display that data inside the employees.component.html file.

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Company</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let employee of employees">
      <td>{{ employee.id }}</td>
      <td>{{ employee.name }}</td>
      <td>{{ employee.company }}</td>
    </tr>
  </tbody>
</table>

Finally I will declare the EmployeeService service as a provider inside the app.module.ts file.

import { EmployeeService } from './employees/employee.service';
providers: [EmployeeService]

NativeScript – Lesson 1

You can create Native IOS and Android Apps with Javascript.

Native Script is a open source framework for building native mobile apps with Angular, Vue.js, TypeScript, or Javascript.

Get Started

Click https://www.nativescript.org

Click the “Start coding today” option on the web site clicked

NativeScript

You must choose one of them. I’m going to use the Angular framework.

 

You have to see the screen as shown below.

NativeScript-Playground

 

Click the “Preview” button.

 

NativeScript-Playground-1

 

You must download two apps NativeScript Playground and NativeScript Preview on your device.

 

On your device, you will see an application like the below image after scanning the QR code.

 

NativeScript-Playground-2

C# SqlCommand Example



private string connectionString = WebConfigurationManager.AppSettings["connectionString"];

public rmtoken ReadTokenFromDB(string eftkodu, string scope, int wsauthority)
{
    try
    {
        rmtoken rmtoken = new rmtoken();
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select access_token, expires_in, refresh_token, tokendate from rmtoken where eftkodu='" + eftkodu
                + "' and scope='" + scope + "' and wsauthority=" + wsauthority.ToString(), con);
            SqlDataReader dataReader = cmd.ExecuteReader();
            if (dataReader.Read())
            {
                rmtoken.access_token = dataReader["access_token"].ToString();
                rmtoken.expires_in = Convert.ToInt32(dataReader["expires_in"]);
                rmtoken.refresh_token = dataReader["refresh_token"].ToString();
                rmtoken.tokendate = Convert.ToDateTime(dataReader["tokendate"]);
            }
            cmd.Dispose();
            con.Close();
        }
        return rmtoken;
    }
    catch
    {
        //log
        return null;
    }
}



C# POST Method using WebRequest

I will show you how to make a POST request using WebRequest and to create a token.


        public TokenOlusturmaCikti TokenOlusturma(TokenOlusturmaGirdi girdi)
        {
            TokenOlusturmaCikti cikti = null;
            WebRequest req = WebRequest.Create(TokenServisi);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            string parameters = "";
            parameters += "state=" + girdi.state;
            parameters += "&grant_type=" + girdi.grant_type;
            parameters += "&scope=" + girdi.scope;
            parameters += "&username=" + girdi.username;
            parameters += "&password=" + girdi.password;
            parameters += "&client_id=" + girdi.client_id;
            parameters += "&client_secret=" + girdi.client_secret;
            byte[] bytes = Encoding.UTF8.GetBytes(parameters);

            req.ContentLength = bytes.Length;

            Stream stream = req.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            WebResponse res = req.GetResponse();
            if (res == null) return null;

            StreamReader sr = new StreamReader(res.GetResponseStream());
            string json = sr.ReadToEnd();

            cikti = JsonConvert.DeserializeObject(json);
            return cikti;
        }

1

Angular Example

Create a new folder

> mkdir angular6

> cd angular6

1

> ng new myproject

2

> cd myproject

Open the project in your editor. I am using VSCode.

> code .

Start the development server.

> ng serve –open

Create a new component.

> ng g c home

Create an another component.

> ng g c employees

3

app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';

import {RouterModule, Routes} from '@angular/router';
const routes: Routes = [
  { path: 'employees', component: EmployeesComponent },
  { path: 'home', component: HomeComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    EmployeesComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html


<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center;">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</ div>
<h2>Here are some links to help you start: </h2>
<ul>
  
  <li>
    <h2><a>Home</a></h2>
  </li>
  <li>
    <h2><a>Employees</a></h2>
  </li>
</ul>



4

PowerBuilder – compute MD5 value for a file

OLEObject obj_md5, obj_stream, obj_dom, obj_element
integer li_rc, li_temp

If IsNull( as_filepath ) Then
	as_hata = "Dosya Yolu null değer dönmüştür!"
	Return -1
End If

li_temp = 1 //Initial Value

obj_md5 = CREATE OLEObject
li_rc = obj_md5.ConnectToNewObject("System.Security.Cryptography.MD5CryptoServiceProvider")
If li_rc = 0 Then//Success
	obj_stream = CREATE OLEObject
	li_rc = obj_stream.ConnectToNewObject("ADODB.Stream")	
	Choose Case li_rc		
		Case 0
			obj_stream.Open
			obj_stream.Type = 1
			obj_stream.LoadFromFile(as_filepath)
			
			obj_md5.ComputeHash_2(obj_stream.Read)
			
			obj_dom = CREATE OLEObject
			li_rc = obj_dom.ConnectToNewObject("Msxml2.DOMDocument.6.0")	
			If li_rc = 0 Then
				obj_element = obj_dom.CreateElement("tmp")//Gecici Element Olusturma	
				obj_element.DataType = "bin.hex"//Cevirme	 
				obj_element.NodeTypedValue = obj_md5.Hash
				
				as_md5 = obj_element.Text//Cevirilmis MD5 Degeri Alma		
			Else
				li_temp = -1
				as_hata = "Msxml2.DOMDocument.6.0 hata almıştır! li_rc : " + string(li_rc)				
			End If
			
			obj_stream.Close
		Case Else
			li_temp = -1
			as_hata = "ADODB.Stream hata almıştır! li_rc : " + string(li_rc)		
	End Choose	
Else	
	li_temp = -1
	as_hata = "MD5CryptoServiceProvider hata almıştır! li_rc : " + string(li_rc)	
End If

DESTROY obj_dom
DESTROY obj_stream
DESTROY obj_md5
Return li_temp