Posted on

Querying MongoDB using .NET Core

Querying MongoDB using .NET Core

Querying MongoDB using .NET Core

Querying MongoDB using .NET Core

Intro

The following article shows how to querying MongoDB using .NET Core.

MongoDB has recently released  the .NET Core support inside the C# driver (Net Core Support Driver). In fact, 2.3.0 version of C# Drivers has already been released to Nuget.

Querying MongoDB using .NET Core

The demo code is available on GitHub.

Setup the demo database

Firstly, you need to install MongoDB on your OS. Before continue, make sure that MongoDB is running correctly using:

mongod
mongo

Next, execute the following dump which creates the demo database:

mongo demoDB dump.js

Setup .NET Core project

I have previously discussed about .NET Core in the following articles:

Introducing ASP.NET 5 on Ubuntu

Future of ASP.NET is open source and cross platform

.NET Core and MVC: Customize view paths

There are different ways to use .NET Core on your OS, the following example uses the Yeoman aspnet-generator to scaffold a Web API template. It creates the following folder structure:
Samueles-MacBook-Pro:Blog.DotNetCoreMongoDb samueleresca$ tree
.
├── Controllers
│   └── ValuesController.cs
├── Dockerfile
├── Models
│   └── PostModel.cs
├── Program.cs
├── Properties
│   └── launchSettings.json
├── README.md
├── Startup.cs
├── appsettings.json
├── project.json
├── project.lock.json
├── web.config
└── wwwroot

project.json

project.json specifies the packages used by the project. Add the MongoDb drivers and launch the dotnet restore command inside the project folder to restore packages:

Defining model

You need to define a model which reflects the structure of your MongoDB collection, add the PostModel.cs file inside the Model folder:

Defining repository

PostsRepository is the core part of the project: it uses the MongoDB drivers to implement the CRUD operations on the Posts collection. Add the PostsRepository.cs file inside the Repository folder:

Defining controller

The PostsController handles the incoming HTTP requests and invokes the PostsRepository to return the query result:

Conclusion

You can run the webserver using the dotnet run command, and call Action methods  using a generic Web API client:

GET http://localhost:5000/api/posts
POST http://localhost:5000/api/posts?title="Title1"&content="Content1"&name="Test"

The code of this article is available on GitHub, at the following link.

 

Cheers 🙂

Posted on

Developing artificial intelligence using .NET

Developing AI using .Net

Developing artificial intelligence using .NET

Developing artificial intelligence using .Net
Microsoft has recently released two important AI services:

  • Microsoft Cognitive Services  are APIs which lets you tap into an ever-growing collection of powerful AI algorithms developed by experts in the fields of computer vision, speech, natural language processing, knowledge extraction and web search;
  • Bot framework is a very useful framework to build and connect intelligent bots to interact with your users naturally wherever they are, from Telegram to Skype, Slack, Facebook and other popular services;

This article discovers this services and shows how developing artificial intelligence using .NET.

Demo

The demo shows how to build a Bot that can automatically caption photos sent by users.

Requirements

  • Visual studio 2015 community edition , download here;
  • Bot conversation emulator, click here to download;
  • Microsoft cognitive services subscription, sign in here;
  • Visual studio Bot Framework .NET template, which can be downloaded here. To install, save the zip file to your Visual Studio 2015 templates directory which is traditionally in "%USERPROFILE%\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#\";

Setup the bot project

Create a new C# project using the new Bot Application template:

Developing artificial intelligence using .NET

Visual studio generates a new controller, by default, called MessageController, which is the main entry point of your bot:

Setup the bot emulator

The emulator gives the possibility to test your bots locally. You can download the emulator here.

Developing AI using .Net

The emulator requires 3 params:

  • The Url for your bot set the localhost:<port> pulled from the last step. You will need to add the path “/api/messages” to your URL when using the Bot Application template;
  • MicrosoftAppId field is NOT required to test bots locally;
  • MicrosoftAppPassword field is NOT required to test bots locally;

Important: you need to run your bot project in Visual Studio, to use the bot emulator.

Setup images recognition (Microsoft cognitive services: Vision)

Microsoft Cognitive Services APIs offer the possibility to implement AI inside our applications. There are different services:  Speech, Language, Knowledge, Vision and Search. This demo uses the Vision service to caption photos sent by users.

Class schema

Developing artificial intelligence using .Net

Code

Firstly, add the IVisionConnector.cs interface and VisionConnector.cs class to your project:

The IVisionConnector interface is referenced by MessagesController and describes main methods which are used by VisionConnector. API Token is required by VisionServiceClient to consume APIs. You can get the APIs token here.

