Exemple #1
0
 public static void CreateClient(string serviceUrl)
 {
     try {
         Instance = new AmazonDynamoDBClient(new AmazonDynamoDBConfig {
             ServiceURL = serviceUrl
         });
     } catch (Exception e) {
         LambdaLogger.Log($"Error: failed to create a DynamoDB client: {e.Message}");
     }
 }
Exemple #2
0
 public PostgreSQLDataClient(ConnectionStringsConfig connConfig)
 {
     /*config = new ConnectionStringsConfig
      * {
      *  PostgreSQL = Config.PostgresConnectionString,
      *  ConnectionTimeout = 15
      * };*/
     config = connConfig;
     LambdaLogger.Log("connection string is " + this.config.PostgreSQL);
 }
Exemple #3
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 string FunctionHandler(string input, ILambdaContext _)
        {
            LambdaLogger.Log("Input: " + input);

            // ConnectToDatabase();

            LambdaLogger.Log($"From custom class library: IsEven(2) {SampleCalcUtil.IsEven(2)}");

            return(input?.ToUpper());
        }
        public override void GetSongInfoRequested(Dictionary <string, Slot> intentSlots)
        {
            var trackFound = intentSlots.TryGetValue("SongNumber", out Slot trackRequested);

            if (trackFound)
            {
                SongRequested.SongNumber = trackRequested.Value;
                LambdaLogger.Log($"*** INFO: SongNumber {trackRequested.Value}");
            }
        }
Exemple #5
0
        public string Put()
        {
            LambdaLogger.Log($"Credential-only Test invoked");

            var secretJson = SecretService.GetSecret("dynamo_iam_user").Result;

            LambdaLogger.Log($"Secret received");

            return(secretJson);
        }
Exemple #6
0
 //--- Constructors ---
 public MicrobFunction()
 {
     _tableName = System.Environment.GetEnvironmentVariable("DYNAMO_TABLE_NAME");
     _awsRegion = System.Environment.GetEnvironmentVariable("AWS_REGION");
     LambdaLogger.Log($"***INFO: {_tableName}");
     LambdaLogger.Log($"***INFO: {_awsRegion}");
     _regionEndpoint = RegionEndpoint.GetBySystemName(_awsRegion);
     _dynamoClient   = new AmazonDynamoDBClient(_regionEndpoint);
     _table          = Table.LoadTable(_dynamoClient, _tableName);
 }
Exemple #7
0
 private static AccessDetails ReturnNotAuthorised(AuthorizerRequest authorizerRequest)
 {
     LambdaLogger.Log(
         $"Token beginning with {authorizerRequest.Token.Substring(0, 8)} is invalid or should not have access to" +
         $" {authorizerRequest.ApiAwsId} - {authorizerRequest.ApiEndpointName}" +
         $" in {authorizerRequest.Environment}");
     return(new AccessDetails {
         Allow = false, User = "******"
     });
 }
        public static SkillResponse GenerateAlexaAskResponse(string message, Dictionary <string, object> sessionAttributes, bool shouldEndSession)
        {
            var repromptMessage = GenerateRepromptMessage(message);
            var finalResponse   = ResponseBuilder.Ask(message, repromptMessage);

            finalResponse.SessionAttributes         = sessionAttributes;
            finalResponse.Response.ShouldEndSession = shouldEndSession;
            LambdaLogger.Log($"*** INFO: Alexa final response: {JsonConvert.SerializeObject(finalResponse)}");
            return(finalResponse);
        }
Exemple #9
0
 private static APIGatewayProxyResponse SendServerErrorResponse(Exception e)
 {
     LambdaLogger.Log("Error: " + e.Message);
     return(new APIGatewayProxyResponse
     {
         IsBase64Encoded = true,
         StatusCode = 500,
         Body = "Error processing request: " + ". Error Details: " + e.Message + e.StackTrace
     });
 }
