Beispiel #1
0
        public static ActivityResult SendSmsChallenge(
            [ActivityTrigger] VerificationParameter phone,
            [Microsoft.Azure.WebJobs.Table("approval", "AzureWebJobsStorage")] CloudTable table,
            ILogger log,
            [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")]
            out CreateMessageOptions message)
        {
            try
            {
                int challengeCode = GetChallengeCode();

                log.LogInformation($"Sending verification code {challengeCode} to {phone.Payload}.");

                var entity = new ApprovalEntity(phone.OrchestrationId, "NewMember", challengeCode, EventNameSms);
                log.LogInformation(SimpleJson.SimpleJson.SerializeObject(entity));

                table.AddToTableStorageASync(entity).GetAwaiter().GetResult();
                message = new CreateMessageOptions(new PhoneNumber(phone.Payload));

                message.Body = $"Your verification code is {challengeCode:0000}";

                return(new ActivityResult {
                    HasError = false, Value = challengeCode
                });
            }
            catch (Exception ex)
            {
                message = null;
                return(new ActivityResult {
                    HasError = true, Value = ex.Message
                });
            }
        }
        public IActionResult DeleteRequest(int RID)
        {
            DateTime parsedDate;
            var      getOrder = _context.Order.FirstOrDefault(x => x.ID == RID);

            var getbakery = _context.Bakery.FirstOrDefault(x => x.Id == getOrder.BakeryID);

            parsedDate = DateTime.Parse(getOrder.Order_Date);

            var accountSid = "AC9385ee5b15020a0b41930222101b915e";
            var authToken  = "b0adb5c55ca70e17ff56de32cfe3e364";

            TwilioClient.Init(accountSid, authToken);
            string truckphoneNumber = getbakery.PhoneNumber;

            truckphoneNumber = truckphoneNumber.Remove(0, 1);
            var messageOptions = new CreateMessageOptions(
                new PhoneNumber("whatsapp:+962" + truckphoneNumber));

            messageOptions.From = new PhoneNumber("whatsapp:+14155238886");
            messageOptions.Body = "Your Flour order of " + getOrder.TotalTons + " tons has Canceled  " + parsedDate;

            var message = MessageResource.Create(messageOptions);

            _context.Order.Remove(getOrder);

            _context.SaveChanges();

            return(Ok("Order Deleted"));
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous,
                                                                  "get", "post",
                                                                  Route = null)] HttpRequest req,
                                                     [TwilioSms(AccountSidSetting = "TwilioAccountSid",
                                                                AuthTokenSetting = "TwilioAuthToken",
                                                                From = "+19073181762")] ICollector <CreateMessageOptions> messages,
                                                     ILogger log)

        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string   requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            PostData data        = JsonConvert.DeserializeObject <PostData>(requestBody);
            string   url         = $"https://www.google.com/maps/search/?api=1&query={data.Latitude},{data.Longitude}";

            log.LogInformation($"URL created - {url}");
            foreach (string toNo in data.ToNumbers)
            {
                PhoneNumber          number  = new PhoneNumber(toNo);
                CreateMessageOptions message = new CreateMessageOptions(number)
                {
                    Body = $"I'm here! {url}"
                };
                log.LogInformation($"Creating SMS message to {message.To}, message is '{message.Body}'.");
                messages.Add(message);
            }
            return(new OkResult());
        }
