public SqsSender(ILambdaLogger Logger)
        {
            logger = Logger;
            var awsCreds = new BasicAWSCredentials(AccessKey, SecretKey);
            var config   = new AmazonSQSConfig
            {
                //RegionEndpoint = Amazon.RegionEndpoint.EUCentral1,
                ServiceURL = ServiceUrl
            };
            var amazonSqsClient   = new AmazonSQSClient(awsCreds, config);
            var listQueuesRequest = new ListQueuesRequest
            {
                QueueNamePrefix = "myQueue"
            };

            if (!Task.Run <bool>(async() => await QueueExists(amazonSqsClient, QueueName)).Result)
            {
                CreateQueueResponse createQueueResponse =
                    Task.Run <CreateQueueResponse>(async() => await CreateQueue(amazonSqsClient, QueueName)).Result;
            }
            if (!Task.Run <bool>(async() => await QueueExists(amazonSqsClient, QueueName)).Result)
            {
                logger.LogLine("QUEUE WAS NOT CREATED");
            }
        }
Exemple #2
0
        private async Task <CloudTrailRecords> ExtractCloudTrailRecordsAsync(ILambdaLogger logger, byte[] input)
        {
            var appearsGzipped = ResponseAppearsGzipped(input);

            logger.LogLine($"Input appears to be gzipped: {appearsGzipped}");
            if (appearsGzipped)
            {
                using (var contents = new MemoryStream())
                    using (var gz = new GZipStream(new MemoryStream(input), CompressionMode.Decompress))
                    {
                        await gz.CopyToAsync(contents);

                        input = contents.ToArray();
                    }
            }

            var serializedRecords = Encoding.UTF8.GetString(input);

            logger.Log(serializedRecords);
            return(JsonConvert.DeserializeObject <CloudTrailRecords>(serializedRecords));

            bool ResponseAppearsGzipped(byte[] bytes)
            {
                var header = new byte[GZipHeaderBytes.Length];

                Array.Copy(bytes, header, header.Length);
                return(header.SequenceEqual(GZipHeaderBytes));
            }
        }
        public IntentParameters(ILambdaLogger logger, Session inputSession, Device systemDevice)
        {
            Logger = logger;

            InputSession = inputSession;

            DeviceSupportedInterfaces = systemDevice?.SupportedInterfaces ?? new Dictionary <string, object>();

            DeviceId = systemDevice?.DeviceID ?? "";

            if (InputSession.Attributes == null)
            {
                InputSession.Attributes = new Dictionary <string, object>();
            }

            ParameterQueues = new Dictionary <string, object>
            {
                { InputsQueueKey, new PersistentQueue <InputItem>(logger, InputSession, InputsQueueKey) },
                { CommandsQueueKey, new PersistentQueue <CommandDefinition>(logger, InputSession, CommandsQueueKey) },
                { ParametersQueueKey, new PersistentQueue <ApplicationParameter>(logger, InputSession, ParametersQueueKey) }
            };

            AddParameters(logger, InputSession);

            if (inputSession.New)
            {
                foreach (var key in ParameterQueues.Keys)
                {
                    var resettableQueue = ParameterQueues[key] as IResettable;

                    resettableQueue?.Reset();
                }
            }
        }
        public PersistentQueue(ILambdaLogger logger, Session session, string key)
        {
            _fauxList = new List <T>();

            _logger = logger;

            _session = session;

            Key = "_PersistentQueue_" + key;

            if (!_session.Attributes.ContainsKey(Key))
            {
                //_logger.LogLine("New PersistentQueue " + _commandQueueKey);

                _session.Attributes[Key] = new List <T>();

                _fauxList = new List <T>();
            }
            else if (_session.Attributes.ContainsKey(Key))
            {
                //_logger.LogLine("Existing PersistentQueue " + _commandQueueKey);

                var stack = _session.Attributes[Key];

                var parsedArray = JArray.Parse(JsonConvert.SerializeObject(stack));

                _session.Attributes[Key] = parsedArray.ToObject <List <T> >();

                _fauxList = Items;
            }
        }
Exemple #5
0
        private string IfIntent(IntentRequest intentRequest, ILambdaLogger logger)
        {
            string result = "If Created, Parameters: ";

            if ((intentRequest.Intent.Slots.TryGetValue("varName", out var varName)) &&
                (intentRequest.Intent.Slots.TryGetValue("compareType", out var compareType)) &&
                (intentRequest.Intent.Slots.TryGetValue("number", out var number)))
            {
                if (!string.IsNullOrEmpty(varName?.Value))
                {
                    result += " var name: " + varName.Value;
                }

                if (!string.IsNullOrEmpty(compareType?.Value))
                {
                    result += " compareType: " + compareType.Value;
                }

                if (!string.IsNullOrEmpty(number?.Value))
                {
                    result += " number: " + number.Value;
                }


                var x    = new { varName = varName.Value, compareType = convertCompareTextToSymbol(compareType.Value), number = number.Value };
                var data = JsonConvert.SerializeObject(x);

                HttpHelper.PerformPost(Settings.PostUrl + "/CreateIf", data);
            }
            return(result);
        }
