public TwilioSMSService(IOptions<SmsSettings> smsSettings)
        {
            _smsSettings = smsSettings.Value;
            //TwilioClient.Init(_smsSettings.Sid, _smsSettings.Token);
            _restClient = new TwilioRestClient(_smsSettings.Sid, _smsSettings.Token);

        }
예제 #2
0
        public static void SendSms(string to, string message) {


            var twilio = new TwilioRestClient(TwilioAccountSid, TwilioAuthToken);
            twilio.SendMessage(FromNumber, to, message);

        }
        private void OnTimer(object sender, ElapsedEventArgs e)
        {
            try
            {
                EventLog.WriteEntry("Checking for new bark", EventLogEntryType.Information);
                var newLatestBark = GetLatestBark().GetAwaiter().GetResult();
                if (newLatestBark != null && (LatestBark == null || newLatestBark.Id != LatestBark.Id))
                {
                    EventLog.WriteEntry("Sending new bark: " + newLatestBark.Bark, EventLogEntryType.Information);

                    if (!string.IsNullOrWhiteSpace(TwilioAccountSid) && !string.IsNullOrWhiteSpace(TwilioAuthToken))
                    {
                        var twilioClient = new TwilioRestClient(TwilioAccountSid, TwilioAuthToken);
                        twilioClient.SendMessage(TwilioSenderNumber, TwilioRecipentNumber, "🐶 " + newLatestBark.Bark);
                    }
                    else
                    {
                        EventLog.WriteEntry("Twilio account SID or AuthToken not configured", EventLogEntryType.Warning);
                    }

                    LatestBark = newLatestBark;
                }
            }
            catch (Exception exception)
            {
                EventLog.WriteEntry(exception.Message, EventLogEntryType.Error);
            }
        }
예제 #4
0
파일: TwilioHelper.cs 프로젝트: bvcms/bvcms
        public static List<TwilioNumber> GetUnusedNumberList()
        {
            var available = new List<TwilioNumber>();

            var twilio = new TwilioRestClient(GetSid(), GetToken());
            var numbers = twilio.ListIncomingPhoneNumbers();

            var used = (from e in DbUtil.Db.SMSNumbers
                        select e).ToList();

            for (var iX = numbers.IncomingPhoneNumbers.Count() - 1; iX > -1; iX--)
            {
                if (used.Any(n => n.Number == numbers.IncomingPhoneNumbers[iX].PhoneNumber))
                    numbers.IncomingPhoneNumbers.RemoveAt(iX);
            }

            foreach (var item in numbers.IncomingPhoneNumbers)
            {
                var newNum = new TwilioNumber();
                newNum.Name = item.FriendlyName;
                newNum.Number = item.PhoneNumber;

                available.Add(newNum);
            }

            return available;
        }
예제 #5
0
 static void SendTextMessage(string text)
 {
     string AccountSid = REMOVED_KEY;
     string AuthToken = REMOVED_TOKEN;
     var twilio = new TwilioRestClient(AccountSid, AuthToken);
     var message = twilio.SendSmsMessage("+14155085433", REMOVED_PHONE_NUMBER_TO, text, "");
 }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        string AuthToken = "your_auth_token";
        var twilio = new TwilioRestClient(AccountSid, AuthToken);

        // Generate a random, unique code
        var uniqueCode = "1234567890";

        // Normally, we would call twilio.SendMessage() to send an SMS
        // But it doesn't support passing the ProvideFeedback parameter.
        var request = new RestRequest("Accounts/" + AccountSid + "/Messages.json", Method.POST);
        request.AddParameter("From", "+15017250604");
        request.AddParameter("To", "+15558675309");
        request.AddParameter("Body", "Open to confirm: http://yourserver.com/confirm?id=" + uniqueCode);
        request.AddParameter("ProvideFeedback", true);
        var response = twilio.Execute(request);

        var message = JsonConvert.DeserializeObject<Message>(response.Content,
            new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });

        Console.WriteLine("We should save this to a database:");
        Console.WriteLine("Unique Code = " + uniqueCode);
        Console.WriteLine("Message SID = " + message.Sid);
    }
예제 #7
0
파일: TwilioHelper.cs 프로젝트: bvcms/bvcms
        public static List<IncomingPhoneNumber> GetNumberList()
        {
            var twilio = new TwilioRestClient(GetSid(), GetToken());
            var numbers = twilio.ListIncomingPhoneNumbers();

            return numbers.IncomingPhoneNumbers;
        }