Beispiel #4
0
        public ActionResult Create([Bind(Include = "Id,UserName,PassWord,Email,Phone,Status")] Account account)
        {
            if (ModelState.IsValid)
            {
                var random = new Random();
                account.Status = Account.AccountStatus.INACTICE;

                var newAccount = db.Accounts.Add(account);

                db.SaveChanges();
                var code = new VerificationCode()
                {
                    AccountId = newAccount.Id,
                    Code      = random.Next(100000, 999999).ToString()
                };

                var newCode = db.VerificationCodes.Add(code);

                var accountSid = "AC6f7db6a784b209ec8a1a9b9da19c68ce";
                var authToken  = "[AuthToken]";
                TwilioClient.Init(accountSid, authToken);

                var messageOptions = new CreateMessageOptions(
                    new PhoneNumber(newAccount.Phone));
                messageOptions.MessagingServiceSid = "MG1c7f4e78f0273088ca8993888a73d3e5";
                messageOptions.Body = "Your Verification Code : " + newCode.Code;

                var message = MessageResource.Create(messageOptions);
                Console.WriteLine(message.Body);
                return(View("VerificationCode"));
                //return RedirectToAction("Index");
            }

            return(View(account));
        }
        public IActionResult ChangeRequest(int RID)
        {
            var getOrder = _context.Order.FirstOrDefault(x => x.ID == RID);

            getOrder.OrderStatues = 1;

            _context.Update(getOrder);
            _context.SaveChanges();

            var accountSid = "AC9385ee5b15020a0b41930222101b915e";
            var authToken  = "b0adb5c55ca70e17ff56de32cfe3e364";

            TwilioClient.Init(accountSid, authToken);
            var gettruck = (from x in _context.TruckDriver
                            where x.AdministratorID == getOrder.AdministratorID
                            select new
            {
                x.PhoneNumber
            }).ToList();

            for (int i = 0; i < gettruck.Count; i++)
            {
                string truckphoneNumber = gettruck.ElementAt(i).PhoneNumber;
                truckphoneNumber = truckphoneNumber.Remove(0, 1);
                var messageOptions = new CreateMessageOptions(
                    new PhoneNumber("whatsapp:+962" + truckphoneNumber));
                messageOptions.From = new PhoneNumber("whatsapp:+14155238886");
                messageOptions.Body = "Order of " + getOrder.TotalTons + " tons has Accepted " + getOrder.Order_Date + " Please deliver it ASAP !";

                var message = MessageResource.Create(messageOptions);
                Console.WriteLine(message.Body);
            }

            return(Ok("Order Accepted"));
        }
Beispiel #6
0
        public static void Run(

            [QueueTrigger(
                 "orders",
                 Connection = "AzureWebJobsStorage")]
            OrderMessage orderMessage,

            [CosmosDB(
                 databaseName: "orders",
                 collectionName: "products",
                 ConnectionStringSetting = "AzureCosmosDB",
                 Id = "{productId}",
                 PartitionKey = "{key}")]
            InventoryItem product,

            [CosmosDB(
                 databaseName: "orders",
                 collectionName: "products",
                 ConnectionStringSetting = "AzureCosmosDB")]
            out InventoryItem updatedProduct,

            [TwilioSms(
                 AccountSidSetting = "TwilioAccountSid",
                 AuthTokenSetting = "TwilioAuthToken",
                 From = "+12056289114")]
            out CreateMessageOptions smsMessage,

            [SendGrid(ApiKey = "SendGridAPIKey")] out SendGridMessage email,

            ILogger log)
        {
            try {
                // -- demo purposes only ----------------------------------------------------------
                orderMessage.email = Environment.GetEnvironmentVariable("DestinationEmail");
                orderMessage.phone = Environment.GetEnvironmentVariable("DestinationPhoneNumber");
                // --------------------------------------------------------------------------------

                smsMessage = new CreateMessageOptions(new PhoneNumber(orderMessage.phone))
                {
                    Body = string.Format("Thanks for your order, {0}!", orderMessage.name)
                };

                updatedProduct          = product;
                updatedProduct.quantity = (product.quantity - orderMessage.quantity);

                email = new SendGridMessage();
                email.AddTo(orderMessage.email);
                email.AddContent("text/html", string.Format(
                                     "Hi, {0}! Your order for \"{1}\" is processed.",
                                     orderMessage.name, product.description));
                email.SetFrom(new EmailAddress("*****@*****.**"));
                email.SetSubject("Thank you for your order!");

                log.LogInformation(orderMessage.orderId.ToString());
            }
            catch (Exception ex) {
                log.LogError("order", ex);
                throw;
            }
        }
Beispiel #7
0
        public static async Task SmsServiceBusAsync(
            [ServiceBusTrigger("communication", "sms", Connection = "AzureWebJobsServiceBus")]
            SmsMessage msg,
            [TwilioSms(AccountSidSetting = "TwilioSid", AuthTokenSetting = "TwilioToken", From = "+1 203-347-4577")] IAsyncCollector <CreateMessageOptions> options,
            ILogger log,
            CancellationToken token
            )
        {
            if (msg.Message == null)
            {
                log.LogError("message is null");
                return;
            }

            if (msg.PhoneNumber == null)
            {
                log.LogError("no phone number");
                return;
            }

            CultureInfo.DefaultThreadCurrentCulture = msg.CultureInfo;
            var messageOptions = new CreateMessageOptions(new PhoneNumber(msg.PhoneNumber))
            {
                Body = string.Format(ResourceWrapper.GetString("sms_text"), msg.Message)
            };

            if (msg.PhoneNumber.StartsWith("+972"))
            {
                messageOptions.From = "Spitball";
            }
            await options.AddAsync(messageOptions, token);
        }