Exemple #6
0
        /*
         * public static string GetDeviceLocation2(string apiAccessToken, string url)
         * {
         *  //TODO - make this look like the other things
         *  string response = "";
         *
         *  try
         *  {
         *      var client = new HttpClient();
         *      client.DefaultRequestHeaders.Clear();
         *      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiAccessToken);
         *      client.DefaultRequestHeaders.Add("User-Agent", "Request-Promise");
         *      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
         *
         *      response = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
         *  }
         *  catch (Exception ex)
         *  {
         *      response = "error: " + ex.Message;
         *  }
         *
         *
         *  return response;
         *
         * }
         */

        public static string ExtractDeviceZipCodeFromJSON(ILambdaLogger log, string json, string defaultZipCode)
        {
            // parse out the zip code and return it

            /*
             *  {
             *  "countryCode" : "US",
             *  "postalCode" : "98109"
             *  }
             */

            log.LogLine($"CoolPlaces Skill location json:");
            log.LogLine(json);

            string zipCode = defaultZipCode;

            dynamic responseData = JsonConvert.DeserializeObject(json);

            zipCode = responseData.postalCode.ToString();

            log.LogLine($"CoolPlaces Skill location zip:");
            log.LogLine(zipCode);

            return(zipCode);
        }
Exemple #7
0
        /// <summary>
        /// Handles the intent and returns the required information
        /// </summary>
        private async Task <SkillResponse> HandleIntent(SkillRequest skillRequest, ILambdaLogger logger)
        {
            IntentRequest intentRequest = skillRequest.Request as IntentRequest;

            if (intentRequest.Intent.ConfirmationStatus == ConfirmationStatus.Denied)
            {
                return(ResponseBuilder.Tell("Then I cannot help you!"));
            }

            if (intentRequest.Intent.Name == "PersonIsInOfficeIntent")
            {
                return(await HandleIsPersonInOfficeIntent(intentRequest, logger));
            }
            else if (intentRequest.Intent.Name == "WhereIsPersonIntent")
            {
                return(await HandlewhereIsPersonIntent(intentRequest, logger));
            }
            else if (intentRequest.Intent.Name == "PersonCameToWorkToday")
            {
                return(await HandlePersonCameToWorkToday(skillRequest, logger));
            }
            else
            {
                return(HandleUnknownIntent());
            }
        }
        public async Task <string> Transcode(string sourceFile, ILambdaLogger logger)
        {
            var pipelines = await transcoder.ListPipelinesAsync();

            var pipeline = pipelines.Pipelines.First(p => p.Name == "adex_pipeline");

            logger.LogLine(String.Format("Found pipeline {0} with input {1}, output {2}", pipeline.Name, pipeline.InputBucket, pipeline.OutputBucket));

            pipeline.Role = "arn:aws:iam::160534783289:role/Elastic_Transcoder_Default_Role";

            var response = await transcoder.CreateJobAsync(new CreateJobRequest()
            {
                PipelineId = pipeline.Id,

                Input = new JobInput()
                {
                    Container = "auto",
                    Key       = sourceFile
                },
                Output = new CreateJobOutput()
                {
                    Key      = String.Format("{0}.mp3", sourceFile),
                    PresetId = MP3_PRESET
                }
            });

            logger.LogLine(response.HttpStatusCode.ToString());

            return("transcoded " + sourceFile);
        }
 public string parseTitle(string t, ILambdaLogger log)
 {
     try
     {
         char first = t[0];
         if (!Char.IsLetter(first))
         {
             t = t.Remove(0, 1);
         }
         if (t.Contains("Today I Learned"))
         {
             t = t.Replace("Today I Learned", "");
         }
         else if (t.Contains("today I learned"))
         {
             t = t.Replace("Today I Learned", "");
         }
         //Optimize the beginning
         string f = t[0].ToString();
         if (f == f.ToLower() && f != f.ToUpper())
         {
             t = t[0].ToString().ToUpper() + t.Substring(1, t.Length - 1);
         }
         return(t);
     }
     catch (Exception e)
     {
         log.LogLine("error: " + e.Message);
         return(t);
     }
 }
        private async Task StartNewSurveyAsync(string phoneNumber, ILambdaLogger logger)
        {
            // save info about the respondent
            logger.LogLine($"Saving survey response for {Sanitizer.MaskPhoneNumber(phoneNumber)}");
            var phoneNumberHash = Sanitizer.HashPhoneNumber(phoneNumber);
            var surveyResponse  = new SurveyResponse
            {
                PhoneNumberHash = phoneNumberHash,
                TaskToken       = "",
                Responses       = new Dictionary <string, string>()
            };
            await _DataAccess.SaveSurveyResponeAsync(surveyResponse).ConfigureAwait(false);

            // start the workflow
            logger.LogLine($"Starting workflow for {Sanitizer.MaskPhoneNumber(phoneNumber)}");
            using (var client = StepFunctionClientFactory.GetClient())
            {
                var state = new State
                {
                    PhoneNumber = phoneNumber
                };
                var req = new StartExecutionRequest
                {
                    Name            = phoneNumberHash + Guid.NewGuid().ToString("N"),
                    StateMachineArn = ServerlessConfig.StateMachineArn,
                    Input           = JsonConvert.SerializeObject(state)
                };
                await client.StartExecutionAsync(req).ConfigureAwait(false);
            }
        }
