コード例 #1
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(SaasafrasAppTableCreateRequest input, ILambdaContext context)
        {
            var apiKey           = System.Environment.GetEnvironmentVariable("API_KEY");
            var baseUrl          = System.Environment.GetEnvironmentVariable("BASE_URL");
            var connectionString = System.Environment.GetEnvironmentVariable("PODIO_DB_CONNECTION_STRING");

            var client = new BbcServiceClient(baseUrl, apiKey);
            SaasafrasTokenProvider token = new SaasafrasTokenProvider(input.solutionId, input.version, client);

            //var podio = new PodioCore.Podio(token);

            System.Console.WriteLine($"Entered function...");
            ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            using (var _mysql = new MySqlQueryHandler(connectionString ?? "server=mpactprodata.czsyc7qltifw.us-east-2.rds.amazonaws.com;uid=admin;pwd=perilousDeity;database=podioTest"))
            {
                if (input.spaceName != "Contacts")
                {
                    await _mysql.CreatePodioAppView(input.solutionId, input.version, input.spaceName, input.appName);

                    await _mysql.CreatePodioAppTable(input.solutionId, input.version, input.spaceName, input.appName);
                }
                else
                {
                    await _mysql.CreatePodioContactsTable();

                    var http = new System.Net.Http.HttpClient();
                    http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth2", token.TokenData.AccessToken);
                    http.BaseAddress = new Uri("https://api.podio.com/");
                    int limit  = 50;
                    int offset = 0;
                    int count  = 0;
                    do
                    {
                        var content = await http.GetStringAsync($"contact?offset={offset}&limit={limit}");

                        var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject <List <PodioContact> >(content);
                        foreach (var contact in contacts)
                        {
                            await _mysql.AddContact(
                                contact.ProfileId,
                                contact.UserId,
                                contact.Name,
                                (contact.Email?.Length ?? 0) > 0?contact.Email[0] : "",
                                (contact.Address?.Length ?? 0) > 0?contact.Address[0] : "",
                                contact.City,
                                contact.State,
                                contact.Zip,
                                contact.Type,
                                (contact.Phone?.Length ?? 0) > 0?contact.Phone[0] : ""
                                );
                        }
                        count   = contacts.Count;
                        offset += limit;
                    }while (count >= limit);
                }
            }
        }
コード例 #2
0
        private async Task <APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent)
        {
            var lambdaFunction = new TestWebApp.HttpV2LambdaFunction();
            var requestStream  = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent));

#if NETCOREAPP_2_1
            var request = new Amazon.Lambda.Serialization.Json.JsonSerializer().Deserialize <APIGatewayHttpApiV2ProxyRequest>(requestStream);
#else
            var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize <APIGatewayHttpApiV2ProxyRequest>(requestStream);
#endif
            return(await lambdaFunction.FunctionHandlerAsync(request, context));
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: will14smith/Photography
        static async Task Main(string[] args)
        {
            var      rawInput = Environment.GetEnvironmentVariable("INPUT");
            SNSEvent input;

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(rawInput)))
            {
                var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
                input = serializer.Deserialize <SNSEvent>(stream);
            }

            var processor = new ThumbnailProcessorFunction();
            await processor.Handle(input);
        }
コード例 #4
0
        public FunctionTest()
        {
            var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            // Construct a stream from our test data to replicate how Lambda
            // will get the data.
            using (var stream = GenerateStreamFromString(_testData))
            {
                _data = serializer.Deserialize <Dictionary <string, object> >(stream);
            }

            // Cache the data so it's available to the function test below.
            _data = JsonConvert.DeserializeObject <Dictionary <string, object> >(_testData);
        }
コード例 #5
0
        /// <summary>
        /// An overload of FunctionHandlerAsync to allow working with the typed API Gateway event classes. Implemented as an extension
        /// method to avoid confusion of using it as the function handler for the Lambda function.
        /// </summary>
        /// <param name="function"></param>
        /// <param name="request"></param>
        /// <param name="lambdaContext"></param>
        /// <returns></returns>
        public static async Task <APIGatewayProxyResponse> FunctionHandlerAsync(this APIGatewayProxyFunction function, APIGatewayProxyRequest request, ILambdaContext lambdaContext)
        {
            ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            var requestStream = new MemoryStream();

            serializer.Serialize <APIGatewayProxyRequest>(request, requestStream);
            requestStream.Position = 0;

            var responseStream = await function.FunctionHandlerAsync(requestStream, lambdaContext);

            var response = serializer.Deserialize <APIGatewayProxyResponse>(responseStream);

            return(response);
        }
