All Products
Search
Document Center

Function Compute:Compile and deploy code packages

Last Updated:Apr 25, 2024

You can compile a program in an on-premises .NET environment, package the program into a ZIP package, and then upload the code package in the Function Compute console or by using Serverless Devs. Then, you can test your function to ensure that your code runs as expected.

Dependency library of the C# runtime environment

Function Compute provides the Aliyun.Serverless.Core dependency library for the C# runtime. You can use the library to define information such as the handler interface and the context object.

You can obtain the preceding dependency library from NuGet packages and add the library to the <YourProjectName>.csproj file in the code directory. The following sample code provides an example:

  <ItemGroup>
        <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
        <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.3" />
  </ItemGroup>

Use .NET Core CLI to compile and deploy a program

A .NET Core deployment package must contain the assemblies that are compiled by using your function and the dependencies of all assemblies. You can use .NET Core CLI to compile and deploy a program. If you use the .NET Core CLI, you can create a .NET-based Function Compute application across platforms. For more information, see .NET.

Step 1: Create a .NET project

  1. Run the following command to create a .NET project:

    dotnet new console -o HelloFcApp -f netcoreapp3.1

    The following items describe the parameters in the preceding command:

    • new console: the application template in the console.

    • -o|--output: the output path of the project. In this example, the HelloFcApp directory is created to store the project content.

    • -f|--framework: the .NET version. If the runtime version is .NET Core 3.1, set the parameter to netcoreapp3.1. If the runtime version is .NET Core 2.1, set the parameter to netcoreapp2.1.

    The following sample code provides an example of project directory structures:

    HelloFcApp
    ├── HelloFcApp.csproj
    ├── Program.cs
    └── obj
  2. In the project directory, modify the parameter settings in the file based on the actual situation.

    • HelloFcApp.csproj file

      The configuration file of the .NET project. The file records the information about the project, such as the target framework and the dependency library of the assembly. You must add the dependency library provided by Function Compute to the file. The following sample code provides an example:

      <Project Sdk="Microsoft.NET.Sdk">
      
        <PropertyGroup>
          <OutputType>Exe</OutputType>
          <TargetFramework>netcoreapp3.1</TargetFramework>
        </PropertyGroup>
      
        <ItemGroup>
              <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
              <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.3" />
        </ItemGroup>
      
      </Project>
    • Program.cs file

      The code of the handler. For more information, see Handlers. In this topic, an event handler of the Stream type is used.

      using System.IO;
      using System.Threading.Tasks;
      using Aliyun.Serverless.Core;
      using Microsoft.Extensions.Logging;
      
      namespace Example
      {
          public class Hello
          {
              public async Task<Stream> StreamHandler(Stream input, IFcContext context)
              {
                  IFcLogger logger = context.Logger;
                  logger.LogInformation("Handle request: {0}", context.RequestId);
                  MemoryStream copy = new MemoryStream();
                  await input.CopyToAsync(copy);
                  copy.Seek(0, SeekOrigin.Begin);
                  return copy;
              }
      
              static void Main(string[] args){}
          }
      }

Step 2: Compile the .NET project

  1. Run the following command to go to the project directory to compile the project and output the result to the target directory:

    cd HelloFcApp && dotnet publish -c Release -o ./target
  2. Run the following command to go to the target directory to package the project:

    cd target && zip -r HelloFcApp.zip *

    The following sample code provides an example of the structure of ZIP packages:

    HelloFcApp.zip
    ├── Aliyun.Serverless.Core.dll
    ├── HelloFcApp.deps.json
    ├── HelloFcApp.dll
    ├── HelloFcApp.pdb
    ├── HelloFcApp.runtimeconfig.json
    └── Microsoft.Extensions.Logging.Abstractions.dll
    Important

    Make sure that the HelloFcApp.dll file and other files are packaged to the root directory of the ZIP file.

Step 3: Deploy the project code and perform verification

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click Create Function.

  3. On the Create Function page, select Event Function, configure the parameters, and then click Create.

    The following items describe the parameters that you must configure on the Create Function page. Use the default values for other parameters.

    • Runtime: Select .NET Core 3.1.

    • Code Upload Method: Select Upload ZIP and upload the ZIP file that is packaged in Step 2.

    • Handler: Enter HelloFcApp::Example.Hello::StreamHandler. For information about the format of a handler, see Handlers.

    After the function is created, you are redirected to the Code tab of the Function Details page.

  4. On the Code tab of the Function Details page, click Test Function.

    After the function is successfully executed, the following result is returned:

    {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }

    You can also click the Log Output tab to view the information about the logs.

Compile and deploy code packages by using Serverless Devs

Before you start

Procedure

  1. Run the following command to initialize the project:

    s init 

    Configure Alibaba Cloud as the cloud vendor, a template, a runtime, and the region in which the application is deployed, and the function name.

  2. Run the following command to go to the directory of the project:

    cd start-fc3-dotnetcore

    The following code snippet shows the directory structure:

    start-fc3-dotnetcore
    ├── HelloFcApp
    │   ├── bin
    │   ├── obj
    │   ├── target
    │   ├── HelloWorldApp.csproj
    │   └── Program.cs
    ├── readme
    └── s.yaml
  3. Run the following command to deploy the project:

    s deploy

    Sample command output:

    s.yaml: /root/start-fc3-dotnetcore/s.yaml
    Downloading[/v3/packages/fc3/zipball/0.0.24]...
    Download fc3 successfully
      Steps for [deploy] of [hello-world-app]
    ====================
    Microsoft (R) Build Engine version 16.7.3+2f374e28e for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      Determining projects to restore...
      Restored /root/start-fc3-dotnetcore/HelloWorldApp/HelloWorldApp.csproj (in 154 ms).
      HelloWorldApp -> /root/start-fc3-dotnetcore/HelloWorldApp/bin/Release/netcoreapp3.1/HelloWorldApp.dll
      HelloWorldApp -> /root/start-fc3-dotnetcore/HelloWorldApp/target/
    
     [hello_world] completed (2.66s)
    
     Result for [deploy] of [hello-world-app]
    ====================
    region:         cn-hangzhou
    description:    hello world by serverless devs
    functionName:   start-dotnetcore-p6jp
    handler:        HelloWorldApp::Example.Hello::StreamHandler
    internetAccess: true
    memorySize:     128
    role:           
    runtime:        dotnetcore3.1
    timeout:        10
    
    A complete log of this run can be found in: /root/.s/logs/0327105651
  4. Run the sudo s invoke command to test the function.

    Sample command output:

      Steps for [invoke] of [hello-world-app]
    ====================
    ========= FC invoke Logs begin =========
    FunctionCompute dotnetcore3.1 runtime inited.
    FC Invoke Start RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    hello world!  
    FC Invoke End RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    
    Duration: 117.33 ms, Billed Duration: 118 ms, Memory Size: 128 MB, Max Memory Used: 13.16 MB
    ========= FC invoke Logs end =========
    
    Invoke instanceId: c-6603951e-15f440b6-2df37e4bf046
    Code Checksum: 13273801077182424526
    Qualifier: LATEST
    RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    
    Invoke Result:
    hello world!  
    ✔ [hello_world] completed (0.72s)
    
    A complete log of this run can be found in: /root/.s/logs/0327114013