Exemple #11
0
        public AudioSkillResponse Handle(AudioSkillRequest input, ILambdaContext context)
        {
            _log = context.Logger;
            _log.LogLine($"Request type={input.GetRequestType()}.");

            if (input.GetRequestType() == typeof(ILaunchRequest))
            {
                return(HandleLaunchRequest());
            }
            if (input.GetRequestType() == typeof(IIntentRequest))
            {
                return(HandleIntentRequest(input.Request));
            }
            if (input.GetRequestType() == typeof(IAudioPlayerPlaybackNearlyFinishedRequest))
            {
                return(HandlePlaybackNearlyFinishedRequest(input.Request));
            }
            if (input.GetRequestType() == typeof(IAudioPlayerPlaybackStartedRequest))
            {
                return(HandlePlaybackStartedRequest(input.Request));
            }
            if (input.GetRequestType() == typeof(IAudioPlayerPlaybackStoppedRequest))
            {
                return(HandlePlaybackStoppedRequest(input.Request));
            }
            if (input.GetRequestType() == typeof(IAudioPlayerPlaybackFailedRequest))
            {
                _log.LogLine($"Request: {input.Request}");
                return(Failed("Failed to play song."));
            }
            return(DefaultResponse(input.Request));
        }
Exemple #12
0
        public async Task FunctionHandler(ILambdaContext context)
        {
            _context = context;
            _logger  = _context.Logger;
            _logger.Log($"{context?.FunctionName} => {nameof(FunctionHandler)} => Started");
            _verbose = Environment.GetEnvironmentVariable("verbose").ToBoolOrDefault(true);
            var maxTime   = 60 * 1000;
            var rateLimit = 20 * 1000;
            var sw        = Stopwatch.StartNew();

            long remaining = 0;

            do
            {
                _logger.Log($"New Execution Started, currently elpased: {sw.ElapsedMilliseconds}");
                var elapsed = await Execute();

                var rateAwait = rateLimit - elapsed;

                remaining = maxTime - (sw.ElapsedMilliseconds + Math.Max(rateLimit, 2 * elapsed) + 1000);

                if (rateAwait > 0 && remaining > 0)
                {
                    Log($"Rate Limit Awaiting {rateAwait} [ms] remaining out of {rateLimit} [ms]. Total elapsed: {sw.ElapsedMilliseconds} [ms]");
                    await Task.Delay((int)rateAwait);
                }

                await Task.Delay(1000);
            } while (remaining > 0);
        }
