In this article, we are going to learn how to set up GraphQL in .NET Core application. We are going to use different third-party libraries to make this integration easier and will explain in detail how to use GraphQL elements (Type, Query, and Schema) to complete the integration process of GraphQL in .NET Core.

About GraphQL and How it’s Different from REST

GraphQl is a query language. It executes queries by using type systems which we define for our data. GraphQL isn’t tied to any specific language or a database, just the opposite, it is adaptable to our code and our data as well.

Let’s talk a bit about how GraphQL differs from REST:

  • GraphQL requires fewer roundtrips to the server and back to fetch all the required data for our view or template page. With REST, we have to visit several endpoints (api/subjectsapi/professorsapi/students …) to get all the data we need for our page, but that’s not the case with GraphQL. With GraphQL, we create only one query which calls several resolvers (functions) on the server side and returns all the data from different resources in a single request.
  • With REST, as our application grows, the number of endpoints grows as well, and that requires more and more time to maintain. But, with GraphQL we have only one endpoint api/graphql and that is all.
  • By using GraphQL, we never face a problem of getting too much or too few data in our response. That’s because we are defining our queries with the fields which states what we need in return. That way, we are always getting what we have requested. So, if we send a query like this one:

JavaScript

query OwnersQuery {
owners {
name account {
type
}
}
}

We are 100% sure that we will get this response back:JavaScript

{
“data”: {
“owners”: [{
“name”: “John Doe”,
“accounts”: [{
“type”: “Cash”
},
{
“type”: “Savings”
}]
}]
}
}

With REST this is not the case. Sometimes we get more than we need and sometimes less, it depends on how actions on a certain endpoint are implemented.

These are the most important differences between REST and GraphQL. In the next article we will create a project base on our article microservices

Anonymous Classes

An anonymous class is a class that does not have a name. This sound strange but sometimes an anonymous class can be useful, especially when using query expressions.

Let’s see what we mean by that.

We can create an object of anonymous class simply by using the new keyword in front of curly braces:

myAnonymousObj = new { Name = "John", Age = 32 };

This object contains two properties the Name and the Age. The compiler will implicitly assign the types to the properties based on the types of their values. So what this means basically is that the Name property will be of the string type and the Age property of the int type.

But now, we can ask, what type the myAnonymousObj is? And the answer is that we don’t know, which is the point of anonymous classes. But in C# this is not a problem, we can declare our object as an implicitly typed variable by using the var keyword:

var myAnonymousObj = new { Name = "nesto", Age = 32 };

The var keyword causes the compiler to create a variable of the same type as the expression that we use to initialize that object. So let’s see a couple of examples of well-known types:

var number = 15; // the number is of type int
var word = "example"; //the word is of type string
var money = 987.32; //the money is of type double

We can access the properties of our anonymous object the same way we did with regular objects:

Console.WriteLine($"The name of myAnonymousObject is {myAnonymousObj.Name}, the age is {myAnonymousObj.Age}");

Nullable Types

The null value is useful for initializing reference types. So, it is logical that we can’t assign the null value to the value type because the null is itself a reference.

That being said, we can see that the following statement will throw an error:

int number = null;

However, C# provides us with a modifier that we can use to declare a value type as a nullable value type. We can use the ? sign to indicate that value type is nullable:

int? number = null;

We can still assign an integer value to our nullable value type:C#

int? number = null;
int another = 200; 
number = 345;
number = another;

This is all valid. But if we try to assign the variable of an int type with a value of our nullable type, we are going to have a problem:

int? number = null;
int another = 200; 
another = number; //this is the problem

This makes sense if we consider that the variable number might contain the null but the variable another can’t contain null at all.

Properties of Nullable Types

The nullable types expose a few properties which can come in handy while working on our projects. The HasValueproperty indicates whether a nullable type contains a value or it is a null. The Value property enables us to retrieve the value of the nullable type if it is not a null:

int ? number = null;
 number = 234; //comment this line to print out the result from the else block 
 if (number.HasValue) {
     Console.WriteLine(number.Value);
 } else {
     Console.WriteLine("number is null");
 }


Data Types

Data types that represent the whole numbers are expressed with a certain number of bits. For unsigned numbers, the range is from 0 to 2N-1, and signed numbers range is from -2N-1 to 2N-1-1. So if the data type has a size of 8 bits like the sbyte data type, we can represent its range like this: from -27 to 27-1 => from -128 to 127.

The following table contains different data types that represent the whole numbers:

whole numbers table - C# Data Types

Letter u in front of the type means that type can’t contain negative numbers, it is unsigned.

The types mentioned above are the whole number types. But in C#, we have the number types with the floating point.

