Пример #1
0
        //--- Methods ---
        public override async Task InitializeAsync(LambdaConfig config)
        {
            Client = new AmazonPinpointClient();

            // TODO: s3 bucket for storage
            PinpointBucket = config.ReadS3BucketName("PinpointBucket");
        }
Пример #2
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="req"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <NumberValidateResponse> FunctionHandler(PhoneNumberValidationRequestModel req, ILambdaContext context)
        {
            if (req != null)
            {
                try
                {
                    using (var client = new AmazonPinpointClient())
                    {
                        var res = await client.PhoneNumberValidateAsync(new PhoneNumberValidateRequest()
                        {
                            NumberValidateRequest = new NumberValidateRequest()
                            {
                                IsoCountryCode = req.Country,
                                PhoneNumber    = req.PhoneNumber
                            }
                        });

                        if (res.HttpStatusCode == System.Net.HttpStatusCode.OK)
                        {
                            return(res.NumberValidateResponse);
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Logger.Log(ex.Message);
                    context.Logger.Log(ex.StackTrace);
                }
            }
            return(null);
        }
 public static void Main(string[] args)
 {
     using (var client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region)))
     {
         var sendRequest = new SendMessagesRequest
         {
             ApplicationId  = appId,
             MessageRequest = new MessageRequest
             {
                 Addresses = new Dictionary <string, AddressConfiguration>
                 {
                     {
                         toAddress,
                         new AddressConfiguration
                         {
                             ChannelType = "EMAIL"
                         }
                     }
                 },
                 MessageConfiguration = new DirectMessageConfiguration
                 {
                     EmailMessage = new EmailMessage
                     {
                         FromAddress = senderAddress,
                         SimpleEmail = new SimpleEmail
                         {
                             HtmlPart = new SimpleEmailPart
                             {
                                 Charset = charset,
                                 Data    = htmlBody
                             },
                             TextPart = new SimpleEmailPart
                             {
                                 Charset = charset,
                                 Data    = textBody
                             },
                             Subject = new SimpleEmailPart
                             {
                                 Charset = charset,
                                 Data    = subject
                             }
                         }
                     }
                 }
             }
         };
         try
         {
             Console.WriteLine("Sending message...");
             SendMessagesResponse response = client.SendMessages(sendRequest);
             Console.WriteLine("Message sent!");
         }
         catch (Exception ex)
         {
             Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
         }
     }
 }
Пример #4
0
 public Handler()
 {
     region            = Environment.GetEnvironmentVariable("region");
     originationNumber = Environment.GetEnvironmentVariable("originationNumber");
     projectId         = Environment.GetEnvironmentVariable("projectId");
     client            = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region));
     dBClient          = new AmazonDynamoDBClient();
     tableName         = Environment.GetEnvironmentVariable("dynamodbTable");
 }
Пример #5
0
        public async Task <IActionResult> SendTextMessage([FromBody] TextMessage model)
        {
            if (model == null || string.IsNullOrWhiteSpace(model.MessageBody) ||
                string.IsNullOrWhiteSpace(model.DestinationNumber) ||
                string.IsNullOrWhiteSpace(model.MessageType))
            {
                return(BadRequestResult(SMS));
            }

            if (!ValidationHelper.IsValidPhoneNumber(model.DestinationNumber))
            {
                return(BadRequestResult(SMS));
            }

            if (!ValidationHelper.IsValidMessageType(model.MessageType))
            {
                return(BadRequestResult(SMS));
            }

            var client = new AmazonPinpointClient(_awsCredentials, RegionEndpoint.GetBySystemName(_awsSettings.Region));

            SendMessagesRequest sendRequest =
                SendMessageRequest(SMS, model.DestinationNumber);

            sendRequest.MessageRequest.MessageConfiguration = new DirectMessageConfiguration
            {
                SMSMessage = new SMSMessage
                {
                    Body        = model.MessageBody,
                    MessageType =
                        model.MessageType
                        .ToUpper(),     //messageType can be TRANSACTIONAL or PROMOTIONAL
                }
            };
            try
            {
                SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);

                ((IDisposable)client).Dispose();
                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    return(BadRequestResult(SMS));
                }

                if (response.MessageResponse.Result[model.DestinationNumber].StatusCode != StatusCodes.Status200OK)
                {
                    return(BadRequestResult(SMS));
                }
            }
            catch
            {
                ((IDisposable)client).Dispose();
                return(BadRequestResult(SMS));
            }
            return(new OkObjectResult(new { success = true, message = $"{SMS} sent." }));
        }