Exemple #13
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 SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            //standard stuff
            var requestType = input.GetRequestType();

            _logger    = context.Logger;
            _alexaUser = input.Session.User.UserId;
            SetStandardResponse();

            if (requestType == typeof(LaunchRequest))
            {
                _logger.LogLine($"Default LaunchRequest made: 'Strava, open Jira");
                (_innerResponse as PlainTextOutputSpeech).Text = "Welcome to the Strava skill. Ask me some questions";
            }

            if (input.GetRequestType() == typeof(IntentRequest))
            {
                var intentRequest = (IntentRequest)input.Request;


                switch (intentRequest.Intent.Name)
                {
                case "GetLastActivityIntent":
                    GetLastActivityIntent();
                    break;

                default:
                    _logger.LogLine($"Unknown intent: {intentRequest.Intent.Name}");
                    (_innerResponse as PlainTextOutputSpeech).Text = "Sorry, Strava cant answer that question yet";
                    break;
                }
            }

            return(_response);
        }
 private string ParseResponse(GetObjectResponse response, ILambdaLogger logger)
 {
     using (var stream = response.ResponseStream)
     {
         return(new DdexToJsonConverter().ToJson(XDocument.Load(stream)));
     }
 }
        /// <summary>
        /// Validate New and Old are valid
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="oldResult"></param>
        /// <param name="newResult"></param>
        /// <param name="homeStats"></param>
        /// <param name="awayStats"></param>
        /// <returns></returns>
        private async Task <bool> ValidateMatchAsync(ILambdaLogger logger, DataRepository.DataEntities.Match oldResult,
                                                     DataRepository.DataEntities.Match newResult, TeamSeasonStats homeStats, TeamSeasonStats awayStats)
        {
            if (oldResult.Year != newResult.Year || oldResult.Season != newResult.Season ||
                oldResult.Round != newResult.Round)
            {
                logger.LogLine($"Match is invalid {newResult.Year}#{newResult.Season}#{newResult.Round}#{newResult.MatchId}.");
                return(false);
            }

            if ((_year.HasValue && _season.HasValue) && (newResult.Year != _year.Value || newResult.Season != _season.Value))
            {
                logger.LogLine($"Match has invalid year or season {newResult.Year}#{newResult.Season}#{newResult.Round}#{newResult.MatchId}.");
                return(false);
            }

            if (oldResult.MatchId != newResult.MatchId || oldResult.HomeTeamId != newResult.HomeTeamId ||
                oldResult.AwayTeamId != newResult.AwayTeamId)
            {
                logger.LogLine($"Match is invalid, teams don't match {newResult.Year}#{newResult.Season}#{newResult.Round}#{newResult.MatchId}.");
                return(false);
            }

            if (newResult.WasPlayed && (!newResult.HomeScore.HasValue || !newResult.AwayScore.HasValue))
            {
                logger.LogLine($"Match is invalid, match played but no score {newResult.Year}#{newResult.Season}#{newResult.Round}#{newResult.MatchId}.");
                return(false);
            }

            return(true);
        }
Exemple #16
0
        private SkillResponse HandleIntent(IntentRequest intentRequest, ILambdaLogger logger)
        {
            logger.LogLine($"IntentRequest {intentRequest.Intent.Name} made");

            // Do Web Scraping and get the Data from websites
            //var responseSpeech = "Hello world";
            //var responseSpeech = WebScraping.GetAllCertifications(CategoryOfQuestion.Certification)[0].Description;
            //intentRequest.Intent.Name == 'Certification'
            var responseSpeech = "";

            if (intentRequest.Intent.Slots.TryGetValue("Category", out var category))
            {
                if (!string.IsNullOrEmpty(category.Value))
                {
                    responseSpeech = filterCategory(category.Value);
                }
            }

            if (intentRequest.Intent.Slots.TryGetValue("City", out var citySlot))
            {
                if (!string.IsNullOrEmpty(citySlot.Value))
                {
                    responseSpeech += $" from {citySlot.Value}";
                }
            }

            responseSpeech += "!";

            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = responseSpeech
            });

            return(response);
        }
