Cloud Functions Using the New .NET Runtime
Tags: appwrite, dotnet, opensource, cloud
Published: 2022-06-03 15:13:28

One of the highlights of Appwrite’s latest release is the addition of **four** new Cloud Function runtimes! **Java, Kotlin, .NET, and C++** are now a part of our ever-growing list of runtimes! 🤯

In this article, we’ll take a look at writing Cloud Functions using the .NET runtime. Whether you’re a web, game, or Windows app developer, you could build your entire app and write any necessary Cloud Functions without the need to learn any new language! 🤩

> #### 🤔 New to Appwrite?
[Appwrite](https://appwrite.io) is **open source backend-as-a-service** that abstracts all the complexity involved in building a modern application by providing you with a set of REST APIs for your core backend needs. Appwrite handles user authentication and authorization, real-time databases, file storage, cloud functions, webhooks, and much more! If there is anything missing, you can extend Appwrite using your favorite backend language.

## 📝 Prerequisites

Before we get started, there are a couple of prerequisites. If you have the prerequisites set up already, you can skip to the following section. 

In order to follow along, you’ll need a few things beforehand.

* 🖥 **An Appwrite instance**

If you haven’t set up an Appwrite instance yet, you can follow the getting started guides to get up and running quickly. You can choose between [One-click installations on DigitalOcean](https://appwrite.io/docs/installation#one-click-setups) or [Manual installations with Docker](https://appwrite.io/docs/installation#installWithDocker).

**TL;DR** - It's just a single command to install Appwrite

```bash
docker run -it --rm \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
    --entrypoint="install" \
    appwrite/appwrite:0.14.2
```

Once your server is up and running, head over to the Appwrite Dashboard on your server’s public IP address ( or `localhost` if you installed locally ) and create a new admin user account.


![Sign Up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ab57xma1hl5e5orqvaf.png)

> Note: In order to enable the .NET runtime for Appwrite Cloud Functions, you need to update the `.env` file in the Appwrite installation folder. Find the file and add `dotnet-6.0` to the comma-separated list in the environment variable `_APP_FUNCTIONS_RUNTIMES`. This will make the .NET runtime available in Appwrite Functions. You can then load the updated configuration using the `docker-compose up -d` command.

* 🧑‍💻 **The Appwrite CLI**

We’ll use the Appwrite CLI during this exercise as it makes the process super simple. If you have Node.js installed, the installation command is a simple

```bash
npm install -g appwrite-cli
```

If `npm` is not your thing, we have numerous installation options you can find in the [getting started guide for the CLI](https://appwrite.io/docs/command-line). 

## 🏁 Getting Started

With everything set up, we can now begin! Login to the Appwrite CLI using the `appwrite login` command and use the credentials we used when setting up the Appwrite server to login. 

```bash
appwrite login
? Enter your email test@test.com
? Enter your password ********
? Enter the endpoint of your Appwrite server http://localhost/v1
✓ Success
```

Next, we need to create a new Appwrite project to work with. We can use the `appwrite init project` command to set it up.

```bash
appwrite init project
? How would you like to start? Create a new Appwrite project
? What would you like to name your project? Project X
✓ Success
```

You can give your project any name of your choice. You’ll notice a new `appwrite.json` file in the current directory which stores all the information about your project.

It’s time to start writing our function! But wait, we don't need to start from scratch! The CLI can setup all the boilerplate for us using the `appwrite init function` command.

```bash
appwrite init function
? What would you like to name your function? dotnet-example
? What runtime would you like to use? .NET (dotnet-6.0)
✓ Success 
```

Give your function a name and choose the **.NET 6.0** runtime. This will create a new Appwrite Function in your project and set up all the boilerplate code necessary. Feel free to examine the files created in the `functions/dotnet-example` directory. You’ll find the CLI created a simple .NET function that returns a very important JSON message

```json
{
	"areDevelopersAwesome":true
}
```

Before we go ahead and modify the function, let’s deploy it using the `appwrite deploy function` command to get a feel of the end-to-end workflow from initializing the function to deploying it. 

```bash
appwrite deploy function
? Which functions would you like to deploy? dotnet-example (629a0be8defc0742333b)
ℹ Info Deploying function dotnet-example ( 629a0be8defc0742333b )
ℹ Info Ignoring files using configuration from appwrite.json
✓ Success Deployed dotnet-example ( 629a0be8defc0742333b )
```

The appwrite deploy function command packages your source code, uploads it to the Appwrite server, and initiates the build process. During this time, all the function’s dependencies are installed and a `.dll` file is generated for your function. 

You can head over to your Appwrite Dashboard to track the progress of your deployment.


![Function Description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nmx46ouhg1ph8022fb4n.png)

Once the deployment completes, you can execute your function by clicking the **Execute Now** button. 

![Function Logs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w4ba0dmyjqqa3gmmpbqp.png)

The first execution results in what we call a **Cold Start**. Essentially this is the first time a runtime is created, so it takes a bit longer. As you can see, the first execution took about `122ms` and subsequent executions were around `3ms`. Now that we have an idea of the complete workflow, we can start tinkering with the code and write some cool functions.

## 🧮  Answering the most fundamental question in Mathematics

As the title suggests we’re going to write a cloud function to answer one of the most fundamental questions in Mathematics.

Is the given number odd or even? I know what you’re thinking… It’s so easy! Why do I need a Cloud Function for it? I could just write

```csharp
int x = 12;
Console.WriteLine(x % 2 == 0); // true
Console.WriteLine(x / 2 * 2 == x); // true
Console.WriteLine((x & 1) == 0); // true
Console.WriteLine(x >> 1 << 1 == x); // true
```

But wait! We’re taking this to the next level. We’re going to decide if our number is even or odd using one of the most sophisticated and well-written APIs out there! The [isEven API](https://isevenapi.xyz/).

Jokes aside, this example aims to illustrate how you can make API calls from your Cloud Function which will enable you to build anything you’d like. 

Firstly, open the `dotnet-example` folder in your favorite IDE. Let’s start with a blank canvas and clean up our `src/Index.cs` file to

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public async Task<RuntimeResponse> Main(RuntimeRequest req, RuntimeResponse res)
{
    var data = new Dictionary<string,object>();
    data.Add("message", "Hello World");

    return res.Json(data);
}
```

In order to deal with JSON objects more easily, we’ll make use of the popular [`Newtonsoft.Json`](https://www.nuget.org/packages/Newtonsoft.Json/) library. Include the following dependency in the `Function.csproj` file. 

```xml
<ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
```

Next, let’s write some code to read and parse a number sent as an argument to this function.

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;

public async Task<RuntimeResponse> Main(RuntimeRequest req, RuntimeResponse res)
{

    string number = "2";
    if (!string.IsNullOrEmpty(req.Payload))
    {
        var payload = JsonConvert.DeserializeObject<Dictionary<string, object>>(req.Payload, settings: null);
        number = payload?.TryGetValue("number", out var value) == true
            ? value.ToString()!
            : "2";
    }

    var data = new Dictionary<string,object>();
    data.Add("message", $"Hello World! The entered number is {number}");

    return res.Json(data);
}
```

Let’s go over the code we just wrote. From the [Cloud Functions documentation](https://appwrite.io/docs/functions#writingYourOwnFunction), we see that the `payload` is available through the `request` object and is a JSON string that needs to be converted to a JSON object to parse further. If the `payload` is empty, we replace it with an empty JSON object. This is achieved using the `Newtonsoft.json` library. 

We then retrieve the `number` that was passed to the function and default to the number `2` in case it’s empty.

Next, let’s make the call to the API using the native HTTP client. 

```csharp
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

public async Task<RuntimeResponse> Main(RuntimeRequest req, RuntimeResponse res)
{

    string number = "2";
    if (!string.IsNullOrEmpty(req.Payload))
    {
        var payload = JsonConvert.DeserializeObject<Dictionary<string, object>>(req.Payload, settings: null);
        number = payload?.TryGetValue("number", out var value) == true
            ? value.ToString()!
            : "2";
    }

    HttpClient http = new();
    var responseString = await http.GetStringAsync($"https://api.isevenapi.xyz/api/iseven/{number}/");
    var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseString, settings: null);

    return res.Json(response);
}
```

Awesome! We’re all set to test our function! If you remember the drill, all we need to do is deploy our function. 

```bash
appwrite deploy function
? Which functions would you like to deploy? dotnet-example (629a0be8defc0742333b)
ℹ Info Deploying function dotnet-example ( 629a0be8defc0742333b )
ℹ Info Ignoring files using configuration from appwrite.json
✓ Success Deployed dotnet-example ( 629a0be8defc0742333b )
```

You can now head over to the Appwrite console and execute the function with the following payload. 

![Function Input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q88wuwe55d2b59vzwq51.png)

Head over to the **Logs** tab to check the status and response from the function.

![Function Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d14cvqi8uvole5x21z7i.png)

Perfect! Looks like we’ve managed to solve one of the most pressing problems in Mathematics after all! Not to mention, the API also comes with a host of quirky Ads! 😆

And that brings us to the end of this tutorial. Feel free to modify the function to your liking and play around with the API. If you’re stuck and need any help or have any feedback and suggestions for us, we’re always here to help. Simply head over to the `#support` channel on our [Discord Server](https://appwrite.io/discord). 😊

## 📚 Resources

Here are some handy links for more information

- [Appwrite Contribution Guide](https://github.com/appwrite/appwrite/blob/master/CONTRIBUTING.md)
- [Appwrite GitHub](https://github.com/appwrite/appwrite)
- [Functions Documentation](https://appwrite.io/docs/functions)
- [Cloud Function Examples](https://github.com/open-runtimes/examples)