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);
            }
        }
Example #2
0
        private async Task <bool> SendSMS(string fromNumber, string toNumber, string message, ILambdaLogger logger)
        {
            bool result;

            try
            {
                dynamic smsResource = await _twilioApi.MessagingApi.SendSMS(_twilioApi.AccountSid,
                                                                            new System.Collections.Generic.Dictionary <string, string>
                {
                    { "From", fromNumber },
                    { "To", toNumber },
                    { "Body", message.EndsWith("phone=")
                            ? message + IVRWorkflow.SwitchCallerId(toNumber)
                            : message }
                });

                string status = smsResource.status;
                result = status.Equals("queued");
                if (result)
                {
                    logger.LogLine("SMS message queued for sending to " + toNumber);
                    logger.LogLine("Twilio SMS message resource: " + JsonConvert.SerializeObject(smsResource));
                }
                else
                {
                    logger.LogLine("SMS message not queued");
                }
            }
            catch (ApiException ex)
            {
                logger.LogLine("Cannot send SMS: " + ex.Message);
                result = false;
            }
            return(result);
        }
        /// <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);
        }
Example #4
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));
        }
Example #5
0
        public async Task ProcessMessageAsync(SQSEvent.SQSMessage message)
        {
            _logger.LogLine("Processing message \n" + message.Body);

            DownloadEpubContract epubDownloadContract =
                JsonConvert.DeserializeObject <DownloadEpubContract>(message.Body);

            User user = epubDownloadContract.User;

            TelegramFileResult telegramFileResult = GetTelegramFile(epubDownloadContract.FileId);

            Stream fileStream = GetTelegramFileStream(telegramFileResult.Result.FilePath);

            string bucketName  = Environment.GetEnvironmentVariable("ALEXA_READER_BUCKET");
            string contentType = "application/epub+zip";
            string uuid        = Guid.NewGuid().ToString();
            string folderName  = $"{user.FromId}/{uuid}";
            string fileName    = $"{uuid}.epub";

            AwsService.S3.PutObject(fileStream, $"{folderName}/{fileName}", bucketName, contentType);

            ParseEpubContract processContract = new ParseEpubContract
            {
                User       = user,
                FileName   = fileName,
                FolderName = folderName,
            };

            string messageBody = JsonConvert.SerializeObject(processContract);
            string queueUrl    = Environment.GetEnvironmentVariable("PARSE_EPUB_QUEUE_URL");

            AwsService.SQS.SendMessage(messageBody, queueUrl);

            _logger.LogLine($"Message sent to {queueUrl} queue\n" + messageBody);
        }
Example #6
0
        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);
        }
Example #7
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);
        }
Example #8
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);
        }
Example #9
0
        public async Task <string> GetMenuItems(string weekDay)
        {
            ExtServiceHelper service      = new ExtServiceHelper();
            string           _weekDay     = String.Empty;
            string           menu         = String.Empty;
            bool             QueryNeeded  = true;
            List <string>    weekDayNames = new List <string> {
                "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"
            };

            if ((String.IsNullOrEmpty(weekDay)) || (!weekDayNames.Contains(weekDay.ToUpper())))
            {
                weekDay = null;
            }
            if (String.IsNullOrEmpty(weekDay))
            {
                log.LogLine($"Weekday slot value is: NULL");
                DateTime today = DateTime.Now;
                _weekDay = today.DayOfWeek.ToString().ToUpper();
                if ((_weekDay.Equals("SATURDAY", StringComparison.CurrentCultureIgnoreCase) || (_weekDay.Equals("SUNDAY", StringComparison.CurrentCultureIgnoreCase))))
                {
                    _weekDay = "MONDAY";
                }
            }
            else
            {
                if ((weekDay.Equals("SATURDAY", StringComparison.CurrentCultureIgnoreCase) || (weekDay.Equals("SUNDAY", StringComparison.CurrentCultureIgnoreCase))))
                {
                    log.LogLine($"External API query not required. Sending a standard response...");
                    menu        = "Chirec doesn't provide school lunch on Saturdays and Sundays. Try asking the menu for a weekday instead...";
                    QueryNeeded = false;
                }
                else
                {
                    _weekDay = weekDay;
                }
            }

            if (QueryNeeded)
            {
                log.LogLine($"API Request: " + webApiUri + _weekDay);
                string response = await service.GetDataFromService(webApiUri, new List <object> {
                    _weekDay
                });

                menu = "The menu for " + _weekDay + " is " + response;
            }
            log.LogLine($"Final Response: " + menu);
            return(menu);
        }
        public async Task <SkillResponse> HandleAsync(IntentRequest request, ILambdaLogger logger)
        {
            var agencyName       = request.Intent.Slots?.FirstOrDefault(slot => slot.Key == "agency").Value?.Value;
            var agencyNameExists = !string.IsNullOrEmpty(agencyName);

            var agencyId = GetAgencyId(agencyName);

            if (agencyNameExists && agencyId == null)
            {
                // The user said something weird
                var response = ResponseBuilder.Tell(new PlainTextOutputSpeech
                {
                    Text = "I didn't quite get that. Which launch do you want to learn about?"
                });
                response.Response.ShouldEndSession = false;
                return(response);
            }

            var responseSpeech = string.Empty;

            try
            {
                var upcomingLaunches = await GetUpcomingLaunchesFromCache(logger);

                var launch = agencyId == null
                    ? upcomingLaunches.FirstOrDefault()
                    : upcomingLaunches.FirstOrDefault(l => l.Rocket.Agencies.Any(a => a.Id == agencyId));

                if (launch == null)
                {
                    responseSpeech = $"I can't find any upcoming {(agencyId == null ? "" : agencyName)} launches.";
                }
                else
                {
                    responseSpeech = $"{launch.Rocket.Name} will be launching the {launch.Missions.First().Name} mission <break strength=\"medium\"/> from {launch.Location.Name} <break strength=\"medium\"/> no earlier than <say-as interpret-as=\"date\">????{launch.Net.Value.ToString("MMdd")}</say-as>.";
                }
            }
            catch (Exception ex)
            {
                logger.LogLine($"Exception caught: {ex.GetType().Name}");
                logger.LogLine(ex.Message);
                responseSpeech = "Sorry, I wasn't able to retrieve the next launch.";
            }

            return(ResponseBuilder.Tell(new SsmlOutputSpeech()
            {
                Ssml = $"<speak>{SsmlSanitizer.Sanitize(responseSpeech)}</speak>"
            }));
        }
Example #11
0
        public SkillResponse FunctionHandlerAsync(SkillRequest input, ILambdaContext context)
        {
            // Objekte vor Aufruf erzeugen
            SkillResponse skillResponse = new SkillResponse();

            skillResponse.Response = new ResponseBody {
                ShouldEndSession = false
            };
            IOutputSpeech outputSpeech  = null;
            IntentRequest intentRequest = input.Request as IntentRequest;
            ILambdaLogger lambdaLogger  = context.Logger;  // log to CloudWatch


            //S3   to be evaluated.

            //  db Connect , problem mit nicht passenden assemblys

            /* string dbconnectstring =StaticValues.SERVER+StaticValues.DATABASE+StaticValues.UID+StaticValues.PASSWORD;
             * MySqlConnection connection = new MySqlConnection(dbconnectstring);
             * MySqlCommand command = connection.CreateCommand();
             * command.CommandText = "SELECT * FROM Waren";
             * MySqlDataReader Reader;
             * connection.Open();
             * Reader = command.ExecuteReader(); */

            if (logging)
            {
                lambdaLogger.LogLine("Log started");
                lambdaLogger.LogLine("FunctionName:" + context.FunctionName + "last edited by " + StaticValues.company);
                lambdaLogger.LogLine("Log ended");
            }

            /* direktes Schreiben in eine Datei geht nicht, da es ein read-only Verzeichnis ist
             * try
             * { System.IO.File.WriteAllText("logfile.txt", "Log started from " + context.FunctionName); }
             * catch(Exception e)
             * {
             *  lambdaLogger.LogLine("Fehler bei logFile :" + e.Message);
             * }
             */



            // (Sprach)ausgabe erstellen
            skillResponse.Response.OutputSpeech = outputSpeech;

            skillResponse.Version = "1.0";
            return(skillResponse);
        }
        public async Task WriteMessageAsync(MessageEvent evnt, Target visibility)
        {
            if ((visibility & Target.CloudWatchLogs) == Target.CloudWatchLogs)
            {
                _lambdaLogger?.LogLine($"{_context.AwsRequestId}: {evnt.Message}");
            }

            if (_manager != null && (visibility & Target.Client) == Target.Client)
            {
                evnt.TargetUser = _input.UserId;
                evnt.ResourceId = _input.PhotoId;

                await _manager.SendMessage(evnt);
            }
        }