Exemple #17
0
        public static AuthPolicyBuilder Validade(string token,
                                                 string method,
                                                 ILambdaLogger logger)
        {
            try
            {
                var methodArn  = ApiGatewayArn.Parse(method);
                var apiOptions = new ApiOptions(methodArn.Region, methodArn.RestApiId, methodArn.Stage);

                var policyBuilder = new AuthPolicyBuilder("", methodArn.AwsAccountId, apiOptions);

                var isValid = token.Equals("7793B690-9EC7-4240-A152-1D3046693CB3");

                if (isValid)
                {
                    policyBuilder.AllowMethod(new HttpVerb(methodArn.Verb), methodArn.Resource);
                }
                else
                {
                    policyBuilder.DenyMethod(new HttpVerb(methodArn.Verb), methodArn.Resource);
                }

                return(policyBuilder);
            }
            catch (Exception e)
            {
                logger.LogLine($"Error {e.Message} at {e.StackTrace}");

                return(default);
Exemple #18
0
        /// <summary>
        /// This method fails or times out with at least 20% chance
        /// </summary>
        private Task CallUnpredictableExternalAPI(SQSEvent.SQSMessage message, ILambdaLogger contextLogger)
        {
            contextLogger.Log(" ** inside CallExternalService **");

            //about 10% of requests should explode
            var seed = Guid.NewGuid().GetHashCode();

            contextLogger.Log($" ** checking RND seed {seed} **");
            var rnd           = new Random(seed);
            int failureChance = rnd.Next(1, 11);

            if (failureChance == 5)
            {
                contextLogger.Log($" ** about to throw exception, failureChance = {failureChance} **");
                throw new ApplicationException();
            }

            //about 10% of requests should time out
            failureChance = rnd.Next(1, 11);
            if (failureChance == 10)
            {
                contextLogger.Log($" ** about to freeze,  failureChance = {failureChance} **");
                Thread.Sleep(TimeOutSeconds * 1000);
                return(Task.Run(() => {}));
            }

            //this is happy path
            return(this.ResendMessageToAnotherQueue(OutputQueueUrl, message, contextLogger));
        }
Exemple #19
0
 public static void UpdateLogger(ILambdaLogger logger, StringBuilder sb)
 {
     Logger.WriteLine = s =>
     {
         logger.LogLine(s);
         sb?.Append(s + "\n");
     };
 }
        public async Task Initialize(APIGatewayProxyRequest request, ILambdaContext context)
        {
            this.ProxyRequest = request;
            this.Logger       = context.Logger;
            await this.InitializeConfiguration();

            await this.InitializeServiceProvider();
        }
 public DynamoDbBaseRepository(AmazonDynamoDBClient dynamoDBClient, ILambdaLogger lambdaLogger, JsonHelper jsonHelper = null)
 {
     LambdaLogger         = lambdaLogger;
     Logger               = null;
     DynamoDBContext      = new DynamoDBContext(dynamoDBClient);
     AmazonDynamoDBClient = dynamoDBClient;
     JsonHelper           = jsonHelper ?? new JsonHelper();
 }
 public DynamoDbBaseRepository(AWSCredentials awsCredentials, RegionEndpoint awsRegion, ILambdaLogger logger, JsonHelper jsonHelper = null)
 {
     LambdaLogger         = logger;
     Logger               = null;
     AmazonDynamoDBClient = new AmazonDynamoDBClient(awsCredentials, awsRegion);
     DynamoDBContext      = new DynamoDBContext(AmazonDynamoDBClient);
     JsonHelper           = jsonHelper ?? new JsonHelper();
 }
Exemple #23
0
        private Task <SkillResponse> HandleStopIntentAsync(IntentRequest request, ILambdaLogger logger)
        {
            var response = ResponseBuilder.Empty();

            response.Response.ShouldEndSession = true;

            return(Task.FromResult(response));
        }
Exemple #24
0
        public ConsoleOutWrapper(ILambdaLogger logger)
        {
            _standardOut = Console.Out;
            Console.SetOut(new WrapperTextWriter(_standardOut, logger, false));

            _standardError = Console.Error;
            Console.SetError(new WrapperTextWriter(_standardError, logger, false));
        }
Exemple #25
0
        /// <summary>
        /// Handles when the user calls the skill name
        /// </summary>
        private SkillResponse HandleLaunch(LaunchRequest launchRequest, ILambdaLogger logger)
        {
            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = "Hello! You can ask me if someone is in the office if you want."
            });

            return(response);
        }
Exemple #26
0
        public async Task FunctionHandler(SQSEvent sqsEvent, ILambdaContext context)
        {
            _logger = context.Logger;

            foreach (var record in sqsEvent.Records)
            {
                await ProcessMessageAsync(record);
            }
        }
Exemple #27
0
        private SkillResponse HandleLaunch(LaunchRequest launchRequest, ILambdaLogger logger)
        {
            logger.LogLine($"LaunchRequest made");
            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = $"Welcome! This is a perfect working speach to program program."
            });

            return(response);
        }
Exemple #28
0
 public CurrentSession(ILambdaLogger log, String subreddit, int postNumber, String selfText, String title, bool inTitleMode, String url)
 {
     this.log         = log;
     this.subreddit   = subreddit;
     this.postNumber  = postNumber;
     this.selfText    = selfText;
     this.title       = title;
     this.inTitleMode = inTitleMode;
     this.url         = url;
 }
        public async Task <Document> Persist(Message message, ILambdaLogger logger)
        {
            logger.LogLine("writing " + message.Name + " to DynamoDB Names document");

            var artist = new Document();

            artist["Name"] = message.Name;

            return(await namesTable.PutItemAsync(artist));
        }
 public static AuthPolicyBuilder Validade(string token,
                                          string method,
                                          ILambdaLogger logger)
 {
     try
     {
         token = token.Replace("Bearer ", "");
         var xApiTokenChar = new char[1];
         token.CopyTo(token.Length - 1, xApiTokenChar, 0, 1);
         token = token[0..^ 1];