Exemple #10
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 string FunctionHandler(string input, ILambdaContext context)
        {
            LambdaLogger.Log($"Incoming input is: {input}");

            return(input switch
            {
                "Hello" => "Hello World",
                "Foo" => "Foo",
                _ => input?.ToUpper(),
            });
        /// <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 <string> FunctionHandler(object input, ILambdaContext context)
        {
            LambdaLogger.Log("Input: " + input.ToString());
            var auth = await GetOrganisationAuth.GetOrganisationAuthCodes().ConfigureAwait(true);

            var result = JsonConvert.SerializeObject(auth);

            LambdaLogger.Log("Output: " + result);
            return(result);
        }
Exemple #12
0
        //No content (Base Type)
        public IEnumerable <Card> FindFromBaseType(GetCardRequest request)
        {
            LambdaLogger.Log($"Entering: FindFromBaseType({ JsonConvert.SerializeObject(request) })");

            var conditions = new List <ScanCondition>();

            AddBaseTypeConditions(request, conditions);

            return(FindAll(conditions));
        }
Exemple #13
0
        //Lambda entery point - ****maybe i can with the handler serializer get the pickup location in constructor...
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            //returning a bad 'response' if something not went wall
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.BadRequest
            };

            try
            {
                //inserting a byte array in order to return a random string orderId
                string orderId = toUrlString(new byte[32]);

                //requester user name from cognito user pool
                string userName = request.RequestContext.Authorizer.Claims.GetValueOrDefault("cognito:username");

                //taking the body of the apigateway lambda request
                var deserialize = JObject.Parse(request.Body);
                this.body = JsonConvert.DeserializeObject <PickUpLocation>(deserialize["PickupLocation"].ToString());


                //logging the event we recieved
                LambdaLogger.Log("Received event (" + orderId + "): " + "Latitude: " + body.Latitude + ",Longitude: " + body.Longitude + "...");

                //getting the unicorn nearest to the desired location (for now returning just a random one)
                PickUpLocation pickUpLocation = this.body;
                Unicorn        unicorn        = findUnicorn(pickUpLocation);

                //adding the ride to dynamoDB
                await recordRide(orderId, userName, unicorn);

                //prepering the response of our apigateway
                RideResponse ride = new RideResponse(orderId, unicorn, unicorn.Name, "30 seconds", userName);

                //adding and logging the weather from a weather api service call for the given lat and lon
                ride.Weather = await GetWeatherForecast(pickUpLocation.Latitude, pickUpLocation.Longitude);

                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = JsonConvert.SerializeObject(ride),
                    Headers    = new Dictionary <string, string> {
                        { "Access-Control-Allow-Origin", "*" }
                    }
                };
            }
            catch (Exception e)
            {
                context.Logger.LogLine("Error in inserting a new item to the database and/or returning a valid value");
                context.Logger.LogLine(e.Message);
                context.Logger.LogLine(e.StackTrace);
            }

            return(response);
        }
        /// <summary>
        /// Includes market price and productId on the card
        /// </summary>
        /// <param name="importList"></param>
        public async void AddTCGDetails(Card importCard)
        {
            LambdaLogger.Log($"Entering: AddTCGDetails({ JsonConvert.SerializeObject(importCard) })");

            try
            {
                var name = importCard.Name;

                var filter = new TCGSearchFilter
                {
                    name   = "ProductName",
                    values = new List <string>()
                    {
                        name
                    }
                };

                var request = new TCGSearchRequest
                {
                    filters = new List <TCGSearchFilter>()
                    {
                        filter
                    },
                    limit  = 10,
                    offset = 0
                };

                var searchResponse = await Search(request);

                LambdaLogger.Log($"TCG Search Response: { JsonConvert.SerializeObject(searchResponse) }");

                if (searchResponse.success)
                {
                    var responseCard = searchResponse.results
                                       .Where(x => x.name == name)
                                       .FirstOrDefault();

                    if (responseCard != null)
                    {
                        importCard.TCGGroupId   = responseCard.groupId;
                        importCard.TCGProductId = responseCard.productId;
                    }
                }
                else
                {
                    LambdaLogger.Log($"TCG Search Response failure: { JsonConvert.SerializeObject(searchResponse) }");
                }
            }
            catch (Exception exp)
            {
                LambdaLogger.Log($"Error: {exp}");
            }

            LambdaLogger.Log($"Leaving: AddTCGDetails({ JsonConvert.SerializeObject(importCard) })");
        }
