3 Games to Have Fun and Help Science .. Be a Citizen Scientist today

It all started in December 2019 .. When WHO was informed of unknown cases in Wuhan City, China. Since then, the world has experienced one of the biggest and longest pandemics. However, the big difference is that this time, science had advanced a lot in the recent decades, and that gave us the biggest tool to fight back with this tiny COVID-19 virus.

A lot of scientists around the world gathered together to fight back! Quickly, multiple studies were conducted across the world, and that led to various solutions and vaccines. All this highlighted the importance of science more than ever. Everybody wants more of science. Everybody wants better answers and faster results.

On the other hand, there are problems in the world that are not easy to solve. Finding a good and fast solution to them requires studying a lot of different things altogether. And that takes time, money, and resources. One of the interesting initiatives is citizen scientists. Citizen science helps crowd-source studies and enables scientists with a lot of data they can work on. If you want to know more, I explained all about it (with examples) in this blog post.

From time to time, When I get bored and want to play games on my mobile phone. One day, I was wondering that it would be good to download some of those citizen scientists games. This way, whenever I wanted to free up my mind and play some game, I can play those and who knows, maybe I can contribute to something!

In this post, I’m going to share with you, 3 of the citizen scientists games I liked and installed on my phone to play from time to time.

1. Nemo-Net

We mapped more of the surface of the Moon and the Mars, than we have our own ocean!

Dr. Earle, Oceanographer

Sometime along the way, we humans got so excited about outer space, that we forgot our ecosystem. Therefore we know little about coral reefs and oceans. NASA created this game so that players can help classify coral reefs. The data from this game is fed to Pleiades Supercomputer to help build a neural network that can assess the health of coral reefs around the world.

You simply need to paint coral reefs with colour in a 3D scan of the ocean. It’s available for iOS, Android, and Windows.

2. Cancer Crusade

Cancer Crusade is the name of a game developed by Moffitt Cancer Center in the USA. The player plays the role of a doctor who is treating different virtual patients. There are some treatments available, and you can combine and apply them in a way to cure the Tumor. It’s quite a fun and engaging game. The results are sent back to Moffitt Cancer Center and analyzed for new and improved treatments. It’s available for iOS on App Store. Android version can be downloaded from their website.

3. ROCKS & RUNES

This game has been designed in the form of an animal that likes to collect shiny runestones. These runes are divided by some rocks. The player should destroy these rocks in order to combine runestones and release their magic power. In reality, the player is turning off inactive properties of compounds in order to boost the overall effectiveness. The data gives new opportunities to scientists to fight cancer. It’s available for iOS, Android, Mac, and Windows.

Last word…

I believe the idea of citizen science and the apps and games built based on it, needs much more attention in today’s world. We know how much science can protect our lifestyle and can give us the freedom we want to grow and roam.

Have you participated in any CitSci project? let me know what you think about these games or any other project you know about.

PS: I am NOT affiliated with any of the projects above, I wrote this simply because I find this idea interesting and worth talking about.

What is GraphQL? How to Use it in ASP.NET Core WebApi? Let Me Explain Simply…

From ASP.NET Web Forms to ASP.NET AJAX, then ASP.NET MVC and ASP.NET Web API, building an API has evolved massively. An API started from being a function you can run on another computer, evolved massively to accommodate what today’s applications need.

Throughout the projects I have been involved in, I have always worked with REST APIs. REST API architecture is simple and clean, it’s easy to pick up for new developers and it is less mistake-prone since each and every API is going to have the same structure.

In a typical REST API, you would have a separate endpoint for each object type. That endpoint, based on your implementation, would provide GET, POST, PUT, PATCH, DELETE actions. In addition to that, they could get some query parameters, to filter the data (for example based on an ID or date, etc.). But when you would get the result, you would get the whole object. And that can be a bigger headache when you are using Domain-Driven Design architecture and dealing with millions/billions of aggregate objects.

Entering GraphQL…

GraphQL is a query language for APIs. GraphQL gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

graphql.org

In 2012, Facebook built GraphQL to address the above issue. GraphQL, typically has one endpoint. And, that endpoint accepts a query. So far, it is not that fascinating, but the actual beauty is in the “query” I just mentioned. In the query, you mention what type (or types) you want, what property values you’d want to use as filter, and lastly, what properties of those types you’d like to get back.

How does GraphQL work?

As you guessed, you can request for one or more types, you can search/filter based on any property and you can get only the properties you are interested in. The query is in JSON format and you’d get the result back in JSON format. This can save you multiple roundtrips to the server and decrease your server load as well as network traffic and latency.

I know you are excited to see an example of a query .. so let me show you:

Query

query PersonAndFriends {
   person (id: 2001) {
      name
      friends {
         name
      }
   }
}