Beispiel #8
0
        public HttpResponseMessage SendSMSVerycode(string phone, string msg)
        {
            var message    = CreateMessageData($"service/verycode/{phone}/{msg}");
            var accountSid = "AC4f9d7812a1eeb2e8d5e1b7008f38dff7";
            var authToken  = "a460fe4c4fde4ee44fb7b327dd1efb72";

            TwilioClient.Init(accountSid, authToken);
            var messageOptions = new CreateMessageOptions(new PhoneNumber(("+84" + phone).ToString()));

            messageOptions.From = new PhoneNumber("+16623378292");
            messageOptions.Body = msg;
            try
            {
                var result = MessageResource.Create(messageOptions);

                //Console.WriteLine(result.Body);
                return(CreateOkResponse(message, "Đã gửi 1 mã xác thức tới số máy " + phone));
            }
            catch (TwilioException e)
            {
                Console.WriteLine(e);
                if (e.ToString().Contains("The number  is unverified") || e.ToString().Contains("number  is not a valid phone number"))
                {
                    return(CreateOkResponse(message, "Số điện thoại không đúng"));
                }
                else
                {
                    return(CreateOkResponse(message, "server error"));
                }
            }
        }
        public async static Task <CreateMessageOptions> Run(
            [QueueTrigger(queueName: "game-results", Connection = "AzureWebJobsStorage")]
            GameResult gameResultFromQueue,
            [CosmosDB(databaseName: dbName, collectionName: collName, ConnectionStringSetting = conxString,
                      SqlQuery = "SELECT * FROM c WHERE c.FavoriteTeam = {Opponent}")] IEnumerable <FriendInfo> friends,
            [CosmosDB(databaseName: dbName, collectionName: collName, ConnectionStringSetting = conxString)]
            IAsyncCollector <GameResult> writeResultsToCosmos,
            //[TwilioSms(AccountSidSetting ="TwilioAccountSID",AuthTokenSetting ="TwilioAuthKey")]
            //    IAsyncCollector<CreateMessageOptions>smsMessages,
            TraceWriter log)
        {
            // First write the game result to cosmos
            await writeResultsToCosmos.AddAsync(gameResultFromQueue);

            // Make sure the Brewers won - if so, text all our friends!
            if (!gameResultFromQueue.BrewersWin)
            {
                return(null);
            }

            foreach (var friend in friends)
            {
                var msgOptions = new CreateMessageOptions(new PhoneNumber(friend.TelNumber))
                {
                    From = new PhoneNumber(GetEnvironmentVariable("TwilioFromPhone")),
                    Body = $"Yeah - the Brewers beat the {gameResultFromQueue.Opponent} again {friend.Name}!! HA HA HA HA HA!!!"
                };

                return(msgOptions);

                //await smsMessages.AddAsync(msgOptions);
            }

            return(null);
        }
        /// <summary>
        /// Creates Twilio SMS message options object from a Bot Framework <see cref="Activity"/>.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <param name="twilioNumber">The Twilio phone number assigned to the bot.</param>
        /// <returns>The Twilio message options object.</returns>
        /// <seealso cref="TwilioAdapter.SendActivitiesAsync(ITurnContext, Activity[], System.Threading.CancellationToken)"/>
        public static CreateMessageOptions ActivityToTwilio(Activity activity, string twilioNumber)
        {
            if (activity == null)
            {
                throw new ArgumentNullException(nameof(activity));
            }

            if (string.IsNullOrWhiteSpace(twilioNumber))
            {
                throw new ArgumentNullException(nameof(twilioNumber));
            }

            var mediaUrls = new List <Uri>();

            if (activity.Attachments != null)
            {
                mediaUrls.AddRange(activity.Attachments.Select(attachment => new Uri(attachment.ContentUrl)));
            }

            var messageOptions = new CreateMessageOptions(activity.Conversation.Id)
            {
                ApplicationSid = activity.Conversation.Id,
                From           = twilioNumber,
                Body           = activity.Text,
                MediaUrl       = mediaUrls,
            };

            return(messageOptions);
        }
        static void Main(string[] args)
        {
            // Find your Account Sid and Token at twilio.com/console
            const string accountSid = "ACa8574533b3e522f0137793cf2460c87d"; //"AC4874be86630d88b0295e40be2864bbda";
            const string authToken  = "8889f8f273a32a0b2656b4068572c975";   //"6bf8073bd0c85f54ce6427c65e97b893";

            TwilioClient.Init(accountSid, authToken);

            //var message = MessageResource.Create(
            //    body: "Join Earth's mightest heroes. Like Kevin Bacon.",
            //    from: new Twilio.Types.PhoneNumber("+15005550006"),
            //    to: new Twilio.Types.PhoneNumber("+919600688497")
            //);

            //Console.WriteLine(message.Sid);
            //Console.ReadLine();

            var messageOptions = new CreateMessageOptions(
                new PhoneNumber("+919600688497"));

            messageOptions.From = new PhoneNumber("+17345266121");
            messageOptions.Body = "Hi Anna Working for the Mobile token request Sample annaaa";

            var message = MessageResource.Create(messageOptions);

            Console.WriteLine(message.Body);
            Console.ReadLine();
        }
