Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Cloud Functions Using the New .NET Runtime
Appwrite profile imageAditya Oberai
Aditya Oberai forAppwrite

Posted on • Edited on

     

Cloud Functions Using the New .NET Runtime

One of the highlights of Appwrite’s latest release is the addition offour 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 isopen 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 betweenOne-click installations on DigitalOcean orManual 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
Enter fullscreen modeExit fullscreen mode

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

Sign Up

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 adddotnet-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 thedocker-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

npminstall-g appwrite-cli
Enter fullscreen modeExit fullscreen mode

Ifnpm is not your thing, we have numerous installation options you can find in thegetting started guide for the CLI.

🏁 Getting Started

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

appwrite login? Enter your emailtest@test.com? Enter your password********? Enter the endpoint of your Appwrite server http://localhost/v1✓ Success
Enter fullscreen modeExit fullscreen mode

Next, we need to create a new Appwrite project to work with. We can use theappwrite 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
Enter fullscreen modeExit fullscreen mode

You can give your project any name of your choice. You’ll notice a newappwrite.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 theappwrite init function command.

appwrite initfunction? What would you like to name yourfunction? dotnet-example? What runtime would you like to use? .NET(dotnet-6.0)✓ Success
Enter fullscreen modeExit fullscreen mode

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 thefunctions/dotnet-example directory. You’ll find the CLI created a simple .NET function that returns a very important JSON message

{"areDevelopersAwesome":true}
Enter fullscreen modeExit fullscreen mode

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

appwrite deployfunction? Which functions would you like to deploy? dotnet-example(629a0be8defc0742333b)ℹ Info Deployingfunctiondotnet-example( 629a0be8defc0742333b)ℹ Info Ignoring files using configuration from appwrite.json✓ Success Deployed dotnet-example( 629a0be8defc0742333b)
Enter fullscreen modeExit fullscreen mode

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

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

Function Logs

The first execution results in what we call aCold 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 about122ms and subsequent executions were around3ms. 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

intx=12;Console.WriteLine(x%2==0);// trueConsole.WriteLine(x/2*2==x);// trueConsole.WriteLine((x&1)==0);// trueConsole.WriteLine(x>>1<<1==x);// true
Enter fullscreen modeExit fullscreen mode

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! TheisEven 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 thedotnet-example folder in your favorite IDE. Let’s start with a blank canvas and clean up oursrc/Index.cs file to

usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;publicasyncTask<RuntimeResponse>Main(RuntimeRequestreq,RuntimeResponseres){vardata=newDictionary<string,object>();data.Add("message","Hello World");returnres.Json(data);}
Enter fullscreen modeExit fullscreen mode

In order to deal with JSON objects more easily, we’ll make use of the popularNewtonsoft.Json library. Include the following dependency in theFunction.csproj file.

<ItemGroup><PackageReferenceInclude="Newtonsoft.Json"Version="13.0.1"/></ItemGroup>
Enter fullscreen modeExit fullscreen mode

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

usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingNewtonsoft.Json;publicasyncTask<RuntimeResponse>Main(RuntimeRequestreq,RuntimeResponseres){stringnumber="2";if(!string.IsNullOrEmpty(req.Payload)){varpayload=JsonConvert.DeserializeObject<Dictionary<string,object>>(req.Payload,settings:null);number=payload?.TryGetValue("number",outvarvalue)==true?value.ToString()!:"2";}vardata=newDictionary<string,object>();data.Add("message",$"Hello World! The entered number is{number}");returnres.Json(data);}
Enter fullscreen modeExit fullscreen mode

Let’s go over the code we just wrote. From theCloud Functions documentation, we see that thepayload is available through therequest object and is a JSON string that needs to be converted to a JSON object to parse further. If thepayload is empty, we replace it with an empty JSON object. This is achieved using theNewtonsoft.json library.

We then retrieve thenumber that was passed to the function and default to the number2 in case it’s empty.

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

usingSystem;usingSystem.Collections.Generic;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingNewtonsoft.Json;publicasyncTask<RuntimeResponse>Main(RuntimeRequestreq,RuntimeResponseres){stringnumber="2";if(!string.IsNullOrEmpty(req.Payload)){varpayload=JsonConvert.DeserializeObject<Dictionary<string,object>>(req.Payload,settings:null);number=payload?.TryGetValue("number",outvarvalue)==true?value.ToString()!:"2";}HttpClienthttp=new();varresponseString=awaithttp.GetStringAsync($"https://api.isevenapi.xyz/api/iseven/{number}/");varresponse=JsonConvert.DeserializeObject<Dictionary<string,object>>(responseString,settings:null);returnres.Json(response);}
Enter fullscreen modeExit fullscreen mode

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

appwrite deployfunction? Which functions would you like to deploy? dotnet-example(629a0be8defc0742333b)ℹ Info Deployingfunctiondotnet-example( 629a0be8defc0742333b)ℹ Info Ignoring files using configuration from appwrite.json✓ Success Deployed dotnet-example( 629a0be8defc0742333b)
Enter fullscreen modeExit fullscreen mode

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

Function Input

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

Function Output

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

📚 Resources

Here are some handy links for more information

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Build like a team of hundreds_

More fromAppwrite

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp