Appwrite
Published in

Appwrite

Cloud Functions Using the New .NET Runtime

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 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 or Manual installations with Docker.

TL;DR — It’s just a single command to install Appwrite

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.

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

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.

🏁 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.

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.

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.

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

{
"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.

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.

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

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

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.

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

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 library. Include the following dependency in the Function.csproj file.

<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.

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, 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.

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.

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.

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

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. 😊

📚 Resources

Here are some handy links for more information

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Oberai

Aditya Oberai

296 Followers

DevRel🥑 @ Appwrite📍Hosts random community convos 🤓📍👨‍👩‍👧‍👦 MLH Coach | Twilio Champion | Gold Microsoft Student Ambassador | Google DSC Lead 👨‍👩‍👧‍👦