Пример #6
0
        public async Task <bool> ValidateNumber(string phoneNumber)
        {
            if (string.IsNullOrWhiteSpace(phoneNumber))
            {
                return(false);
            }
            var phone = FormatPhoneNumber(phoneNumber);

            if (string.IsNullOrEmpty(phone))
            {
                return(false);
            }

            var creds = new BasicAWSCredentials(_configuration["SMSAWSCredsAccess"], _configuration["SMSAWSCredsSecret"]);

            AmazonPinpointClient pinpointClient = null;
            //with proxy
            var proxyConfig = _configuration.GetValue <string>("ProxyAddress");

            if (string.IsNullOrEmpty(proxyConfig))
            {
                var config = new AmazonPinpointConfig
                {
                    ProxyHost      = proxyConfig,
                    RegionEndpoint = Amazon.RegionEndpoint.USEast1
                };
                pinpointClient = new AmazonPinpointClient(creds, config);
            }
            else
            {
                //without proxy
                pinpointClient = new AmazonPinpointClient(creds, Amazon.RegionEndpoint.USEast1);
            }

            PhoneNumberValidateRequest phoneValidateRequest = new PhoneNumberValidateRequest
            {
                NumberValidateRequest = new NumberValidateRequest()
                {
                    PhoneNumber    = phone,
                    IsoCountryCode = "US"
                }
            };

            PhoneNumberValidateResponse phoneValidateResponse = await pinpointClient.PhoneNumberValidateAsync(phoneValidateRequest);

            if (phoneValidateResponse.HttpStatusCode == HttpStatusCode.OK)
            {
                var numberValidateResponse = phoneValidateResponse.NumberValidateResponse;
                return(numberValidateResponse != null && numberValidateResponse.PhoneTypeCode == 0);
            }
            return(false);
        }
Пример #7
0
        protected IAmazonPinpoint CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonPinpointConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonPinpointClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Пример #8
0
        private static async Task SendMessage()
        {
            using (AmazonPinpointClient client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region)))
            {
                var sendRequest = new SendMessagesRequest
                {
                    ApplicationId  = appId,
                    MessageRequest = new MessageRequest
                    {
                        Addresses = new Dictionary <string, AddressConfiguration>
                        {
                            {
                                destinationNumber,
                                new AddressConfiguration
                                {
                                    ChannelType = "SMS"
                                }
                            }
                        },
                        MessageConfiguration = new DirectMessageConfiguration
                        {
                            SMSMessage = new SMSMessage
                            {
                                Body              = message,
                                MessageType       = messageType,
                                OriginationNumber = originationNumber,
                                SenderId          = senderId,
                                Keyword           = registeredKeyword
                            }
                        }
                    }
                };
                try
                {
                    Console.WriteLine("Sending message...");
                    var response = await client.SendMessagesAsync(sendRequest).ConfigureAwait(false);

                    Console.WriteLine("Message sent!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
                }
            }
        }