Result

{
   "data": {
   "person": {
       "name": "Rose DeWitt",
       "friends": [
       {
          "name": "Jack Dawson"
       },
       {
          "name": "Cal Hockley"
       },
       {
          "name": "Ruth DeWitt"
       }
     ]
    }
  }
}

Above, I defined a query with the name “PersonAndFriends”, I’m asking for a person with ID=2001, and I am interested to get back its name and friends fields. Within friends (which can be an array), I’m asking to only get back name field. On top of that, the shape of a GraphQL query closely matches the result of it. It’s cool, isn’t it?

There are 3 types of query. “query” itself, “mutation” and “subscription“. query is your way to request for data, mutate is the way to change the data (such as create a new record, update it, delete it).

Queries accept variables, so that you don’t need to manipulate string to put your arguments dynamically.

Query with variables

query PersonQuery($id: ID!) {
  person(id: $id) {
    name
  }
}
{
  "id": 2001
}

Result

{
  "data": {
    "person": {
      "name": "Rose DeWitt",
    }
  }
}

Internally, The query and each field of types is backed by a separate function called resolver which is provided by the developer to GraphQL. Execution of a query starts by calling the resolver function of the query with passed-in arguments. If the function returns an object, GraphQL will execute its resolver passing in the object. For each selected field, GraphQL calls their resolver functions to get their values. This process continues until all resolvers return Scalar types and not objects. It is as if GraphQL traverses a graph from its root until it covers all the leaves, hence the name Graph Query Language.

How to use GraphQL?

In order to use GraphQL, two things should be provided to build a GraphQL server. Firstly, object types, what data can be queried, and how it can be queried. Defining types and schemas, help GraphQL to validate queries and execute them. Secondly, resolver functions for each type and its fields.

Defining types

type Query {
  actor(episode: Episode): Cast
  car(id: ID!): Vehicle
}

type Cast {
  id: ID!
  name: String!
  episode: [Episode!]!
  height(unit: LengthUnit = METER): Float
}

enum Episode {
  PILOT
  ONE
  FINALE
}

“!” comes after the field type and shows that field is non-nullable and when you query that field, it will always have a value. [ and ] represent an array. Fields can have arguments, and arguments can have default values(e.g. height field). Built-In scalar types can be Int (32-bit integer), Float, String, Boolean and ID (which is non-human-readable and unique string).

The query structure is actually another type named “Query”. It defines, what fields can be queried, and what arguments each field can take. Also, it defined what fields and arguments are non-nullable. Mutation is also defined in the same way.

GraphQL allows you to define input object types which are objects that you can pass as an argument to a query or mutation. Input types need to be defined separately with input keyword. Input types can have relationship with other input types but cannot refer object types or have arguments.

input FoodReviewInput {
  stars: Int!
  comment: String
}

Defining resolver functions

It’s quite straight-forward, you start with a function to resolve the query:

Query: {
  actor(obj, args, context, info) {
    return context.db.getActorByID(args.id).then(
      response => new Actor(response)
    )
  }
}

Each function has four arguments, obj is the object resulted from running the previous function, args is field or query arguments, context is a contextual object containing information like the logged-in user and etcetera, info contains information about the query and its types.

Just like that, you define the rest of the functions for types and fields:

Actor: {
  name(obj, args, context, info) {
    return obj.name
  }
Vehicle(obj, args, context, info) {
    return obj.vehicleIDs.map(
      id => context.db.getVehicleByID(id).then(
        response => new Vehicle(response)
      )
    )
  } 
}

But That seems to be a lot of work!

Yes, but the good news is, there are many libraries available that would take the complexity away from you. They take care of object definition, authorization, security, pagination, caching, etc. GraphQL website provides you with a list of libraries and tools you can use in your preferred programming language here.

How to use GraphQL in .NET Core?

I found hotchocolate library which does most of the work and creates a neat GraphQL server in no time. I found its tutorial quite succinct and to-the-point, you can find it here

Architect discussion: When to use GraphQL?

Like any other technology, GraphQL has its own pros and cons. When you want to make an architectural decision, you need to be aware of these pros and cons and make sure that this technology can do what you want to achieve. I found these points about GraphQL versus REST Api:

What you get:

  • Ask for what you need: As you know by now, in GraphQL you mention the fields you want to be returned to you, and that is one of the main benefits of using GraphQL. Especially if you are dealing with large aggregate objects and you need to transfer data over public internet (which incurs cost), This is very beneficial. Although REST API doesn’t have this feature by itself, it is technically possible to use OData to query REST API. However, in my opinion, GraphQL is more like a standard for this and it’s better to rely on a standard than a combination of technologies.
  • Solves n+1 problem: Imagine a situation where you get a root object (like a Person) and then loop through its Friends collection and send another request to fetch each Friend object separately. GraphQL solves this problem, since you can mention whatever you want in your query.
  • Combined Query: Combined queries are when you request for separate not-related objects in the same query. For example, you can write a query that returns persons and books. Normally you would have to make two separate API calls, but with GraphQL you can do it in one query.
  • API Versioning: GraphQL query and its result is in JSON format. Therefore, if there is any changes in the schema, JSON inherently handles that for you. And every subsequent systems that use your GraphQL endpoint, since they use JSON, it’s safe for them as well. Obviously, if you delete/rename a field, that’s still a breaking change.

What to watch out:

  • Caching: REST API is heavily based on how HTTP works, and HTTP has a nice caching mechanism. However, GraphQL needs a bit of more work to implement its own caching.
  • Harder with Microservice Architecture: When you have separate micro-services for different aggregates, in REST API, you can call separate URLs and get both objects. But in GraphQL, since you only deal with one endpoint, GraphQL needs to call those endpoints separately behind-the-scene, aggregate the data and send it back to you. Which can be not-ideal in some solutions.
  • Combined Query: Combined query is one of the great features, however, if you are not careful, it can expose some data to the users that should not have access to that part of the data.
  • Monitoring: Since REST API is based on HTTP protocol, there are many layers of monitoring already built around that. You can monitor and log your REST API calls inside and out. However, the monitoring tools for GraphQL is still thin and you need to consider what’s available if monitoring and logging is a requirement for your solution.

How to learn more…

Volia! Thanks for reading.

How to Secure Your ASP.NET Core WebApi with Azure AD and OAuth 2.0

Azure AD is a common way of access control these days. OAuth is a well-known protocol that is used and expected from APIs. I found it tricky to integrate my APIs with Azure AD. So I decided to explain it all in very simple terms in this post.

Twenty years ago, when Active Directory was part of Windows NT and Windows 2000 Server, I was no big fan of it. Nowadays, Active Directory (AD) is a core service offered in Microsoft Azure and it really is a comprehensive access management service. It offers various ways of Authentication, Single Sign-on (SSO), Business to Business authentication (B2B), Business to Customer/Guest Authentication (B2C), Application/API management, Device management and etc. On top of that, it provides conditional access rules and Multi-factor Authentication (MFA).

One of the common industry authentication standards these days is OAuth. OAuth is an open protocol for simple and secure authorization of web, mobile and desktop applications. It’s widely used and expected and if any API doesn’t have that, I’d say that’s a big negative point. As I always say, best practices and standards help us to know how that part of the system works generally and how it’s going to behave in different edge cases. No one has the time to study and learn how your API authentication mechanism works and how it’s going to behave in different situations.

OAuth offers different authentication paths (which are called as Grant Types). Each Grant Type is designed for a specific situation. For example, client credential grant type is for when an application (such as an API or a mobile App) wants to authenticate itself to another system. If you want to read more about OAuth, I’d suggest to look here.

How to accept authenticated requests in your API?

Microsoft recommends using Microsoft.Identity.Web library, and it’s a great library. It’s super easy to secure controllers with this library and only let in signed-in requests.

In Startup.cs or where you have ConfigureServices method, add this:

using Microsoft.Identity.Web;

public void ConfigureServices(IServiceCollection services)
{
    // Adds Microsoft Identity platform (AAD v2.0) support to protect this Api
    services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

    services.AddControllers();
}

And, in Configure method, add these middlewares to app-builder instance:

app.UseAuthentication();
app.UseAuthorization();

And, finally, in your controllers, you can easily use Authorize custom attribute:

[Authorize]
public class TodoListController : Controller
{
   /// controller actions
}

How to make an authenticated request to an API?

Again, we are using Microsoft.Identity.Web library. By default, the configuration of this library should be in appsettings.json:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "[Enter 'common', or 'organizations' or the Tenant Id",
    "ClientId": "[Enter the Client Id",
    "ClientSecret": "[Copy the client secret added to the app from the Azure portal]",
    
    // If using other OAuth authentication paths
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc",

    // If instead of client_id and client_secret, the Api requires a certificate
    "ClientCertificates": "[or Enter the certificate details]"
  }
}

Then, in order to obtain an access token, simply inject ITokenAcquisition in the constructor:

using Microsoft.Identity.Web;

private readonly ITokenAcquisition _tokenAcquisition;

public TodoListService(ITokenAcquisition tokenAcquisition)
{
     _tokenAcquisition = tokenAcquisition;
}

And, for client credentials flow, simply do:

var accessToken = await _tokenAcquisition.GetAccessTokenForAppAsync("<Put your scope here>");

Voilà! You have the accessToken. You can assign it now to Authorization header of your HttpClient and make the call.