예제 #8
0
 public static void SendTextMessage(string message)
 {
     TwilioRestClient twilioClient = new TwilioRestClient
         (ConfigurationManager.AppSettings["TwilioAcccountSid"], ConfigurationManager.AppSettings["TwilioAuthToken"]);
     twilioClient.SendSmsMessage(ConfigurationManager.AppSettings["TwilioSenderPhone"],
         ConfigurationManager.AppSettings["TwilioReceiverPhone"], message);
 }
        public static void SendSmsToAllInvolved(int orderId, string action)
        {
            IstokDoorsDBContext db = new IstokDoorsDBContext();

            var employeesToInform = db.Employees.Where(i => i.IsSmsInformed == true).ToList();

            string messageText;

            if (action == "ship")
            {
                messageText = " Заказ " + orderId + " oтправлен! Проверьте Журнал Учёта Складских Запасов для дополнительной информации.";
            }
            else
            {
                messageText = " Заказ " + orderId + " oтменён! Проверьте Журнал Учёта Складских Запасов для дополнительной информации.";
            }

            var twilio = new TwilioRestClient(TwilioSender.AccountSid, TwilioSender.AuthToken);

            if (employeesToInform != null)
            {
                foreach (var employee in employeesToInform)
                {
                    var message = twilio.SendMessage(TwilioSender.PhoneNumber, employee.PhoneNumber1, messageText, "");
                }

            }
        }
예제 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string fromNumber = Request["From"];
            string toNumber = Request["To"];
            string smsBody = Request["Body"];

            //check for invalid requests
            if (string.IsNullOrEmpty(smsBody))
                return;

            var twilio = new TwilioRestClient(TWILIO_ACCOUNT_ID, TWILIO_AUTH_TOKEY);

            //Parse the message body, get the language
            SmsMessage smsMsg = new SmsMessage(smsBody);

            //Get the Google translation controller
            GoogleTranslateController translateController = new GoogleTranslateController();

            //Get the language of the sms.
            string smsLanguageCode = translateController.DetectLanguage(smsMsg.Content);

            //Get the target language code.
            string targetLanguageCode = translateController.GetLanguageCode(smsMsg.Language, smsLanguageCode);

            //Get the translated message
            string translatedMessage = translateController.TranslateText(smsMsg.Content, targetLanguageCode);
            translatedMessage = HttpUtility.HtmlDecode(translatedMessage);
            var message = twilio.SendMessage(toNumber, fromNumber, translatedMessage, "");
        }
        //
        // GET: /SendMessages/
        public ActionResult Index()
        {
            bool messages = true;

            while (messages)
            {
                string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=AccountName;AccountKey=ACCOUNTKEY";

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
                CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
                CloudQueue queue = queueClient.GetQueueReference("messages");
                CloudQueueMessage retrievedMessage = queue.GetMessage();

                if (retrievedMessage == null)
                {
                    messages = false;
                }

                string phone = retrievedMessage.AsString;

                var twilio = new TwilioRestClient("accountSid", "authToken");
                var call = twilio.InitiateOutboundCall("+YOURTWILIONUMBER", phone, "http://YOURSITE.azurewebsites.net/LookupCompliment/");

                queue.DeleteMessage(retrievedMessage);

            }

            return View("Complete!");
        }
예제 #12
0
        public TwilioProvider(string accountSid, string authToken)
        {
            this.authToken = authToken;
            this.accountSid = accountSid;

            client = new TwilioRestClient(accountSid, authToken);
        }
        public bool SendSMS(string number, string message)
        {
            var settings = _accountSettings.GetVoiceSettings();
            var client = new TwilioRestClient(settings.AccountSid, settings.AuthToken);

            if (number.IndexOf('+') < 0)
            {
                number = "+" + number.Trim();
            }

            var smsNumber = WebConfigurationManager.AppSettings["TwilioNumber"];
            var result = client.SendMessage(smsNumber, number, message);
            if (result.RestException != null)
            {
                _logger.Error($"Exception thrown sending SMS to {number}.  Ex - {result.RestException.Message}");
            }

            if (result.Status != "queued")
            {
                _logger.Error($"SMS sent status - {result.Status}, {result.ErrorMessage}");
            }

            _logger.Debug($"Sending SMS to {number} with content {message}");
            return result.Status == "queued";
        }