Beispiel #12
0
        internal string sendSms(sms message)
        {
            string sid = "Error";

            if (Properties.Settings.Default.sendMessage)
            {
                if (message != null)
                {
                    var messageOptions = new CreateMessageOptions(
                        new PhoneNumber(message.to));
                    messageOptions.From = new PhoneNumber(Properties.Settings.Default.fromPhone);
                    messageOptions.Body = message.message;
                    try
                    {
                        var result = MessageResource.Create(messageOptions);
                        Console.WriteLine(result.Sid);
                        sid = result.Sid;
                    }
                    catch (Exception ex)
                    {
                        logger.Write("Error Sending SMS" + ex.Message);
                        sid = "Error";
                    }
                }
            }
            else
            {
                sid = "Debug Mode - Not Sending Message";
            }
            return(sid);
        }
Beispiel #13
0
        //public Task SendAsync(IdentityMessage message)
        //{
        // Twilio Begin
        //var Twilio = new TwilioRestClient(Keys.SMSAccountIdentification,Keys.SMSAccountPassword);
        //var result = Twilio.SendMessage(Keys.SMSAccountFrom,message.Destination, message.Body);

        //Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
        //Trace.TraceInformation(result.Status);
        //Twilio doesn't currently have an async API, so return success.
        //return Task.FromResult(0);
        // Twilio End

        // ASPSMS Begin
        // var soapSms = new WebApplication1.ASPSMSX2.ASPSMSX2SoapClient("ASPSMSX2Soap");
        // soapSms.SendSimpleTextSMS(
        //   Keys.SMSAccountIdentification,
        //   Keys.SMSAccountPassword,
        //   message.Destination,
        //   Keys.SMSAccountFrom,
        //   message.Body);
        // soapSms.Close();
        // return Task.FromResult(0);
        // ASPSMS End
        //}


        public Task SendAsync(IdentityMessage message)
        {
            // Twilio Begin
            //var Twilio = new TwilioRestClient(Keys.SMSAccountIdentification,Keys.SMSAccountPassword);
            //var result = Twilio.SendMessage(Keys.SMSAccountFrom,message.Destination, message.Body);

            //Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
            //Trace.TraceInformation(result.Status);
            //Twilio doesn't currently have an async API, so return success.
            //return Task.FromResult(0);
            // Twilio End

            var accountSid = Keys.SMSAccountIdentification;
            var authToken  = Keys.SMSAccountPassword;

            TwilioClient.Init(accountSid, authToken);
            PhoneNumber from = new PhoneNumber(Keys.SMSAccountFrom);
            PhoneNumber to   = new PhoneNumber(message.Destination);

            CreateMessageOptions options = new CreateMessageOptions(to);

            options.From = from;
            options.Body = message.Body;
            var result = MessageResource.Create(options);

            return(Task.FromResult(0));
        }