VisionConnector implements methods to communicate with Microsoft Cognitive API.

Next, go to MessagesController.cs class file and replace the following code:

MessageController class watches  all incoming images and returns the detected caption.

All together now!

Finally, run your Visual studio project and set the bot URL on Bot emulator:

Developing artificial intelligence using .NET

Final thoughts

It’s very easy developing artificial intelligence using .NET, Microsoft Cognitive Services  and Bot framework .

They let you build cross-platform apps with powerful algorithms using just a few lines of code.

Bot framework  is compatibile with the most famous chats: Facebook, Telegram, Skype and Whatsapp.

The example is available on GitHub.

Cheers 🙂

 

Posted on

SOLID principles using Typescript

SOLID principles using Typescript

SOLID principles using Typescript

SOLID principles using Typescript

SOLID principles using Typescript

The following article explains SOLID principles using Typescript.

Here are more articles about Typescript:

Introducing Typescript

Introducing Typescript: Language features

SOLID is an acronym for the first five object-oriented design(OOD) principles by Robert C. Martin, popularly known as @UncleBob.

The five SOLID principles are:

  • Single responsibility principle: a class should have one, and only one, reason to change;
  • Open-closed principle: it should be possible to extend the behavoir of a class without  modifying it;
  • Liskov Substitution principle: subclasses should be substitutable for their superclasses;
  • Interface segregation principle: many small, client-specific interfaces are better than one general purpose interface;
  • Dependency inversion principle: depends on abstractions not concretions;

These principles, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.

The Single Responsibility Principle (SRP)

The SRP requires that a class should have only one reason to change. A class that follows this principle performs just few related tasks. You don’t need to limit your thinking to classes when considering the SRP. You can apply the principle to methods or modules, ensuring that they do just one thing and therefore have just one reason to change.

 

Example – wrong way

The class Task defines properties related to the model, but it also defines the data access method to save the entity on a generic data source:

UML

 

SOLID principles using Typescript - SRP wrong way

Code

Example – right way

The  Task class can be divided between Task class, that takes care of model description and TaskRepository that is responsabile for storing the data.

UML

 

SOLID principles using Typescript - SRP right way

Code

 

The Open-closed Princple (OCP)

 Software entities should be open for extension but closed for modification.

The risk of changing an existing class is that you will introduce  an inadvertent change in behaviour. The solution is create another class that overrides the behaviour of  the original class. By following the OCP, a component is more likely to contain maintainable and re-usable code.

Example – right way

The CreditCard class describes a method to calculate the monthlyDiscount(). The monthlyDiscount() depends on the type of Card, which can be : Silver or Gold. To change the monthly discount calc, you should create another class which overrides the monthlyDiscount() Method.

The solution is to create two new classes: one for each type of card.

UML

SOLID principles using Typescript - OCP Right

Code

The Liskov Substitution Principle (LSP)

Child classes should never break the parent class’ type definitions.

The concept of this principle was introduced by Barbara Liskov in a 1987 conference keynote and later published in a paper together with Jannette Wing in 1994.

As simple as that, a subclass should override the parent class methods in a way that does not break functionality from a client’s point of view.

Example

In the following example ItalyPostalAddress, UKPostalAddress and USAPostalAddress extend one common class: PostalAddress.

The AddressWriter class refers PostalAddress: the writer parameter can be of three different sub-types.

UML

SOLID principles using Typescript - LSP Right

Code

The Interface Segregation Principle (ISP)

It is quite common to find that an interface is in essence just a description of an entire class. The ISP states that we should write a series of smaller and more specific interfaces that are implemented by the class. Each interface provides an single behavior.

 

Example – wrong way

The following Printer interface makes it impossible to implement a printer that can print and copy, but not staple:

Example – right way

The following example shows an alternative approach that groups methods into more specific interfaces. It describe a number of contracts that could be implemented individually by a simple printer or simple copier or by a super printer:

The Dependency inversion principle (DIP)

The DIP simply states that high-level classes shouldn’t depend on  low-level components, but instead depend on an abstraction.

Example – wrong way

The high-level WindowSwitch depends on the lower-level CarWindow class:

UML

SOLID principles using Typescript - DIP wrong way

Code

Example – right way

To follow the DIP, the class WindowSwitch should references an interface (IWindow) that is implemented by the object CarWindow:

UML
SOLID principles using Typescript - DIP right way

Code

Final thoughts

Typescript make it possible to bring all of the principles and practices of OOP into your software, using SOLID principles to guide your design patterns.

Here’s the GitHub repository containing the full examples.