Updated on 2024-04-12 GMT+08:00

C# Function Development

Function Syntax

You are advised to use .NET Core 3.1.

FunctionGraph supports C# (.NET Core 2.1) and C# (.NET Core 3.1).

Scope Return parameter Function name (User-defined parameter, Context)

  • Scope: It must be defined as public for the function that FunctionGraph invokes to execute your code.
  • Return parameter: user-defined output, which is converted into a character string and returned as an HTTP response.
  • Function name: user-defined function name. The name must be consistent with that you define when creating a function.

    In the navigation pane on the left of the FunctionGraph console, choose Functions > Function List. Click the name of the function to be set. On the function details page that is displayed, choose Configuration > Basic Settings and set the Handler parameter, as shown in Figure 1. The parameter value is in the format of index.handler. The values of index and handler can be customized.

    Figure 1 Handler parameter
  • Event: event parameter defined for the function.
  • context: runtime information provided for executing the function. For details, see the description of SDK APIs.

    The HC.Serverless.Function.Common library needs to be referenced when you deploy a project in FunctionGraph. For details about the IFunctionContext object, see the context description.

    When creating a C# function, you need to define a method as the handler of the function. The method can access the function by using specified IFunctionContext parameters. Example:

    1
    2
    3
    4
    public Stream handlerName(Stream input,IFunctionContext context)
    {
           // TODO
    }
    

Function Handler

ASSEMBLY::NAMESPACE.CLASSNAME::METHODNAME

  • ASSEMBLY: name of the .NET assembly file for your application, for example, HelloCsharp.
  • NAMESPACE and CLASSNAME: names of the namespace and class to which the handler function belongs.
  • METHODNAME: name of the handler function. Example:

    Set the handler to HelloCsharp::Example.Hello::Handler when you create a function.