We can present them in a table as well:

Decimal numbers table in C# Data Types

In C#, we have two more basic data types:

Char-bool table C# Data Types

To use char type in our code we must place it inside the single quotes: ’a’ or ’A’ or ’3’…

One more type that is often introduced as the basic data type is the string type. But the string is not a value type it is a reference type. To use a string in our code we must place the value inside the double quotes: „This is the string type“ or „3452“…

So, we know we have the value types and reference types, and it is time to talk more about them and variables as well.

Variables in C#

Variable is a name of a memory location in which application stores values.

We should create our variables by following examples:

  • studentName
  • subject
  • work_day …

The wrong examples would be

  • student Name
  • work-day
  • 1place

We should mention that C# is a case-sensitive language so the studentName is not the same as the StudentName.

The C# language has its own set of reserved words, so-called keywords. We can’t use them as a name for our variables.

In C#, we have variables divided into two categories: Value type and Reference type. The difference is that the value type variables stores their values inside their own memory locations, but the memory location for the reference type variables contains only address to the dynamic memory location where the value is stored.

We should declare our variables in the following way:

<data type> <variable name> ;  or <data type> <variable name>, <variable name> ... ;

So a few examples would be:

class Program {
     static void Main(string[] args) {
         int age;
         double temperature,
         change;
         Student student;
     }
 }

Just with the declaration, we can’t assign a value to a value type variables. To do that, we need to use expressions in addition:

<data type> <variable name> = <expression> ;

Again, let’s look at this with an example:

class Program {
     static void Main(string[] args) {
         int x = 5;
         int y = 145 + x;
         char p = 'p';
         p = 'A';
     }
 }

To add a value for the reference type variable, we need to use the newkeyword in the expression part (string is an exception to this rule):

class Program {
     static void Main(string[] args) {
         Student student = new Student("John", 25);
     }
 }

We would like to mention that we don’t recommend to call variables with names „x“ or „y“… We have used that names just for the sake of simplicity. It is a better idea to give meaningful names to our variables.

In Visual Studio, there are at least 3 different types of class library you can create:

  • Class Library (.NET Framework)
  • Class Library (.NET Standard)
  • Class Library (.NET Core)

* Use a .NET Standard library when you want to increase the number of apps that will be compatible with your library, and you are okay with a decrease in the .NET API surface area your library can access.

* Use a .NET Core library when you want to increase the .NET API surface area your library can access, and you are okay with allowing only .NET Core apps to be compatible with your library.

Difference:

Compatibility: Libraries that target .NET Standard will run on any .NET Standard compliant runtime, such as .NET Core, .NET Framework, Mono/Xamarin. On the other hand, libraries that target .NET Core can only run on the .NET Core runtime.

API Surface Area: .NET Standard libraries come with everything in NETStandard.Library whereas .NET Core libraries come with everything in Microsoft.NETCore.App. The latter includes approximately 20 additional libraries, some of which we can add manually to our .NET Standard library (such as System.Threading.Thread) and some of which are not compatible with the .NET Standard (such as Microsoft.NETCore.CoreCLR).

As a quick resume, we can say that:

.Net Framework and .Net Core are two different implementations of the .Net runtime. Both Core and Framework (but especially Framework) have different profiles that include larger or smaller (or just plain different) selections of the many APIs and assemblies Microsoft has created for .Net, depending on where they are installed and in what profile. For example, there are some different APIs available in Universal Windows apps than in the “normal” Windows profile. Even on Windows, you might have the “Client” profile vs the “Full” profile. Additionally, there are other implementations (like Mono) that have their own sets of libraries.

.Net Standard is a specification for which sets of API libraries and assemblies must be available. An app written for .Net Standard 1.0 should be able to compile and run with any version of Framework, Core, Mono, etc, that advertises support for the .Net Standard 1.0 collection of libraries. Similar is true for .Net Standard 1.1, 1.5, 1.6, 2.0, etc. As long as the runtime provides support for the version of Standard targeted by your program, your program should run there.

A project targeted at a version of Standard will not be able to make use of features that are not included in that revision of the standard. This doesn’t mean you can’t take dependencies on other assemblies, or APIs published by other vendors (ie: items on NuGet). But it does mean that any dependencies you take must also include support for your version of .Net Standard. .Net Standard is evolving quickly, but it’s still new enough, and cares enough about some of the smaller runtime profiles, that this limitation can feel stifling. (Note a year and a half later: this is starting to change, and recent .Net Standard versions are much nicer and more full-featured).

On the other hand, an app targeted at Standard should be able to be used in more deployment situations, since in theory it can run with Core, Framework, Mono, etc. For a class library project looking for wide distribution, that’s an attractive promise. For a class library project used mainly for internal purposes, it may not be as much of a concern.