コード例 #6
0
        public async Task KinesisFirehoseResponseLambdaFunctionAsyncTest()
        {
            // ARRANGE
            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName    = "KinesisFirehoseTest",
                FunctionVersion = "1",
                Logger          = TestLogger,
                ClientContext   = ClientContext
            };

            KinesisFirehoseEvent Event = new KinesisFirehoseEvent(
                new List <KinesisFirehoseRecord>()
            {
                new KinesisFirehoseRecord(
                    "1",
                    Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"name\":\"Mike\",\"age\":34}")),
                    1234567890)
            },
                "us-east-1",
                "arn:aws:firehose:us-east-1:123456789012:deliverystream/delivery-stream-name",
                "123"
                );

            KinesisFirehoseEventLambdaFunction Function = new KinesisFirehoseEventLambdaFunction();

            string Json = "";

            // ACT
            KinesisFirehoseTransformResponse Response = await Function.ExecAsync(Event, Context);

            using (MemoryStream MStream = new MemoryStream())
            {
                using (StreamReader Reader = new StreamReader(MStream))
                {
                    Amazon.Lambda.Serialization.Json.JsonSerializer Serde = new Amazon.Lambda.Serialization.Json.JsonSerializer();
                    Serde.Serialize(Response, MStream);
                    MStream.Position = 0;
                    Json             = Reader.ReadToEnd();
                }
            }

            // ASSERT
            Assert.True(!String.IsNullOrEmpty(Json));
        }
コード例 #7
0
ファイル: FunctionTest.cs プロジェクト: agerlet/wpa
        public async void Snap_9_Responsive_Reading()
        {
            var    jsonSerializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
            string input          = await "samples/sample-9.txt".LoadAsync();
            // Invoke the lambda function and confirm the string was upper cased.
            var json = new Function().FunctionHandler(new Models.Payload {
                Input = input
            }, new TestLambdaContext());
            string actual = await jsonSerializer.GetJsonString(json);

            string snap     = await "snaps/snap-9.json".LoadAsync();
            object o        = jsonSerializer.GetJsonObject(snap.Replace("\\n", Environment.NewLine));
            string expected = await jsonSerializer.GetJsonString(o);

            Assert.Equal(expected, actual);
        }
コード例 #8
0
ファイル: FunctionTest.cs プロジェクト: agerlet/wpa
        public async void Snap_2_1_Title_Bible_Verse_and_Multiple_Paragraphs_of_Lyrics()
        {
            var    jsonSerializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
            string input          = await "samples/sample-2.1.txt".LoadAsync();
            // Invoke the lambda function and confirm the string was upper cased.
            var json = new Function().FunctionHandler(new Models.Payload {
                Input = input
            }, new TestLambdaContext());
            string actual = await jsonSerializer.GetJsonString(json);

            string snap     = await "snaps/snap-2.1.json".LoadAsync();
            object o        = jsonSerializer.GetJsonObject(snap.Replace("\\n", Environment.NewLine));
            string expected = await jsonSerializer.GetJsonString(o);

            Assert.Equal(expected, actual);
        }
コード例 #9
0
        public override string ToString()
        {
            string myString;
            var    stream = new MemoryStream();

            var s = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            s.Serialize(this, stream);
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream))
            {
                myString = reader.ReadToEnd();
            }

            return(myString);
        }