Example #13
0
        private async Task <(Guid, string)> ProcessS3File(S3Event evnt, ILambdaLogger logger)
        {
            var s3Event = evnt.Records?[0].S3;

            if (s3Event == null)
            {
                return(Guid.Empty, null);
            }

            try
            {
                if (!s3Event.Object.Key.Contains(Config.GetSection("RiskIdFilePrefix").Value))
                {
                    logger.LogLine($"File {s3Event.Object.Key} from bucket {s3Event.Bucket.Name} is not an valid file");
                    return(Guid.Empty, null);
                }

                var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key);

                Guid id = Guid.NewGuid();
                if (response != null)
                {
                    string fileName = $@"PendingProcessing/{Path.GetFileNameWithoutExtension(s3Event.Object.Key)}_{id}"
                                      + $"{Path.GetExtension(s3Event.Object.Key)}";

                    await S3Client.CopyObjectAsync(s3Event.Bucket.Name, s3Event.Object.Key, s3Event.Bucket.Name, fileName)
                    .ConfigureAwait(false);

                    await S3Client.DeleteObjectAsync(s3Event.Bucket.Name, s3Event.Object.Key).ConfigureAwait(false);

                    using (StreamReader reader = new StreamReader(
                               await S3Client.GetObjectStreamAsync(s3Event.Bucket.Name, fileName, null)))
                    {
                        var content = await reader.ReadToEndAsync();

                        return(id, content);
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogLine(e.Message);
                logger.LogLine(e.StackTrace);
                throw;
            }

            return(Guid.Empty, null);
        }
Example #14
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);
Example #15
0
        public async Task FunctionHandler(CloudWatchEC2StateChangeEvent input, ILambdaContext context)
        {
            log = context.Logger;
            log.LogLine(JsonConvert.SerializeObject(input));

            string   instanceId = input.Detail.InstanceId;
            Instance instance   = await GetInstanceDetails(instanceId);

            var tags = instance.Tags;

            log.LogLine($"Got tag keys: {string.Join(";", tags.Select(t => t.Key))}");

            string action = input.Detail.State.ToLower();

            await UpdateRoute53(instanceId, instance, tags, action);
        }
Example #16
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 Item Review(Guid id, bool goodReview)
        {
            using (var itemContext = new ItemContext()) {
                try
                {
                    var item = itemContext.Items.Single(i => i.ItemId == id);

                    if (goodReview)
                    {
                        item.ReviewGood++;
                    }

                    else
                    {
                        item.ReviewBad++;
                    }
                    itemContext.SaveChanges();
                    return(item);
                }
                catch (Exception e)
                {
                    _logger.LogLine(e.Message);
                    return(null);
                }
            }
        }
        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");
            }
        }
Example #19
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);
        }
 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);
     }
 }
Example #21
0
 public static void UpdateLogger(ILambdaLogger logger, StringBuilder sb)
 {
     Logger.WriteLine = s =>
     {
         logger.LogLine(s);
         sb?.Append(s + "\n");
     };
 }
        /// <summary>
        /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used
        /// to respond to S3 notifications.
        /// </summary>
        /// <param name="evnt"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <string> FunctionHandler(S3Event evnt, ILambdaContext context)
        {
            logger = context.Logger;
            var s3Event = evnt.Records?[0].S3;

            if (s3Event == null)
            {
                return(null);
            }

            if (evnt.Records?[0].EventName != EventType.ObjectCreatedPut)
            {
                return(null);
            }

            try
            {
                var bucketName = s3Event.Bucket.Name;
                var key        = s3Event.Object.Key;

                var response = await this.S3Client.GetObjectAsync(bucketName, key);

                logger.LogLine("Retrived Object");
                var stringReader = new StreamReader(response.ResponseStream);
                var data         = await stringReader.ReadToEndAsync();

                var dataObject = JsonConvert.DeserializeObject <Models.ObjectModel>(data);
                logger.LogLine("Deserialized Object");

                if (dataObject.State != ObjectState.UNKNOWN)
                {
                    return(null);
                }

                await ProcessData(dataObject, bucketName, key);

                return(null);
            }
            catch (Exception e)
            {
                logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
                logger.LogLine(e.Message);
                logger.LogLine(e.StackTrace);
                throw;
            }
        }