Exemple #15
0
        public override LexResponse Process(LexEvent lexEvent, ILambdaContext context)
        {
            IDictionary <string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> requestAttributes = lexEvent.RequestAttributes ?? new Dictionary <string, string>();
            IDictionary <string, string> slots             = lexEvent.CurrentIntent.Slots;

            LambdaLogger.Log("GetBin Intent Processor");
            LambdaLogger.Log("Bot Name =" + lexEvent.Bot.Name);
            LambdaLogger.Log("Bot Aliase =" + lexEvent.Bot.Alias);
            LambdaLogger.Log("Bot Version =" + lexEvent.Bot.Version);
            LambdaLogger.Log("user ID =" + lexEvent.UserId);
            LambdaLogger.Log("Transcription =" + lexEvent.InputTranscript);
            LambdaLogger.Log("Invocation Source =" + lexEvent.InvocationSource);
            LambdaLogger.Log("Output Dialog Mode =" + lexEvent.OutputDialogMode);

            foreach (KeyValuePair <string, string> entries in sessionAttributes)
            {
                LambdaLogger.Log(string.Format("Session Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in requestAttributes)
            {
                LambdaLogger.Log(string.Format("Request Attribute = {0}, Value = {1}", entries.Key, entries.Value));
            }

            foreach (KeyValuePair <string, string> entries in slots)
            {
                LambdaLogger.Log(string.Format("Slot = {0}, Value = {1}", entries.Key, entries.Value));
            }

            String faqResponse = ReadObjectDataAsync(lexEvent.InputTranscript).Result;

            if (faqResponse.Equals(""))
            {
                return(Close(
                           sessionAttributes,
                           "Failed",
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = String.Format("Please wait for one of my human colleagues to join this chat.")
                }));
            }
            else
            {
                return(Close(
                           sessionAttributes,
                           "Fulfilled",
                           new LexResponse.LexMessage
                {
                    ContentType = MESSAGE_CONTENT_TYPE,
                    Content = String.Format(faqResponse)
                }));
            }
        }
Exemple #16
0
        /// <summary>
        /// Entry point for the BlogPost Handler.
        /// </summary>
        /// <param name="blogPost">The Incoming BlogPost</param>
        /// <param name="context">The Lambda event context</param>
        /// <returns></returns>
        public BlogPost FunctionHandler(BlogPost blogPost, ILambdaContext context)
        {
            // not using a separate logic layer because this _is_ the logic layer
            LambdaLogger.Log("BlogPostHandler Lambda Started");

            // Config/Initialization
            EnvironmentHandler env = EnvironmentHandler.GetEnvironmentHandler();

            string bucketName         = env.GetVariable("BucketName");
            string bucketRegionString = env.GetVariable("BucketRegion");
            string postsDirectory     = env.GetVariable("PostsDirectory");
            string imagesDirectory    = env.GetVariable("ImagesDirectory");
            string metaDirectory      = env.GetVariable("MetaDirectory");

            // get blog post
            BlogPostS3Access blogPostAccess = new BlogPostS3Access(bucketName, bucketRegionString);

            blogPostAccess.Logger = context.Logger;

            var blogPostResponse = blogPostAccess.GetBlogPost(blogPost);

            blogPostResponse.Wait();
            blogPost = blogPostResponse.Result;

            if (blogPost.Metadata != null)
            {
                // get related posts
                TagFileS3Access tagFileAccess = new TagFileS3Access();
                tagFileAccess.Logger = context.Logger;
                var relatedPostsResponse = tagFileAccess.GetBlogPostIdsFromTags(blogPost.Metadata.Tags);
                relatedPostsResponse.Wait();
                blogPost.RelatedPosts = relatedPostsResponse.Result;

                // remove all related posts which are the current post
                blogPost.RelatedPosts.RemoveAll(b => b.Id == blogPost.Id);

                // populate related posts objects
                for (int i = 0; i < blogPost.RelatedPosts.Count; i++)
                {
                    var relatedPostResponse = blogPostAccess.GetBlogPost(blogPost.RelatedPosts[i]);
                    relatedPostResponse.Wait();
                    blogPost.RelatedPosts[i] = relatedPostResponse.Result;

                    // remove Markdown identifiers in the teaser content text, as it shows up
                    // as a related post
                    blogPost.RelatedPosts[i].Content = StringHelper.StripMarkdownIdentifiers(blogPost.RelatedPosts[i].Content);
                }
            }
            else
            {
                return(null);
            }

            return(blogPost);
        }
Exemple #17
0
        /// <summary>
        /// Entry point for loading user decks
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse LoadUserDeck(APIGatewayProxyResponse request, ILambdaContext context)
        {
            LambdaLogger.Log($"Entering: LoadUserDeck({ JsonConvert.SerializeObject(request) })");

            var response = new APIGatewayProxyResponse()
            {
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json" },
                    { "Access-Control-Allow-Origin", "*" }
                }
            };

            try
            {
                if (request.Body == "CloudWatch")
                {
                    return(response);
                }

                var requestDto = JsonConvert.DeserializeObject <LoadDeckRequest>(request.Body);

                var MTGService = ServiceFactory.GetService <MTGService>();

                var deckResponse = MTGService.LoadUserDeck(requestDto);

                response.Body       = JsonConvert.SerializeObject(deckResponse);
                response.StatusCode = (int)HttpStatusCode.OK;
            }
            catch (Exception exp)
            {
                Dictionary <string, string> body = new Dictionary <string, string>()
                {
                    { "Message", "y u breaking my stuff?" },
                    { "Error", $"This is all you get, here's your peasant error: { exp.Message }" }
                };

                var errorResponse = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" },
                        { "Access-Control-Allow-Origin", "*" }
                    },
                    Body = JsonConvert.SerializeObject(body)
                };

                LambdaLogger.Log($"Leaving: LoadUserDeck({ JsonConvert.SerializeObject(errorResponse) })");
                return(errorResponse);
            }

            LambdaLogger.Log($"Leaving: LoadUserDeck({ JsonConvert.SerializeObject(response) })");

            return(response);
        }
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
        {
            //string tableName = System.Environment.GetEnvironmentVariable("DYNAMO_TABLE");
            LambdaLogger.Log("EVENT: " + JsonConvert.SerializeObject(apigProxyEvent));
            try
            {
                string resourceId = null;
                int    idLength   = 1;
                if (apigProxyEvent.Path == "/shortUrl")
                {
                    resourceId = createId(idLength);
                    LambdaLogger.Log("Test environment for set");

                    while (true)
                    {
                        resourceId = createId(idLength);
                        LambdaLogger.Log("Generated id " + resourceId);
                        ShortUrlItem item = await table.get(resourceId);

                        if (item == null)
                        {
                            ApiUrlRequestBody requestBody = JsonConvert.DeserializeObject <ApiUrlRequestBody>(apigProxyEvent.Body);
                            await table.save(new ShortUrl(resourceId, requestBody.originalUrl).dynamoItem);

                            break;
                        }
                        LambdaLogger.Log("ITEM: " + item.ToString() + " ID: " + item.resourceId);
                        idLength++;
                    }
                    return(CreateBasicResponse(new ApiBody
                    {
                        resourceId = resourceId,
                        completeUrl = createCompleteUrl(resourceId)
                    }));
                }
                else
                {
                    LambdaLogger.Log("Test environment for get");
                    ShortUrlItem item = await table.get(apigProxyEvent.PathParameters["resourceId"]);

                    LambdaLogger.Log("ITEM: " + item.ToString() + " ID: " + item.resourceId);

                    resourceId = item.resourceId;
                    if (item.ttl < new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds())
                    {
                        throw new Exception("Expired url");
                    }

                    return(CreateRedirectResponse(item.originalUrl));
                }
            } catch (Exception e)
            {
                return(CreateErrorResponse());
            }
        }
Exemple #19
0
        protected virtual async Task PreparePubSubMessage(SQSEvent sqs)
        {
            LambdaLogger.Log($"Starting to process {sqs.Records.Count} SQS records...");
            foreach (var record in sqs.Records)
            {
                if (!record.MessageAttributes.ContainsKey(Constants.PubSubBucket))
                {
                    continue;
                }

                LambdaLogger.Log($"The records message attributes contains key {Constants.PubSubBucket}");
                var bucket     = record.MessageAttributes[Constants.PubSubBucket].StringValue;
                var key        = record.MessageAttributes[Constants.PubSubKey].StringValue;
                var s3Response = await _s3Client.GetObjectAsync(bucket, key);

                var json = await ReadStream(s3Response.ResponseStream);

                var snsEvent = JsonConvert.DeserializeObject <SNSEvent.SNSMessage>(json);
                if (snsEvent?.Message != null && snsEvent.MessageAttributes != null)
                {
                    record.Body = snsEvent.Message;

                    LambdaLogger.Log("Adding SNS message attributes to record");
                    foreach (var attribute in snsEvent.MessageAttributes)
                    {
                        if (!record.MessageAttributes.ContainsKey(attribute.Key))
                        {
                            record.MessageAttributes.Add(attribute.Key,
                                                         new SQSEvent.MessageAttribute
                            {
                                DataType = "String", StringValue = attribute.Value.Value
                            });
                        }
                    }
                }
                else
                {
                    var sqsEvent = JsonConvert.DeserializeObject <SendMessageRequest>(json);
                    record.Body = sqsEvent.MessageBody;

                    LambdaLogger.Log("Adding SQS message attributes to record");
                    foreach (var attribute in sqsEvent.MessageAttributes)
                    {
                        if (!record.MessageAttributes.ContainsKey(attribute.Key))
                        {
                            record.MessageAttributes.Add(attribute.Key,
                                                         new SQSEvent.MessageAttribute
                            {
                                DataType = "String", StringValue = attribute.Value.StringValue
                            });
                        }
                    }
                }
            }
        }
Exemple #20
0
        public async Task <List <Quote> > GetAllResponses()
        {
            var responses = new List <Quote>();

            var request = new ScanRequest
            {
                TableName = "WisdomOfAvasarala",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":s", new AttributeValue {
                          S = "1"
                      } }
                },
                FilterExpression = "reply = :s"
            };

            var resp = await _client.ScanAsync(request);

            foreach (Dictionary <string, AttributeValue> item in resp.Items)
            {
                var quote = new Quote();

                quote.medium = item["medium"].S;
                if (quote.medium == "TV")
                {
                    quote.uuid        = item["uuid"].S;
                    quote.season      = item["season"].S;
                    quote.episode     = item["episode"].S;
                    quote.runningTime = item["runningTime"].S;
                }
                Boolean found;
                if (quote.medium == "Book")
                {
                    found         = Int32.TryParse(item["page"].S, out Int32 page);
                    quote.uuid    = item["uuid"].S;
                    quote.book    = item["book"].S;
                    quote.chapter = item["chapter"].S;
                    quote.page    = (found ? page : 0);
                }

                found           = Int32.TryParse(item["quality"].S, out Int32 quality);
                quote.quality   = (found ? quality : 0);
                quote.polite    = item["polite"].S == "1";
                quote.statement = item["statement"].S == "1";
                quote.reply     = item["reply"].S == "1";
                quote.quoteText = item["quote"].S;

                responses.Add(quote);
            }

            LambdaLogger.Log($"Responses Count: {responses.Count}\n");

            return(responses);
        }