예제 #14
0
        public TwilioSMSMessage SendSMS(string fromNumber, string toNumber, string text)
        {
            var twilio = new TwilioRestClient(SID, AuthToken);

            try
            {
                var response = twilio.SendSmsMessage(fromNumber, toNumber, text);

                if (response != null)
                {
                    var message = new TwilioSMSMessage();

                    if (response.RestException != null)
                    {
                        message.ErrorCode = response.RestException.Code;
                        message.ErrorMessage = response.RestException.Message;
                    }
                    else
                        message.InjectFrom(response);

                    return message;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return null;
        }
예제 #15
0
파일: TwilioHelper.cs 프로젝트: mbgreen/GHV
        public static Twilio.Message SendSms(string number, string content)
        {
            var formattedNumber = FormatPhoneNumber(number);
            var restClient = new TwilioRestClient(_config.GetString(ACCOUNT_SID_KEY), _config.GetString(AUTH_TOKEN_KEY));

            return restClient.SendMessage(_config.GetString(PHONE_NUMBER_KEY), formattedNumber, content);
        }
예제 #16
0
 /// <summary>
 /// This action return the information about one sended Message
 /// </summary>
 /// <param name="MessageSid">id of Message</param>        
 public ActionResult GetMessageById(string MessageSid)
 {
     var twilio = new TwilioRestClient(AccountSid, AuthToken);
       var message = twilio.GetMessage(MessageSid);
       ViewBag.temp = message;
       return View();
 }
        //
        // GET: /Subscription/
        public ActionResult Index(string From, string To, string Body)
        {
            TwilioRestClient twilio;
            SMSMessage text;

            PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
            string oldFrom = From;

            try
            {
                From = phoneUtil.Parse(Body, "US").NationalNumber.ToString();

                twilio = new TwilioRestClient("accountSid", "authToken");
                text = twilio.SendSmsMessage("+YOURTWILIONUMBER", oldFrom, "You're so thoughtful. Steve will call your friend soon!");
            }
            catch (NumberParseException e)
            {

            }

            string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=AccountName;AccountKey=ACCOUNTKEY";

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = queueClient.GetQueueReference("messages");
            queue.CreateIfNotExist();
            CloudQueueMessage message = new CloudQueueMessage(From);
            queue.AddMessage(message, new TimeSpan(1, 0, 0), new TimeSpan(0, 1, 0));

            twilio = new TwilioRestClient("accountSid", "authToken");
            text = twilio.SendSmsMessage("+YOURTWILIONUMBER", From, "Sorry you're not feeling well. You'll soon hear from Steve! If you want Steve to call a friend just send their number!");

            return View();
        }
예제 #18
0
        public void lanzar()
        {
            try
            {
                // Find your Account Sid and Auth Token at twilio.com/user/account
                string AccountSid = "AC5ee97f763eb14e6754a03570fcd1b269";
                string AuthToken = "3fec4bfd5ff5cd6379df62ac78a0e460";
                var twilio = new TwilioRestClient(AccountSid, AuthToken);

                string url = "http://tiendapasteleria.esy.es/texttospeechc.php?Message%5B0%5D=";
                url += "Estimado " + ped.contacto_nom + " " + ped.contacto_ape + " este es un mensaje de la pasteleria San Elias. Le Notificamos que su pedido numero " + ped.idpedido + " esta " + ped.estado.descrip + " .Que tenga un buen dia";
                url = url.Replace(" ", "%20");

                // Build the parameters
                var options = new CallOptions();
                options.Url = url;
                options.To = "+51" + "979085281";
                options.From = "+12019890396";

                var call = twilio.InitiateOutboundCall(options);
                Console.WriteLine(call.Sid);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
예제 #19
0
		/// <summary>
		/// Initiate a new outgoing call
		/// </summary>
		/// <param name="from">The phone number to call from</param>
		/// <param name="to">The phone number to call to</param>
		/// <param name="url">The TwiML URL to use for controlling this call</param>
		/// <param name="statusCallback">The URL to notify upon completion of the call</param>
		/// <param name="statusCallbackMethod">The HTTP method to use when requesting the statusCallback URL</param>
		/// <param name="fallbackUrl">The URL to request upon encountering an in-call error</param>
		/// <param name="fallbackMethod">The HTTP method to use when requesting the fallbackUrl</param>
		/// <param name="ifMachine">The action to take when encountering an answering machine</param>
		/// <param name="sendDigits">The DTMF touch tone digits to transmit when the call is answered</param>
		/// <param name="timeout">The amount of time to allow a call to ring before ending</param>
		/// <returns>A Call Instance resource</returns>
		public static Call MakeCall(string from, string to, string url, string statusCallback,
									string statusCallbackMethod, string fallbackUrl, string fallbackMethod,
									string ifMachine, string sendDigits, int? timeout = null)
		{
			CheckForCredentials();

			var twilio = new TwilioRestClient(AccountSid, AuthToken);

			var options = new CallOptions();
			options.From = from;
			options.To = to;

			if (!string.IsNullOrEmpty(url))
			{
				options.Url = url;
			}
			else
			{
				options.Url = HttpContext.Current.Request.Url.ToString();
			}

			options.StatusCallback = statusCallback;
			options.StatusCallbackMethod = statusCallbackMethod;
			options.FallbackUrl = fallbackUrl;
			options.FallbackMethod = fallbackMethod;
			options.IfMachine = ifMachine;
			options.SendDigits = sendDigits;
			options.Timeout = timeout;

			return twilio.InitiateOutboundCall(options);
		}
예제 #20
0
        private bool SendMessage(string toNumber,string textMsg)
        {
            try
            {
                string AccountSid = "AC04b7185526614dcdfcd8e03e0a5842a2";
                string AuthToken = "976054e44e21b91c4af357f770f325fc";
                var twilio = new TwilioRestClient(AccountSid, AuthToken);

                SMSMessage result = twilio.SendSmsMessage("+16782937535", toNumber, textMsg);

                if (result.RestException != null)
                {
                    //an exception occurred making the REST call
                    string message = result.RestException.Message;
                }

                return true;
            }
            catch (Exception)
            {
                return false;

            }
            // Find your Account Sid and Auth Token at twilio.com/user/account
        }
예제 #21
0
        public override void Execute()
        {
            var sid = EnvironmentVariableHelper.GetEnvironmentVariable(sidKey);
              var token = EnvironmentVariableHelper.GetEnvironmentVariable(tokenKey);
              var number = EnvironmentVariableHelper.GetEnvironmentVariable(numberKey);

              var client = new TwilioRestClient (sid, token);

              foreach (var reminder in In.DueReminders)
              {
            var contact = "+" + reminder.Contact;
            var result = client.SendSmsMessage(number, contact, reminder.Message);
            var error = result.RestException;
            if (error == null) {
              Out.Sent++;
            } else {
              Out.Errors++;
              Console.WriteLine(
            "SMS to {0} failed with a status of {1} and reason of {2}.",
            reminder.Contact,
            error.Status,
            error.Code + ": " + error.Message
              );
            }
              }
        }
예제 #22
0
		/// <summary>
		/// Send an SMS message
		/// </summary>
		/// <param name="from">The number to send the message from</param>
		/// <param name="to">The number to send the message to</param>
		/// <param name="body">The contents of the message, up to 160 characters</param>
		/// <param name="statusCallbackUrl">The URL to notify of the message status</param>
		/// <returns>An SMSMessage Instance resource</returns>
		public static SMSMessage SendSms(string from, string to, string body, string statusCallbackUrl)
		{
			CheckForCredentials();

			var twilio = new TwilioRestClient(AccountSid, AuthToken);
			return twilio.SendSmsMessage(from, to, body, statusCallbackUrl);	
		}
        public string SendSMS(TxtMsgOutbound txtMsgOutbound)
        {

            if (!AppConfigSvcValues.Instance.SmsSimulationMode && OnWhiteList(txtMsgOutbound.MobilePhone))
            {
                ThrottleCount++;
                if (ThrottleCount >= ThrottleMax)
                {
                    _log.Warning("MaxThrottle count exceeded: " + ThrottleMax);
                }
                else
                {
                    string msg = string.Format("Sending SMS to {0}. message: '{1}'. ThrottleCount:{2}", txtMsgOutbound.MobilePhone, txtMsgOutbound.Message, ThrottleCount);
                    _log.Info(msg);

                    var twilio = new TwilioRestClient(AppConfigSvcValues.Instance.TwilioAccountSid, AppConfigSvcValues.Instance.TwilioAuthToken);
                    Message ret = twilio.SendMessage(AppConfigSvcValues.Instance.SourcePhone, txtMsgOutbound.MobilePhone, txtMsgOutbound.Message); //FutureDev: Send async
                    _log.Info("Sent SMS, status: " + ret.Status);

                    if (ret.Status != "queued")
                        _log.Info("Error. Send to Twilio not successful. Status:" + ret.Status + " destPhone:" + txtMsgOutbound.MobilePhone);
                }
            }
            else
            {
                string reason = AppConfigSvcValues.Instance.SmsSimulationMode ? "Simulation" : "not on whitelist";
                txtMsgOutbound.NotSendReason = reason;
                _log.Info("NOT Sending SMS to " + txtMsgOutbound.MobilePhone + " at " + txtMsgOutbound.MobilePhone + ". message: '" + txtMsgOutbound.Message + "' because " + reason);
            }

            _txtMsgOutboundDal.UpdateState(txtMsgOutbound, TxtMsgProcessState.Processed);
            return txtMsgOutbound.Id;
        }
예제 #24
0
파일: Complex2.cs 프로젝트: lshain/Zuma
 private void SendSmsMessage(string username, MessageObject messageObj)
 {
     const string senderNumber = "+17245658130";
     var twilioRestClient = new TwilioRestClient("AC47c7253af8c6fae4066c7fe3dbe4433c", "[AuthToken]");
     var recipientNumber = Utils.GetNum(username);
     twilioRestClient.SendMessage(senderNumber, recipientNumber, messageObj.ShortMessage, MessageCallback);
 }
예제 #25
0
 public void SendMessage(Reminder reminder)
 {
     reminder._mobileNumber = FormatNumber(reminder._mobileNumber);
     var client = new TwilioRestClient(AccountSid, AuthToken);
     var smsMessage = client.SendSmsMessage(From, reminder._mobileNumber, reminder._message);
     LogTextResponse(smsMessage, reminder);
 }
    protected void SendPassButton_Click(object sender, EventArgs e)
    {

        string MyNum = "16093850962";
        string AcctID = "ACfe8686a211342fd1e55bb6654995c77f";
        string AuthTok = "197a4597c18dff5f22208f12151e2d64";

        TwilioRestClient clnt = new TwilioRestClient(AcctID, AuthTok); 

       clnt.SendSmsMessage(MyNum, ForgotTextBox.Text, "Yo What up");

        SqlConnection cont = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
        SqlCommand comm = new SqlCommand(@"Select Password from LoginTable where CellPhone=@CellPhone", cont);



        comm.Parameters.AddWithValue("@CellPhone", ForgotTextBox.Text);
        

        cont.Open();

        SqlDataReader DR = comm.ExecuteReader();
        //Response.Write(DR["Password"].ToString());


    }
예제 #27
0
        public Task SendAsync(IdentityMessage message)
        {
            // Twilio Begin
             var Twilio = new TwilioRestClient(
               System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
               System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"]);
             var result = Twilio.SendMessage(
               System.Configuration.ConfigurationManager.AppSettings["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 MvcPWx.ASPSMSX2.ASPSMSX2SoapClient("ASPSMSX2Soap");
            // soapSms.SendSimpleTextSMS(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"],
            //   message.Destination,
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            //   message.Body);
            // soapSms.Close();
            // return Task.FromResult(0);
            // ASPSMS End
        }
        public TwilioResponse ResponseToSms(SmsRequest request)
        {
            var response = new TwilioResponse();

              try
              {
            string outboundPhoneNumber = request.From;

            var client = new TwilioRestClient(accountSid, authToken);

            var call = client.InitiateOutboundCall(
              twilioPhoneNumber,
              outboundPhoneNumber,
              "http://refuniteivr.azurewebsites.net/api/IVREntry");

            if (call.RestException == null)
            {
              response.Sms("starting call to " + outboundPhoneNumber);
            }
            else
            {
              response.Sms("failed call to " + outboundPhoneNumber + " " + call.RestException.Message);
            }

            return response;
              }
              catch (Exception ex)
              {
            response.Sms("exception: " + ex.Message);
            return response;
              }
        }
        public TwilioCommunicationService(string accountSid, string authToken, string msgUrl)
        {
            messagingBaseUrl = msgUrl;
            _client = new TwilioRestClient(accountSid, authToken);
            _callOptions = new CallOptions();

        }
예제 #30
0
        public Task SendAsync(IdentityMessage message)
        {
            var Twilio = new Twilio.TwilioRestClient(ConfigurationManager.AppSettings["SMSSid"],
                                                     ConfigurationManager.AppSettings["SMSToken"]);

            var result = Twilio.SendMessage(ConfigurationManager.AppSettings["SMSFromPhone"], message.Destination, message.Body, "");

            // Plug in your SMS service here to send a text message.
            return(Task.FromResult(0));
        }
예제 #31
0
        /// <summary>
        /// Send the secret
        /// </summary>
        public void Send(SecurityUser user, string challengeResponse, string tfaSecret)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            else if (String.IsNullOrEmpty(challengeResponse))
            {
                throw new ArgumentNullException(nameof(challengeResponse));
            }
            else if (tfaSecret == null)
            {
                throw new ArgumentNullException(nameof(tfaSecret));
            }

            // First, does this user have a phone number
            string toNumber = user.PhoneNumber;

            if (toNumber == null)
            {
                // Get preferred language for the user
                var securityService = ApplicationServiceContext.Current.GetService <IRepositoryService <UserEntity> >();
                var userEntity      = securityService?.Find(o => o.SecurityUserKey == user.Key).FirstOrDefault();
                if (userEntity != null)
                {
                    toNumber = userEntity.Telecoms.FirstOrDefault(o => o.AddressUseKey == TelecomAddressUseKeys.MobileContact)?.Value;
                }
            }

            // To numbers fail
            if (toNumber == null || challengeResponse.Length != 4 || !toNumber.EndsWith(challengeResponse))
            {
                this.m_tracer.TraceEvent(EventLevel.Warning, "Validation of {0} failed", user.UserName);
            }
            else
            {
                try
                {
                    var client   = new TW.TwilioRestClient(this.m_configuration.Sid, this.m_configuration.Auth);
                    var response = client.SendMessage(this.m_configuration.From, toNumber, String.Format(Strings.default_body, tfaSecret));

                    if (response.RestException != null)
                    {
                        throw new Exception(response.RestException.Message ?? "" + " " + (response.RestException.Code ?? "") + " " + (response.RestException.MoreInfo ?? "") + " " + (response.RestException.Status ?? ""));
                    }
                }
                catch (Exception ex)
                {
                    this.m_tracer.TraceEvent(EventLevel.Error, "Error sending SMS: {0}", ex);
                }
            }
        }
예제 #32
0
        /// <summary>
        /// Send the secret
        /// </summary>
        public String Send(SecurityUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            // First, does this user have a phone number
            string toNumber = user.PhoneNumber;

            if (toNumber == null)
            {
                // Get preferred language for the user
                var securityService = ApplicationServiceContext.Current.GetService <IRepositoryService <UserEntity> >();
                var userEntity      = securityService?.Find(o => o.SecurityUserKey == user.Key).FirstOrDefault();
                if (userEntity != null)
                {
                    toNumber = userEntity.Telecoms.FirstOrDefault(o => o.AddressUseKey == TelecomAddressUseKeys.MobileContact)?.Value;
                }
            }

            try
            {
                // Generate a TFA secret and add it as a claim on the user
                var secret = ApplicationServiceContext.Current.GetService <ITwoFactorSecretGenerator>().GenerateTfaSecret();
                ApplicationServiceContext.Current.GetService <IIdentityProviderService>().AddClaim(user.UserName, new SanteDBClaim(SanteDBClaimTypes.SanteDBOTAuthCode, secret), AuthenticationContext.SystemPrincipal, new TimeSpan(0, 5, 0));

                var client   = new TW.TwilioRestClient(this.m_configuration.Sid, this.m_configuration.Auth);
                var response = client.SendMessage(this.m_configuration.From, toNumber, String.Format(Strings.default_body, secret));

                if (response.RestException != null)
                {
                    throw new Exception(response.RestException.Message ?? "" + " " + (response.RestException.Code ?? "") + " " + (response.RestException.MoreInfo ?? "") + " " + (response.RestException.Status ?? ""));
                }

                return($"Code sent to ******{user.PhoneNumber.Substring(user.PhoneNumber.Length - 4, 4)}");
            }
            catch (Exception ex)
            {
                this.m_tracer.TraceEvent(EventLevel.Error, "Error sending SMS: {0}", ex);
                throw new Exception($"Could not dispatch SMS code to user", ex);
            }
        }
예제 #33
-1
        public override void Run()
        {
            var client = new TwilioRestClient(Queue_Demo.Settings.accountSid, Queue_Demo.Settings.authToken);

            var queue = client.ListQueues().Queues.Where(q => q.FriendlyName == "Demo Queue").FirstOrDefault();

            if (queue!=null)
            {
                var queueSid = queue.Sid;

                var conn = new HubConnection(Queue_Demo.Settings.hubUrl);
                var hub = conn.CreateProxy("Queue");

                conn.Start();

                while (true)
                {
                    Thread.Sleep(10000);

                    var waitTime = client.GetQueue(queueSid).AverageWaitTime;

                    Debug.WriteLine(waitTime);

                    hub.Invoke("ReportAverageWait", new object[] { waitTime });
                }
            }
        }