aws-lambda How to develop aws-lambda(C#) on a local machine Step 2. Add and change code in your project


Example

  1. Open Function.cs and replace the class code with the following:

    public class Function
    {
    
    /// <summary>
    /// A simple function that takes a birth date and returns Age in years
    /// </summary>
    /// <param name="input"></param>
    /// <returns>Age is years</returns>
    /// 
    [LambdaSerializer(typeof(SimpleSerializer))]
    public string FunctionHandler(Dictionary<string, int> input)
    {
        var defaultMessage = "Age could not be determined.";
    
        var birthDate = new DateTime(input["year"], input["month"], input["day"]);
        var ageInYears = DateTime.Today.Year - birthDate.Year;
        if (birthDate.DayOfYear > DateTime.Today.DayOfYear)
            ageInYears--;
    
        defaultMessage = $"Age in years: {ageInYears}";
    
        return defaultMessage;
    }
    }
    

You will need to add the following using statements near the top:

using System.Collections.Generic;
using Amazon.Lambda.Core;
  1. Add a file to the project named SimpleSerializer.cs
  2. Place the following code in that file:
using System;

using System.IO;
using Amazon.Lambda.Core;
using Newtonsoft.Json;

namespace AWSLambdaFunctionAgeInYears
{
public class SimpleSerializer : ILambdaSerializer
{
    public T Deserialize<T>(Stream requestStream)
    {
        string text;
        using (var reader = new StreamReader(requestStream))
            text = reader.ReadToEnd();

        try
        {
            return JsonConvert.DeserializeObject<T>(text);
        }
        catch (Exception ex)
        {
            if (typeof(T) == typeof(System.String))
                return (T)Convert.ChangeType(text, typeof(T));

            throw ex;
        }

    }

    public void Serialize<T>(T response, Stream responseStream)
    {
        StreamWriter streamWriter = new StreamWriter(responseStream);
        try
        {
            string text = JsonConvert.SerializeObject(response);
            streamWriter.Write(text);
            streamWriter.Flush();
        }
        catch (Exception ex)
        {
            if (typeof(T) == typeof(System.String))
            {
                streamWriter.Write(response);
                streamWriter.Flush();
                return;
            }

            throw ex;
        }

    }
}
}
  1. In the Test Project, change line 23 of the FunctionTest.cs to the following:

            var upperCase = function.FunctionHandler(null);
    
  2. Build your solution - you should have no build errors.