.Net Standard can also be useful in situations where the SysAdmin team is wanting to move from ASP.Net on Windows to ASP.Net for .Net Core on Linux for philosophical or cost reasons, but the Development team wants to continue working against .Net Framework in Visual Studio on Windows.

This is how Microsoft explains it:

.NET Framework is the “full” or “traditional” flavor of .NET that’s distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.

.NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.

Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices, usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.

Async & Await Simple Explanation

Simple Analogy

A person may wait for their morning train. This is all they are doing as this is their primary task that they are currently performing. (synchronous programming (what you normally do!))

Another person may await their morning train while he drink his coffee. (Asynchronous programming)

What is asynchronous programming?

Asynchronous programming is where a programmer will choose to run some of his code on a separate thread from the main thread of execution and then notify the main thread on it’s completion.

What does the async keyword actually do?

Prefixing the async keyword to a method name like

async void DoSomething(){ . . .

allows the programmer to use the await keyword when calling asynchronous tasks. That’s all it does.

Why is this important?

In a lot of software systems the main thread is reserved for operations specifically relating to the User Interface. If I am running a very complex recursive algorithm that takes 5 seconds to complete on my computer, but I am running this on the Main Thread (UI thread) When the user tries to click on anything on my application, it will appear to be frozen as my main thread has queued and is currently processing far too many operations. As a result the main thread cannot process the mouse click to run the method from the button click.

When do you use Async and Await?

Use the asynchronous keywords ideally when you are doing anything that doesn’t involve the user interface.

So lets say you’re writing a program that allows the user to sketch on their mobile phone but every 5 seconds it is going to be checking the weather on the internet.

We should be awaiting the call the polling calls every 5 seconds to the network to get the weather as the user of the application needs to keep interacting with the mobile touch screen to draw pretty pictures.

How do you use Async and Await

Following on from the example above, here is some pseudo code of how to write it:

     //ASYNCHRONOUS
    //this is called every 5 seconds
    async void CheckWeather()
    {
        var weather = await GetWeather();
        //do something with the weather now you have it
    }

    async Task<WeatherResult> GetWeather()
    {

        var weatherJson = await CallToNetworkAddressToGetWeather();
        return deserializeJson<weatherJson>(weatherJson);
    }

    //SYNCHRONOUS
    //This method is called whenever the screen is pressed
    void ScreenPressed()
    {
        DrawSketchOnScreen();
    }

On a higher level:

1) Async keyword enables the await and that’s all it does. Async keyword does not run the method in a separate thread. The beginning f async method runs synchronously until it hits await on a time-consuming task.

2) You can await on a method that returns Task or Task of type T. You cannot await on async void method.

3) The moment main thread encounters await on time-consuming task or when the actual work is started, the main thread returns to the caller of the current method.

4) If the main thread sees await on a task that is still executing, it doesn’t wait for it and returns to the caller of the current method. In this way, the application remains responsive.

5) Await on processing task, will now execute on a separate thread from the thread pool.

6) When this await task is completed, all the code below it will be executed by the separate thread

Further to the other answers, have a look at await (C# Reference) and more specifically at the example included, it explains your situation a bit

In the .NET Core series, we are going to go through a detailed example of how to use .NET Core, Angular and MySQL for Microservice web application development.

What are we going to do in this tutorial?

We are going to use MySQL as our database. First, we are going to install the MySQL server, we are going to use Entity Framework EF to automatic create all tables (we are going to use a MySQL Docker Image, but you can use a local MySQL if you prefer).

Then, we are going to step into the world of .NET Core Web API development. It is going to be our server-side part of the application. As we progress through the .NET Core series, we are going to use Repository pattern, SOLID principles. generics, LINQ, entity framework core, create more projects and services to demonstrate some good practices. Overall we will try to write the application as we would in the real-time environment. Furthermore, you will learn about .NET Core architecture and code organization, so you can make it more readable and maintainable.

There are three approaches to using Entity Framework: Database First, Code First and Model First. In this tutorial, we are going to use the Code First approach, reate a model and their relation using classes and then create the database from these classes. It enables us to work with the Entity Framework in an object-oriented manner. Here we need not worry about the database structure.

After we finish the .NET Core series, we are going to introduce two of the most popular client frameworks (Angular and React) to consume our Web API, and at last we are going to create a Xamarin App and deploy it to Android. This will result in creating a full-stack web application.

In the end, we are going to publish our app on Docker, and finish strong by completing the entire development cycle.

You can use Visual Studio or Visual Code for this tutorial, our sample will be created using Visual Code.