SDK APIs

  • Context APIs

    Table 1 describes the provided context attributes.

    Table 1 Context objects

    Attribute

    Description

    String RequestId

    Request ID.

    String ProjectId

    Project Id

    String PackageName

    Name of the group to which the function belongs.

    String FunctionName

    Function name.

    String FunctionVersion

    Function version.

    Int MemoryLimitInMb

    Allocated memory.

    Int CpuNumber

    CPU usage of a function.

    String Accesskey

    Obtains the AK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    NOTE:

    FunctionGraph has stopped maintaining the String AccessKey API in the Runtime SDK. You cannot use this API to obtain a temporary AK.

    String Secretkey

    Obtains the SK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    NOTE:

    FunctionGraph has stopped maintaining the String SecretKey API in the Runtime SDK. You cannot use this API to obtain a temporary SK.

    String SecurityAccessKey

    Obtains the SecurityAccessKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    String SecuritySecretKey

    Obtains the SecuritySecretKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    String SecurityToken

    Obtains the SecurityToken (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    String Token

    Obtains the token (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

    Int RemainingTimeInMilliSeconds

    Remaining running time of a function.

    String GetUserData(string key,string defvalue=" ")

    Uses keys to obtain the values passed by environment variables.

  • Logging APIs

    The following table describes the logging APIs provided in the C# SDK.

    Table 2 Logging APIs

    Method

    Description

    Log(string message)

    Creates a logger object by using context.

    var logger = context.Logger;

    logger.Log("hello CSharp runtime test(v1.0.2)");

    Logf(string format, args ...interface{})

    Creates a logger object by using context.

    var logger = context.Logger;

    var version = "v1.0.2"

    logger.Logf("hello CSharp runtime test({0})", version);

Developing a C# Function

If you use sample package fss_example_csharp2.0, skip 1 and 2, go to 3, and modify the function handler to MyCsharpPro::src.Program::myFunc.

The following describes how to create a C# (.NET Core 2.0) function in Linux.

  1. Create a C# project.

    Log in to a Linux server on which the .NET SDK and required running environment have been installed. Create the /home/fsscsharp/src directory, and decompress the .dll package to this directory, as shown in Figure 2.

    This document uses the DLL function of the fssCsharp2.0-1.0.1 version as an example. The DLL functions of different versions are the same.
    Figure 2 Decompressing the .dll package

    Run the dotnet --info command to check whether the .NET environment has been installed. The command output is as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    root@SZX1000371099:/home/fsscsharp/src# dotnet --info
    .NET Command Line Tools (2.1.202)
    
    Product Information:
     Version:            2.1.202
     Commit SHA-1 hash:  281caedada
    
    Runtime Environment:
     OS Name:     ubuntu
     OS Version:  14.04
     OS Platform: Linux
     RID:         ubuntu.14.04-x64
     Base Path:   /home/lusinking/dotnetdev/sdk/2.1.202/
    
    Microsoft .NET Core Shared Framework Host
    
      Version  : 2.0.9
      Build    : 1632fa1589b0eee3277a8841ce1770e554ece037
    

    Run the following command to create and initialize a console application project:

    "dotnet new console -n project_name"

    Example command:

    dotnet new console -n MyCsharpPro

    Create a handler function in the Program.cs code file in the /home/fsscsharp/src/MyCsharpPro directory. The input is the body of a client request, and the context is a runtime context object provided by FunctionGraph. For more information about context objects, see the context API description. The code is as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    using HC.Serverless.Function.Common;
    using System;
    using System.IO;
    using System.Text;
    
    namespace src
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
            public Stream myFunc(Stream input,IFunctionContext context)
            {
                string payload = "";
                if (input != null && input.Length > 0)
                {
                    byte[] buffer = new byte[input.Length];
                    input.Read(buffer, 0, (int)(input.Length));
                    payload = Encoding.UTF8.GetString(buffer);
                }
                var ms = new MemoryStream();
                using (var sw = new StreamWriter(ms))
                {
                    sw.WriteLine("CSharp runtime test(v1.0.2)");
                    sw.WriteLine("=====================================");
                    sw.WriteLine("Request Id:       {0}", context.RequestId);
                    sw.WriteLine("Function Name:    {0}", context.FunctionName);
                    sw.WriteLine("Function Version: {0}", context.FunctionVersion);
                    sw.WriteLine("Project:          {0}", context.ProjectId);
                    sw.WriteLine("Package:          {0}", context.PackageName);
                    sw.WriteLine("Access Key:       {0}", context.AccessKey);
                    sw.WriteLine("Secret Key:       {0}", context.SecretKey);
                    sw.WriteLine("Token:            {0}", context.Token);
                    sw.WriteLine("User data(ud-a):  {0}", context.GetUserData("ud-a"));
                    sw.WriteLine("User data(ud-notexist): {0}", context.GetUserData("ud-notexist", ""));
                    sw.WriteLine("User data(ud-notexist-default): {0}", context.GetUserData("ud-notexist", "default value"));
                    sw.WriteLine("=====================================");
    
                    var logger = context.Logger;
                    logger.Logf("Hello CSharp runtime test(v1.0.2)");
                    sw.WriteLine(payload);
                }
                return new MemoryStream(ms.ToArray());
            }
        }
    }
    

    For details about the constraints for the APIG event source, see Base64 Decoding and Response Structure.

  2. Compile the C# project.

    Manually add the dll reference (relative path of dll in HinPath) provided by FunctionGraph to the project configuration file MyCsharpPro.csproj. The code is as follows:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
        <Reference Include="HC.Serverless.Function.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
          <HintPath>../HC.Serverless.Function.Common.dll</HintPath>
        </Reference>
      </ItemGroup>
    </Project>

    Run the dotnet build command to compile the project. The command output is as follows:

    root@SZX1000371099:/home/fsscsharp/src/MyCsharpPro# vi MyCsharpPro.csproj
    root@SZX1000371099:/home/fsscsharp/src/MyCsharpPro# dotnet build
    Microsoft (R) Build Engine version 15.7.179.6572 for .NET Core
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      Restore completed in 54.28 ms for /home/fsscsharp/src/MyCsharpPro/MyCsharpPro.csproj.
      MyCsharpPro -> /home/fsscsharp/src/MyCsharpPro/bin/Debug/netcoreapp2.0/MyCsharpPro.dll
    
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    
    Time Elapsed 00:00:01.47

  3. Deploy the C# project to FunctionGraph.

    Use the SSH tool to copy and package the compiled files, as shown in Figure 3.
    Figure 3 Packaging the compiled files

    Create a function and upload the ZIP file.

    Execute the function. The function execution result consists of three parts: function output (returned by callback), summary, and logs (output by using the Console.WriteLine() method).

Execution Result

The execution result consists of the function output, summary, and log output.

Table 3 Description of the execution result

Parameter

Successful Execution

Failed Execution

Function Output

The defined function output information is returned.

A JSON file that contains errorMessage and errorType is returned. The format is as follows:

{
    "errorMessage": "",
    "errorType": ""
}

errorMessage: Error message returned by the runtime.

errorType: Error type.

Summary

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Log Output

Function logs are printed. A maximum of 4 KB logs can be displayed.

Error information is printed. A maximum of 4 KB logs can be displayed.