Beispiel #14
0
        private async static Task <MessageResource> SendTwilioMessageAsync(string fromPhone, string callbackUrl, List <Uri> attachmentMediaUrls, string twilioNumber, string messageText)
        {
            MessageResource      response;
            CreateMessageOptions createMessageOptions = new CreateMessageOptions(new TwilioTypes.PhoneNumber(twilioNumber))
            {
                From = new TwilioTypes.PhoneNumber(fromPhone),
                Body = messageText
            };

            if (callbackUrl.IsNotNullOrWhiteSpace())
            {
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment &&
                    !callbackUrl.Contains(".ngrok.io"))
                {
                    createMessageOptions.StatusCallback = null;
                }
                else
                {
                    createMessageOptions.StatusCallback = new Uri(callbackUrl);
                }
            }

            if (attachmentMediaUrls != null && attachmentMediaUrls.Any())
            {
                createMessageOptions.MediaUrl = attachmentMediaUrls;
            }

            response = await MessageResource.CreateAsync(createMessageOptions).ConfigureAwait(false);

            return(response);
        }
        public static CreateMessageOptions Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                string requestBody = new StreamReader(req.Body).ReadToEndAsync().Result;

                // the string is coming through with extra escape characters in the string.
                string fixedBody = Regex.Unescape(requestBody);
                fixedBody = fixedBody.Substring(1);
                fixedBody = fixedBody.Substring(0, fixedBody.Length - 1);

                log.LogInformation($"Message Body: {fixedBody}");

                var predictionNotification = JsonConvert.DeserializeObject <PredictionNotification>(fixedBody);

                var message = new CreateMessageOptions(predictionNotification.ToPhoneNumber)
                {
                    Body = SMSHelper.FormatSMS(predictionNotification),
                    From = fromPhoneNumber,
                };

                return(message);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error sending SMS Message.");
            }

            return(null);
        }
Beispiel #16
0
        public Task SendAsync(IdentityMessage message)
        {
            CreateMessageOptions options = new CreateMessageOptions(new Twilio.Types.PhoneNumber(message.Destination));

            options.Body = message.Body;
            options.From = new Twilio.Types.PhoneNumber(_fromNumber);
            return(MessageResource.CreateAsync(options));
        }
Beispiel #17
0
        public static int SendSmsChallenge(
            [ActivityTrigger] string phoneNumber,
            TraceWriter log,
            [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")]
#if NETSTANDARD2_0
            out CreateMessageOptions message)
#else
            out SMSMessage message)
Beispiel #18
0
        public static void SendGoodWeatherAlert(
            [ActivityTrigger] string phoneNumber,
            ILogger log,
            [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")]
#if NETSTANDARD2_0
            out CreateMessageOptions message)
#else
            out SMSMessage message)