Exemple #21
0
        public Card FindByName(string name, string manaCost)
        {
            LambdaLogger.Log($"Entering: FindByName({name})");

            //var cards = FindAll(string.Format("Name = {0}", name)).FirstOrDefault();
            var card = DynamoDbHelper.Load <Card>(name, manaCost);

            LambdaLogger.Log($"Leaving: FindByName({ JsonConvert.SerializeObject(card) })");

            return(card);
        }
Exemple #22
0
 /// <summary>
 ///     Constructor to get the sql connection string
 /// </summary>
 public DatabaseWrapper()
 {
     try
     {
         sqlConnection = new SqlConnection(string.Format(_connectionString));
     }
     catch (Exception connectionString)
     {
         LambdaLogger.Log(connectionString.ToString());
     }
 }
Exemple #23
0
        //--- FunctionHandler ---
        public override async Task <string> ProcessMessageAsync(S3Event s3Event)
        {
            LambdaLogger.Log($"*** INFO: PutObjectRequest: {JsonConvert.SerializeObject(s3Event)}");
            var bucketName = s3Event.Records.FirstOrDefault().S3.Bucket.Name;
            var keyName    = s3Event.Records.FirstOrDefault().S3.Object.Key;

            // process request
            await SonglistUpload.HandleRequest(bucketName, keyName);

            return("upload complete");
        }
Exemple #24
0
        static string GetEnv(string envName, string humanName)
        {
            var value = Environment.GetEnvironmentVariable(envName);

            if (value == null)
            {
                LambdaLogger.Log($"Environment variable was not provided during deployment {humanName}");
                throw new ServerException("Invalid server configuration");
            }
            return(value);
        }
Exemple #25
0
        public override void GetSongInfoRequested(Dictionary <string, Slot> intentSlots)
        {
            var options = intentSlots.TryGetValue("Options", out Slot speakerOption);

            if (!options)
            {
                return;
            }
            SpeakerAction = speakerOption.Value;
            LambdaLogger.Log($"*** INFO: Speaker option {speakerOption.Value}");
        }
        private async Task <bool> DeleteItem(string id)
        {
            DeleteItemOperationConfig config = new DeleteItemOperationConfig {
                // Return the deleted item.
                ReturnValues = ReturnValues.AllOldAttributes
            };
            await _table.DeleteItemAsync(id, config);

            LambdaLogger.Log($"*** INFO: Deleted item {id}");
            return(true);
        }
Exemple #27
0
 public void PrintParams(string parameterType, IDictionary <string, string> parameters)
 {
     if (parameters != null)
     {
         foreach (string key in parameters.Keys)
         {
             LambdaLogger.Log(parameterType + " key: " + key + " , value: " + parameters[key] + "\n");
         }
     }
     return;
 }
Exemple #28
0
        public static void Log(string message)
        {
            if (!initialized)
            {
                throw new InvalidOperationException("Logger is not initialized with module name!");
            }
            var line = string.Format(logFormat, DateTime.Now, moduleName, message);

            Trace.WriteLine(line);
            LambdaLogger.Log(line);
        }
Exemple #29
0
 public Function()
 {
     try
     {
         DatabaseWrapper._connectionString = Environment.GetEnvironmentVariable("ConnectionString").ToString();
     }
     catch (Exception connectionException)
     {
         LambdaLogger.Log(connectionException.ToString());
     }
 }
Exemple #30
0
        public GovNotifyStatusResponse GetStatusForLetter(string documentId, string govNotifyNotificationId)
        {
            var response = _govNotifyClient.GetNotificationById(govNotifyNotificationId);

            LambdaLogger.Log($"GovNotify responded successfully with status {response.status}");
            return(new GovNotifyStatusResponse
            {
                Status = GetStatus(response.status),
                SentAt = response.completedAt
            });
        }