コード例 #10
0
ファイル: FunctionTests.cs プロジェクト: youngpong/generator
        public FunctionTest()
        {
            var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            // Construct a stream from our test data to replicate how Hypar
            // will get the data.
            using (var stream = GenerateStreamFromString(_testData))
            {
                _data = serializer.Deserialize <Input>(stream);
            }

            // Add a model to the input to simulate a model
            // passing from a previous execution.
            _data.Model = new Model();
            var spaceProfile = new Profile(Polygon.Rectangle(Vector3.Origin, 2, 2));
            var space        = new Space(spaceProfile, 0, 2);

            _data.Model.AddElement(space);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: russelldear/descartes
        private static void TestGifMessage()
        {
            var testJson = @"
            { ""bodyjson"": { 
                    ""object"": ""page"", 
                    ""entry"": [
                        {
                            ""id"": ""this is an id"",
                            ""time"": ""this is a time"",
                            ""messaging"":
                            [
                                {
                                    ""message"":
                                    {
                                        ""mid"": ""message id"",
                                        ""text"": ""gif yoda""
                                    },
                                    ""sender"": {
                                        ""id"": ""sender id""
                                    },
                                    ""recipient"": {
                                        ""id"": ""recipient id""
                                    },
                                    ""timestamp"": ""message timestamp""
                                }
                            ]
                        }
                    ]
                }, 
                ""params"": { 
                    ""path"": {}, 
                    ""querystring"": {} 
                } 
            }";

            using (Stream s = GenerateStreamFromString(testJson))
            {
                var requestBody = new Amazon.Lambda.Serialization.Json.JsonSerializer().Deserialize <RequestBody>(s);

                Console.WriteLine(new Descartes.Function().FunctionHandler(requestBody, null));
            }
        }
コード例 #12
0
        public FunctionTest()
        {
            var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            // Construct a stream from our test data to replicate how Hypar
            // will get the data.
            string data = File.ReadAllText(@"..\..\..\input.json");

            using (var stream = GenerateStreamFromString(data))
            {
                _data = serializer.Deserialize <Input>(stream);
            }

            // Add a model to the input to simulate a model
            // passing from a previous execution.
            // _data.Model = new Model();
            // var spaceProfile = new Profile(Polygon.Rectangle(2, 2));
            // var space = new Space(spaceProfile, 2, 0);
            // _data.Model.AddElement(space);
        }
コード例 #13
0
ファイル: Function.cs プロジェクト: almarag/jwttokenlambda
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public object FunctionHandler(Stream input, ILambdaContext context)
        {
            try
            {
                Amazon.Lambda.Serialization.Json.JsonSerializer jsonSerializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();
                var requestInput = jsonSerializer.Deserialize <JwtAdminCredentials>(input);

                // Default response
                var result = new APIGatewayProxyResponse()
                {
                    StatusCode = 500
                };

                if (requestInput != null)
                {
                    var token = new JWTService(_context)
                                .CreateToken(requestInput, _jwtSettings);

                    return(new
                    {
                        token
                    });
                }

                return(result);
            }
            catch (Exception e)
            {
                context.Logger.Log(string.Format("Internal server error: {0}", e.Message));
                context.Logger.Log(string.Format("Stack trace: {0}", e.StackTrace));
                return(new APIGatewayProxyResponse()
                {
                    Body = JsonConvert.SerializeObject(new { message = e.Message + e.StackTrace }),
                    StatusCode = 500,
                    Headers = new Dictionary <string, string> {
                        { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE, HEAD, OPTIONS" }
                    }
                });
            }
        }
コード例 #14
0
ファイル: EventTest.cs プロジェクト: weisisheng/aws-misc
        public void ApplicationLoadBalancerRequestSingleValueTest()
        {
            using (var fileStream = File.OpenRead("alb-request-single-value.json"))
            {
                var serializer = new JsonSerializer();
                var evnt       = serializer.Deserialize <ApplicationLoadBalancerRequest>(fileStream);

                Assert.Equal(evnt.Path, "/");
                Assert.Equal(evnt.HttpMethod, "GET");
                Assert.Equal(evnt.Body, "not really base64");
                Assert.True(evnt.IsBase64Encoded);

                Assert.Equal(2, evnt.QueryStringParameters.Count);
                Assert.Equal("value1", evnt.QueryStringParameters["query1"]);
                Assert.Equal("value2", evnt.QueryStringParameters["query2"]);

                Assert.Equal("value1", evnt.Headers["head1"]);
                Assert.Equal("value2", evnt.Headers["head2"]);


                var requestContext = evnt.RequestContext;
                Assert.Equal(requestContext.Elb.TargetGroupArn, "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09");
            }
        }
コード例 #15
0
        public async System.Threading.Tasks.Task FunctionHandler(RoutedPodioEvent input, ILambdaContext context)
        {
            context.Logger.LogLine($"Entered function...");
            context.Logger.LogLine($"AppId: {input.appId}");
            context.Logger.LogLine($"ClientId: {input.clientId}");
            ILambdaSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            BrickBridge.Models.Podio.Item _item;
            using (var stream = new System.IO.MemoryStream())
            {
                serializer.Serialize <Item>(input.currentItem, stream);
                var inputText = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                context.Logger.LogLine($"Input: {inputText}");
                stream.Position = 0;
                _item           = serializer.Deserialize <Models.Podio.Item>(stream);
            }

            context.Logger.LogLine($"SpaceId: {_item.app.space_id}");
            var deployment = input.currentEnvironment.apps.First(a => a.appId == input.appId);
            var spaceName  = deployment.deployedSpaces.First(kv => kv.Value == _item.app.space_id.ToString()).Key;


            var appName = input.currentItem.App.Name;

            using (var _mysql = new MySqlQueryHandler(context))
            {
                context.Logger.LogLine($"Inserting item {input.currentItem.ItemId} from app {input.appId}");
                var podioAppId = await _mysql.GetPodioAppId(input.appId, input.version, spaceName, appName);

                var podioItemId = await _mysql.InsertPodioItem(podioAppId, input.currentItem.ItemId, int.Parse(input.podioEvent.item_revision_id), input.clientId, input.currentEnvironment.environmentId);

                var appFields = await _mysql.SelectAppFields(podioAppId);

                context.Logger.LogLine($"Item has {input.currentItem.Fields.Count} fields to insert.");
                foreach (var field in input.currentItem.Fields)
                {
                    //if the field matches a field defined for this app, insert the field data
                    if (!appFields.Any(a => a.ExternalId == field.ExternalId && a.Type == field.Type))
                    {
                        context.Logger.LogLine($"Field {field.ExternalId} was not found in the PodioFields table.");
                        continue;
                    }
                    var appField = appFields.First(a => a.ExternalId == field.ExternalId && a.Type == field.Type);
                    context.Logger.LogLine($"Inserting field {field.ExternalId} for item {input.currentItem.ItemId}");
                    switch (field.Type)
                    {
                    case "category":
                        var c = input.currentItem.Field <CategoryItemField>(field.ExternalId);
                        foreach (var option in c.Options)
                        {
                            var i = await _mysql.InsertCategoryField(podioItemId, appField.PodioFieldId, option.Text, option.Id.Value);
                        }
                        break;

                    case "contact":
                        var co = input.currentItem.Field <ContactItemField>(field.ExternalId);
                        foreach (var contact in co.Contacts)
                        {
                            var i = await _mysql.InsertContactField(podioItemId, appField.PodioFieldId, contact.ProfileId);
                        }
                        break;

                    case "date":
                        var d = input.currentItem.Field <DateItemField>(field.ExternalId);
                        if (d.Start.HasValue)
                        {
                            await _mysql.InsertDateField(podioItemId, appField.PodioFieldId, d.Start, d.End);
                        }
                        break;

                    case "duration":
                        var du = input.currentItem.Field <DurationItemField>(field.ExternalId);
                        if (du.Value.HasValue)
                        {
                            await _mysql.InsertDurationField(podioItemId, appField.PodioFieldId, du.Value.Value.Seconds);
                        }
                        break;

                    case "location":
                        var l = input.currentItem.Field <LocationItemField>(field.ExternalId);
                        foreach (var location in l.Locations)
                        {
                            var i = await _mysql.InsertLocationField(podioItemId, appField.PodioFieldId, location);
                        }
                        break;

                    case "member":
                        var me = input.currentItem.Field <ContactItemField>(field.ExternalId);
                        foreach (var member in me.Contacts)
                        {
                            var i = await _mysql.InsertMemberField(podioItemId, appField.PodioFieldId, member.ProfileId);
                        }
                        break;

                    case "money":
                        var m = input.currentItem.Field <MoneyItemField>(field.ExternalId);
                        if (m.Value.HasValue)
                        {
                            await _mysql.InsertMoneyField(podioItemId, appField.PodioFieldId, m.Value.Value, m.Currency);
                        }
                        break;

                    case "number":
                        var n = input.currentItem.Field <NumericItemField>(field.ExternalId);
                        if (n.Value.HasValue)
                        {
                            await _mysql.InsertNumberField(podioItemId, appField.PodioFieldId, n.Value.Value);
                        }
                        break;

                    case "phone":
                        var p = input.currentItem.Field <PhoneItemField>(field.ExternalId);
                        foreach (var phone in p.Value)
                        {
                            var i = await _mysql.InsertPhoneField(podioItemId, appField.PodioFieldId, phone.Type, phone.Value);
                        }
                        break;

                    case "email":
                        var e = input.currentItem.Field <EmailItemField>(field.ExternalId);
                        foreach (var email in e.Value)
                        {
                            var i = await _mysql.InsertEmailField(podioItemId, appField.PodioFieldId, email.Type, email.Value);
                        }
                        break;

                    case "progress":
                        var pr = input.currentItem.Field <ProgressItemField>(field.ExternalId);
                        if (pr.Value.HasValue)
                        {
                            await _mysql.InsertProgressField(podioItemId, appField.PodioFieldId, pr.Value.Value);
                        }
                        break;

                    case "app":
                        var a = input.currentItem.Field <AppItemField>(field.ExternalId);
                        foreach (var item in a.Items)
                        {
                            var i = await _mysql.InsertRelationField(podioItemId, appField.PodioFieldId, item.ItemId);
                        }
                        break;

                    case "text":
                        var t = input.currentItem.Field <TextItemField>(field.ExternalId);
                        await _mysql.InsertTextField(podioItemId, appField.PodioFieldId, t.Value);

                        break;

                    case "calculation":
                        //var ca = input.currentItem.Field<CalculationItemField>(field.ExternalId);
                        //if (ca.HasValue() && ca.Value.HasValue)
                        //    await _mysql.InsertNumberField(podioItemId, appField.PodioFieldId, (double)ca.Value.Value);
                        //else
                        //await _mysql.InsertTextField(podioItemId, appField.PodioFieldId, ca.ValueAsString);
                        break;

                    default: throw new Exception($"Cannot handle field type: {field.Type}");
                    }
                }
            }
        }
コード例 #16
0
        public static async Task <int> Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("You must supply the handler name.");
                return(1);
            }
            var handlerSegments = args[0].Split("::");

            if (handlerSegments.Length != 3)
            {
                Console.WriteLine("You must supply the handler name in <assemblyName>::<namespace-qualified type name>::<method> format.");
                return(2);
            }

            var pathToAssembly = System.IO.Path.Join(Environment.CurrentDirectory, "dist", handlerSegments[0] + ".dll");

            System.Reflection.Assembly lambdaAssembly = null;
            try {
                var resolver = new AssemblyResolver(pathToAssembly);
                lambdaAssembly = resolver.Assembly;
                if (lambdaAssembly == null)
                {
                    Console.WriteLine($"Unable to load assembly '{handlerSegments[0]}' from {pathToAssembly}");
                    return(3);
                }
            } catch (System.IO.FileNotFoundException) {
                Console.WriteLine($"Unable to load assembly '{handlerSegments[0]}' from {pathToAssembly}. File not found.");
                return(3);
            }

            /*
             * The below two lines need to match the namespace.class and handler method name
             * defined in your Lambda function. If you change them in your function, you
             * will need to update the two lines below.
             */
            var handlerType = lambdaAssembly.GetType(handlerSegments[1]);

            if (handlerType == null)
            {
                Console.WriteLine($"Unable to load type '{handlerSegments[1]}' from assembly.");
                return(4);
            }
            var handlerMethod = handlerType.GetMethod(handlerSegments[2]);

            if (handlerMethod == null)
            {
                Console.WriteLine($"Unable to load handler method '{handlerSegments[2]}' from '{handlerSegments[1]}'.");
                return(5);
            }

            // Prepare to deserialize the event data
            var inputType      = handlerMethod.GetParameters()[0].ParameterType;
            var serializerType = typeof(Amazon.Lambda.Serialization.Json.JsonSerializer);
            var serializer     = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            object eventData;

            using (var eventStream = Console.OpenStandardInput())
            {
                var deserializeMethod = serializerType.GetMethod("Deserialize").MakeGenericMethod(inputType);
                eventData = deserializeMethod.Invoke(serializer, new[] { eventStream });
            }

            var lambdaInstance = Activator.CreateInstance(handlerType);
            var task           = (Task)handlerMethod.Invoke(lambdaInstance, new[] { eventData, new MockContext(handlerType.Name) });

            await task.ConfigureAwait(false);

            var    resultProperty  = task.GetType().GetProperty("Result");
            object result          = resultProperty.GetValue(task);
            var    serializeMethod = serializerType.GetMethod("Serialize").MakeGenericMethod(resultProperty.PropertyType);

            using (var outStream = Console.OpenStandardOutput())
            {
                serializeMethod.Invoke(serializer, new[] { result, outStream });
            }
            return(0);
        }
コード例 #17
0
 public JsonSerializer()
 {
     _serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer(config => {
         config.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
     });
 }