Beispiel #19
0
        public static void Run(
            [QueueTrigger("notificationqueue", Connection = "AzureWebJobsStorage")] string myQueueItem,
            [SendGrid(ApiKey = "SendgridAPIKey")] out SendGridMessage message,
            IBinder binder,
            [TwilioSms(AccountSidSetting = "AccountSidSetting", AuthTokenSetting = "AuthTokenSetting")] out CreateMessageOptions objsmsmessage,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            dynamic inputJson = JsonConvert.DeserializeObject(myQueueItem);

            string firstName = inputJson.FirstName;
            string lastName  = inputJson.LastName;
            string email     = inputJson.Email;
            string emailContent;

            log.LogInformation($"Email {email}, {firstName + " " + lastName}");

            message = new SendGridMessage();

            message.SetSubject("New User got registered succesfully.");
            message.SetFrom("*****@*****.**");
            message.AddTo(email, firstName + " " + lastName);

            emailContent = "Thank you <b>" + firstName + " " + lastName + "</b> for your registration.<br><br>" + "Below are the details that you have provided us<br><br>" +
                           "<b>First name:</b> " + firstName + "<br>" +
                           "<b>Last name:</b> " + lastName + "<br>" +
                           "<b>Email address:</b> " + email + "<br><br><br>" +
                           "Best Regards," + "<br>" + "Website Team";

            message.AddContent("text/html", emailContent);

            message.AddAttachment(firstName + "_" + lastName + ".log", Convert.ToBase64String(Encoding.UTF8.GetBytes(emailContent)),
                                  "text/plain",
                                  "attachment",
                                  "Logs"
                                  );

            using (var emailLogBloboutput = binder.Bind <TextWriter>(new BlobAttribute($"userregistrationmaillogs/{ inputJson.RowKey }.log")))
            {
                emailLogBloboutput.WriteLine(emailContent);
            }

            var text = config["TelephoneNumber"];

            objsmsmessage = new CreateMessageOptions(new PhoneNumber("+4540811993"))
            {
                Body = "Hello.. Thank you for getting registered.",
                From = new PhoneNumber(text)
            };
        }
 public static void SendGoodWeatherAlert(
     [ActivityTrigger] string phoneNumber,
     ILogger log,
     [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")]
     out CreateMessageOptions message)
 {
     message      = new CreateMessageOptions(new PhoneNumber(phoneNumber));
     message.Body = $"The weather's clear outside! Go take a walk!";
 }
        public static CreateMessageOptions Run([QueueTrigger("%OrderQueue%", Connection = "OrderQueueConnection")] Order data)
        {
            var message = new CreateMessageOptions(new PhoneNumber(data.MobileNumber))
            {
                Body = $"Hallo {data.Name}, danke fuer Ihre Bestellung. Sie wird nun von uns bearbeitet!",
            };

            return(message);
        }
        public static void RunSendReminderEnrollmentNotification([ActivityTrigger] string number,
                                                                 ILogger log,
                                                                 [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")] out CreateMessageOptions message)
        {
            log.LogInformation($"Sending reminder notification to mobile number {number}.");

            message      = new CreateMessageOptions(new PhoneNumber(number));
            message.Body = "Reminder to accept the terms for the rewards";
        }
Beispiel #23
0
        public static async Task SendReminder(
            [TimerTrigger("0 0 * * * *")] TimerInfo myTimer,
            [Table("reminders", Connection = "AzureWebJobsStorage")] CloudTable reminderTable,
            [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+16177670668")] IAsyncCollector <CreateMessageOptions> messages,
            [SignalR(HubName = "ReminderHub")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            // get id (hour)
            string hour = Utilities.GetEasternDateTime(log).AddMinutes(5).Hour.ToString();

            // get row by id
            var findOperation = TableOperation.Retrieve <ReminderTableEntity>(Mappings.PartitionKey, hour);
            var findResult    = await reminderTable.ExecuteAsync(findOperation);

            // check if not found
            if (findResult.Result == null)
            {
                return;
            }

            // grab current text
            var existingRow = (ReminderTableEntity)findResult.Result;
            var message     = existingRow.Message;

            // if we got something, let's do some updates
            if (!string.IsNullOrEmpty(message))
            {
                // clear current reminder text
                var existingReminder = (ReminderTableEntity)findResult.Result;
                existingReminder.Message = "";

                // update existing reminder
                var replaceOperation = TableOperation.Replace(existingReminder);
                await reminderTable.ExecuteAsync(replaceOperation);

                // create sms message
                var reminderPhone = Environment.GetEnvironmentVariable("ReminderNumber");
                var smsMessage    = new CreateMessageOptions(new PhoneNumber(reminderPhone))
                {
                    Body = message
                };

                await messages.AddAsync(smsMessage);

                log.LogInformation($"Sending reminder for hour {hour} with message {message}");

                // send client update
                var returnReminder = existingReminder.ToModel();
                var signalRMessage = new SignalRMessage
                {
                    Target    = "updateReminder",
                    Arguments = new[] { returnReminder }
                };
                await signalRMessages.AddAsync(signalRMessage);
            }
        }
        public static void SendSMS([ActivityTrigger] string taskName,
                                   ILogger log,
                                   [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")]
                                   out CreateMessageOptions message)
        {
            string toNumber = Environment.GetEnvironmentVariable("TwilioPhoneNumberTo");

            message      = new CreateMessageOptions(new PhoneNumber(toNumber));
            message.Body = $"Make sure to finish {taskName}";
        }
Beispiel #25
0
 /// <summary>
 /// Demonstrates declaratively SMS message properties with parameter binding
 /// to message properties.
 /// </summary>
 public static void ProcessOrder_Declarative(
     [QueueTrigger(@"samples-orders")] Order order,
     [TwilioSms(
          From = "{StorePhoneNumber}",
          Body = "{CustomerName}, we've received your order ({OrderId}) and have begun processing it!")]
     out CreateMessageOptions messageOptions)
 {
     // You can set additional message properties here
     messageOptions = new CreateMessageOptions(new PhoneNumber(order.CustomerPhoneNumber));
 }
Beispiel #26
0
 public static void ProcessOrder_Imperative(
     [QueueTrigger(@"samples-orders")] Order order,
     [TwilioSms] out CreateMessageOptions messageOptions)
 {
     messageOptions = new CreateMessageOptions(new PhoneNumber(order.StorePhoneNumber))
     {
         From = new PhoneNumber(order.StorePhoneNumber),
         Body = string.Format("{0}, we've received your order ({1}) and have begun processing it!", order.CustomerName, order.OrderId)
     };
 }
Beispiel #27
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "orders")] OrderReceiveRequest orderReceiveRequest,
            [CosmosDB(
                 databaseName: "%COSMOSDB_DATABASEID%",
                 collectionName: "orders",
                 ConnectionStringSetting = "COSMOSDB_CONNECTIONSTRING")] IAsyncCollector <OrderData> orderReceiveDataCollector,
            [TwilioSms(
                 AccountSidSetting = "TWILIO_ACCOUNTSIDSETTING",
                 AuthTokenSetting = "TWILIO_AUTHTOKENSETTING",
                 From = "%TWILIO_FROM%")] ICollector <CreateMessageOptions> createMessageOptionsCollector,
            ILogger logger)
        {
            logger.LogInformation($"{nameof(OrderReceive)} function processed a request.");

            var orderIdBuilderResponse =
                _orderIdBuilder.Build(
                    orderReceiveRequest.OrderId,
                    orderReceiveRequest.LocationId,
                    orderReceiveRequest.Date);

            var orderData =
                new OrderData
            {
                Id                  = orderIdBuilderResponse.Id,
                Date                = orderReceiveRequest.Date,
                OrderId             = orderReceiveRequest.OrderId,
                CustomerName        = orderReceiveRequest.CustomerName,
                CustomerPhoneNumber = orderReceiveRequest.CustomerPhoneNumber.Sanitize("[^0-9]"),
                LocationId          = orderReceiveRequest.LocationId,
                LocationIdAndDate   = orderIdBuilderResponse.LocationIdAndDate,
                ReadyAt             = orderReceiveRequest.ReadyAt
            };

            await orderReceiveDataCollector.AddAsync(orderData);

            var createMessageOptions =
                new CreateMessageOptions(
                    new PhoneNumber(orderData.CustomerPhoneNumber))
            {
                Body = Environment.GetEnvironmentVariable("ORDERRECEIVED_TEMPLATE")
            };

            createMessageOptions.Body = createMessageOptions.Body.Replace("{{CustomerName}}", orderData.CustomerName);
            createMessageOptions.Body = createMessageOptions.Body.Replace("{{ReadyAtDate}}", orderData.ReadyAt.ToShortDateString());
            createMessageOptions.Body = createMessageOptions.Body.Replace("{{ReadyAtTime}}", orderData.ReadyAt.ToShortTimeString());
            createMessageOptions.Body = createMessageOptions.Body.Replace("{{Id}}", orderData.Id);

            createMessageOptionsCollector.Add(createMessageOptions);

            var orderReceiveResponse =
                new OrderReceiveResponse(
                    orderData);

            return(new CreatedResult("", orderReceiveResponse));
        }
        public static void RunSendFinishedNotification([ActivityTrigger] UpdateStatus dataStatus,
                                                       ILogger log,
                                                       [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")] out CreateMessageOptions message)
        {
            log.LogInformation($"Sending enrollment finished notification to mobile number {dataStatus.MobileNumber}.");

            message      = new CreateMessageOptions(new PhoneNumber(dataStatus.MobileNumber));
            message.Body = dataStatus.Status == EnrollmentStatusEnum.Accepted ?
                           "Thank you for your response! You have successfully been enrolled to the Tailwind Traders Rewards program" :
                           "Thank you for your response! Your Tailwind Traders Rewards program enrollment has been cancelled";
        }
Beispiel #29
0
        public static void Run(
            [QueueTrigger("invoice-notification-request")] InvoiceNotificationRequest notificationRequest,
            [SendGrid(ApiKey = "SendGridApiKey")] out SendGridMessage email,
            [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+15005550006")] out CreateMessageOptions sms,
            ILogger log)
        {
            log.LogInformation($"[NotifyInvoiceFunc] Queue trigger. Function processed: {notificationRequest}");

            email = CreateEmail(notificationRequest);
            sms   = CreateSMS(notificationRequest);
        }
Beispiel #30
0
        public async Task Send(string recipientPhoneNumber, string messageContent)
        {
            TwilioClient.Init(_accountSid, _authenticationToken);

            var messageOptions = new CreateMessageOptions(new PhoneNumber(recipientPhoneNumber));

            messageOptions.From = new PhoneNumber(_senderPhoneNumber);
            messageOptions.Body = messageContent;

            await MessageResource.CreateAsync(messageOptions);
        }