Example #23
0
        private async Task <(string, string)> GetLatLonForUserLocation(AlexaSystem system, ILambdaLogger log)
        {
            HttpClient http        = new HttpClient();
            var        accessToken = system.ApiAccessToken;
            var        deviceId    = system.Device.DeviceID;

            log.LogLine($"accessToken: {accessToken}, id:{deviceId}");
            log.LogLine($"endpoint:{system.ApiEndpoint}");

            var uri = $"https://api.amazonalexa.com/v1/devices/{deviceId}/settings/address";

            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
            var response = await http.SendAsync(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                log.LogLine($"content:{response.Content}");
                var resp = await response.Content.ReadAsStringAsync();

                log.LogLine($"Deserialization: {resp}");
                var jsonAddress    = JObject.Parse(resp);
                var street         = jsonAddress["addressLine1"];
                var city           = jsonAddress["city"];
                var state          = jsonAddress["state"];
                var googleKey      = "";
                var googleUrl      = $"https://maps.googleapis.com/maps/api/geocode/json?address={street},{city},+{state}&key={googleKey}";
                var googleResponse = await http.GetAsync(googleUrl);

                if (!googleResponse.IsSuccessStatusCode)
                {
                    return("47.611959", "-122.332893");
                }
                var json = await response.Content.ReadAsStringAsync();

                var results = JObject.Parse(json);
                var lat     = results["results"]["geometry"]["location"]["latitude"].ToString();
                var lon     = results["results"]["geometry"]["location"]["longitude"].ToString();
                return(lat, lon);
            }


            return("", "");
        }
        protected async Task <string> GetPhoneNumberType(string customerNumber, ILambdaLogger logger)
        {
            string numberType;

            try
            {
                dynamic info = await _twilioApi.LookupsApi.NumberInfo(customerNumber, "USA", "carrier");

                numberType = info.carrier.type;
                logger.LogLine($"PhoneNumber '{customerNumber}' is type '{numberType}'");
            }
            catch (ApiException ex)
            {
                logger.LogLine("PhoneNumber lookup failed: " + ex.Message);
                logger.LogLine(ex.Content ?? "(no exception data)");
                numberType = string.Empty;
            }
            return(numberType);
        }
Example #25
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);
        }
        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));
        }
Example #27
0
        private void LogMetric(string statName, string statType, string value, double sampleRate, params StatTag[] tags)
        {
            if (_random.NextDouble() < sampleRate)
            {
                var tagStrings = tags.Select(tag => tag.ToString());
                var tagString  = $"#{string.Join(",", tagStrings)}";

                _logger.LogLine(
                    $"MONITORING|{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}|{value}|{statType}|{statName}|{tagString}");
            }
        }
Example #28
0
        private SkillResponse HandleLaunch(LaunchRequest launchRequest, ILambdaLogger logger)
        {
            logger.LogLine($"LaunchRequest made");

            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = "Welcome! I am Lisa, You can ask me anything about DevOps."
            });

            return(response);
        }
Example #29
0
        private SkillResponse HandleLaunch(LaunchRequest launchRequest, ILambdaLogger logger)
        {
            logger.LogLine($"LaunchRequest made");

            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = "Welcome! You can ask me to say hello world."
            });

            return(response);
        }
Example #30
0
        private SkillResponse HandleLaunch(LaunchRequest launchRequest, ILambdaLogger logger)
        {
            logger.LogLine($"LaunchRequest made");

            var response = ResponseBuilder.Tell(new PlainTextOutputSpeech()
            {
                Text = "Alexa, please tell me you're working!"
            });

            return(response);
        }