Пример #9
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                CognitoAWSCredentials credentials = new CognitoAWSCredentials(poolId, RegionEndpoint.USEast1);
                var pinpoint = new AmazonPinpointClient(credentials, RegionEndpoint.USEast1);

                var installId = await AppCenter.GetInstallIdAsync();

                EndpointDemographic endpointDemographic = new EndpointDemographic
                {
                    AppVersion      = "1.0.0",
                    Locale          = "zh-hk",
                    Make            = "Microsoft",
                    Model           = "Xbox one s",
                    ModelVersion    = "19042",
                    Platform        = "xbox",
                    PlatformVersion = "19042",
                };

                PublicEndpoint publicEndpoint = new PublicEndpoint
                {
                    ChannelType = ChannelType.CUSTOM,
                    Demographic = endpointDemographic,
                    //More
                };

                string myIp = "77";//await new HttpClient().GetStringAsync("https://api.ipify.org/");

                //Maximum number of attribute keys and metric keys for each event ------ 40 per request
                Dictionary <string, string> attribute = new Dictionary <string, string>
                {
                    { "event_type", "screen" },
                    { "event_screen", "Login" },
                    { "event_category", "Profile" },
                    { "event_action", "Login" },
                    { "is_interactive", "true" },
                    { "screen_referrer", "" },   //Previous screen name
                    { "device_id", "2222-0000-0000-2222" },
                    { "event_ip", myIp },
                    { "window_width", "1920" },
                    { "window_height", "1080" },
                    { "device_platform_name", "xbox" },
                    { "location", "1" },
                    { "tagging_version", "TV 1.0.0" },
                    { "user_id", "1234567890" },
                    { "user_email", "*****@*****.**" },
                    { "user_subscription_source", "IAP" },
                    { "device_type", "TV" },
                    { "screen_inch", "" },
                    { "system_language", "EN" },
                    { "app_language", "EN" },
                    { "app_session_id", Guid.NewGuid().ToString() },          //Initialize while App open/Browser first time open VIU after software open
                    { "activity_session_id", Guid.NewGuid().ToString() },     //Change while App go to background >= 5s , Web >= 30mins
                    { "video_player_session_id", Guid.NewGuid().ToString() }, //Initialize while each time of the Video Player screen is launched.  If the current episode is finished and the next episode is auto-played, this ID should be re-generated to another value.
                    { "network_mode", "Wifi" },
                    { "category_section_name", "" },
                    { "product_id", "123456" },         //Category ID, Series ID, Episode ID, Ad ID
                    { "grid_position_identifier", "" }, //grid_id from API
                    { "grid_position", "1" },           //Grid position
                    { "grid_title", "韩剧_Grid" },
                    { "search_keyword_1", "美好的" },
                    //{"error_code", "" },
                    //{"error_message", "" },
                    { "button_name", "Play Series" },
                    { "video_play_mode", "remote" },
                    { "resolution", "1080p" },
                    { "subtitle_status", "简体中文" },
                    { "duration", "1200" },
                    { "screen_mode", "landscape" },
                    { "timeline_at", "" },//?jindu
                    //{"ad_system", "DPF" },
                    //{"ad_width", "1280" },
                    //{"ad_height", "720" },
                    //{"ad_title", "PG - 13" },
                    //{"ad_request_url", "https://www" },
                    //{"ad_space_id",  "567890"},
                };

                var   current = Package.Current;
                Event @event  = new Event
                {
                    Attributes       = attribute,
                    EventType        = "screen",
                    AppPackageName   = Package.Current.Id.Name,
                    AppTitle         = Package.Current.DisplayName,
                    AppVersionCode   = "10700",
                    SdkName          = GetAWSSDKName(pinpoint.Config.UserAgent),
                    ClientSdkVersion = GetAWSSDKVersion(pinpoint.Config.UserAgent),
                    Timestamp        = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss")
                };
                Dictionary <string, Event> events = new Dictionary <string, Event>();
                events.Add("Events", @event);

                EventsBatch eventsBatch = new EventsBatch
                {
                    Endpoint = publicEndpoint,
                    Events   = events
                };

                Dictionary <string, EventsBatch> batchItem = new Dictionary <string, EventsBatch>();
                batchItem.Add(installId.ToString(), eventsBatch);

                EventsRequest eventsRequest = new EventsRequest
                {
                    BatchItem = batchItem
                };

                PutEventsRequest putEventsRequest = new PutEventsRequest
                {
                    ApplicationId = appId,
                    EventsRequest = eventsRequest
                };

                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(new TimeSpan(0, 0, 3));
                var res = await pinpoint.PutEventsAsync(putEventsRequest, cancellationTokenSource.Token);

                if (res != null)
                {
                    Debug.WriteLine("PinPoint.PutEventsAsync: " + DateTime.UtcNow);
                    Debug.WriteLine("EndpointItemResponse: "
                                    + res?.EventsResponse?.Results[installId.ToString()]?.EndpointItemResponse.StatusCode
                                    + res?.EventsResponse?.Results[installId.ToString()]?.EndpointItemResponse.Message);
                    Debug.WriteLine("EndpointItemResponse: "
                                    + res?.EventsResponse?.Results[installId.ToString()]?.EventsItemResponse["Events"].StatusCode
                                    + res?.EventsResponse?.Results[installId.ToString()]?.EventsItemResponse["Events"].Message);
                }
            }
            catch (AmazonPinpointException ex)
            {
            }
            catch (Exception ex)
            {
            }
        }
Пример #10
0
        public async Task <IActionResult> SendEmail([FromBody] EmailModel model)
        {
            if (model == null || string.IsNullOrWhiteSpace(model.SubjectBody) || string.IsNullOrWhiteSpace(model.ToAddress) ||
                (string.IsNullOrWhiteSpace(model.HtmlBody) && string.IsNullOrWhiteSpace(model.TextBody)))
            {
                return(BadRequestResult(EMAIL));
            }

            if (!ValidationHelper.IsValidEmailAddress(model.ToAddress))
            {
                return(BadRequestResult(EMAIL));
            }

            var client = new AmazonPinpointClient(_awsCredentials, RegionEndpoint.GetBySystemName(_awsSettings.Region));

            SendMessagesRequest sendRequest =
                SendMessageRequest(EMAIL.ToUpper(), model.ToAddress);

            sendRequest.MessageRequest.MessageConfiguration = new DirectMessageConfiguration
            {
                EmailMessage = new EmailMessage
                {
                    FromAddress = _awsSettings.AwsEmail.SenderAddress,
                    SimpleEmail = new SimpleEmail
                    {
                        HtmlPart = string.IsNullOrWhiteSpace(model.HtmlBody)
                            ? null
                            : new SimpleEmailPart
                        {
                            Charset = _awsSettings.AwsEmail.CharSet,
                            Data    = model.HtmlBody
                        },
                        TextPart = !string.IsNullOrWhiteSpace(model.HtmlBody)
                            ? null
                            : new SimpleEmailPart
                        {
                            Charset = _awsSettings.AwsEmail.CharSet,
                            Data    = model.TextBody
                        },
                        Subject = new SimpleEmailPart
                        {
                            Charset = _awsSettings.AwsEmail.CharSet,
                            Data    = model.SubjectBody
                        }
                    }
                }
            };
            try
            {
                SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);

                ((IDisposable)client).Dispose();
                if (response.MessageResponse.Result[model.ToAddress].StatusCode != StatusCodes.Status200OK)
                {
                    return(BadRequestResult(EMAIL));
                }

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    return(BadRequestResult(EMAIL));
                }
            }
            catch
            {
                ((IDisposable)client).Dispose();
                return(BadRequestResult("Email"));
            }
            return(new OkObjectResult(new { success = true, message = "Email sent." }));
        }