Ejemplo n.º 1
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        // To set up environmental variables, see http://twil.io/secure
        const string accountSid   = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string authToken    = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        TwilioClient.Init(accountSid, authToken);

        var stats           = WorkspaceStatisticsResource.Fetch(workspaceSid);
        var cumulativeStats = JObject.FromObject(stats.Cumulative);

        Console.WriteLine(cumulativeStats["avg_task_acceptance_time"]);
        Console.WriteLine(cumulativeStats["tasks_entered"]);

        var tasksByStatus =
            JObject.FromObject(stats.Realtime)["tasks_by_status"].Value <JObject>();

        Console.WriteLine(tasksByStatus["pending"]);
        Console.WriteLine(tasksByStatus["assigned"]);
    }
Ejemplo n.º 2
0
        public static async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

            var accountSid = "";
            var authToken  = "";

            TwilioClient.Init(accountSid, authToken);
            try
            {
                await MessageResource.CreateAsync(
                    to : new PhoneNumber(""),
                    from : new PhoneNumber(""),
                    body : "Test");

                log.Info($"Ok at: {DateTime.Now}");
            }
            catch (ApiException)
            {
                log.Info($"Exception at: {DateTime.Now}");
            }
        }
Ejemplo n.º 3
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var tag = new List <string> {
            "new user"
        };

        var bindings = BindingResource.Read(
            startDate: MarshalConverter.DateTimeFromString("2015-08-25"),
            tag: tag,
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            );

        foreach (var record in bindings)
        {
            Console.WriteLine(record.Sid);
        }
    }
Ejemplo n.º 4
0
        // Twilio SMS notification method, requires input of a message and a phone number as +614 format
        public static void sendSMS(string message, string phone)
        {
            /// ------------------------------------------------------SUPPLIED BY TWILIO -------------------------- \\\
            // Account Information from Twilio account
            const string accountSid = "";
            const string authToken  = "";



            TwilioClient.Init(accountSid, authToken);
            // creates message and specifies numbers
            var smsMessage = MessageResource.Create(
                // contains message to be sent
                body: message,
                // Number supplied by Twilio account
                from: new PhoneNumber(""),
                // Destination number
                to: new PhoneNumber(phone)
                );

            Console.WriteLine(smsMessage.Sid);
            /// ------------------------------------------------------SUPPLIED BY TWILIO END-------------------------- \\\
        }
Ejemplo n.º 5
0
    static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid                   = "accountSid";
        const string authToken                    = "authToken";
        const string serviceSid                   = "serviceSid";
        const string friendlyName                 = "friendlyName";
        const string defaultServiceRoleSid        = "defaultServiceRoleSid";
        const string defaultChannelRoleSid        = "defaultChannelRoleSid";
        const string defaultChannelCreatorRoleSid = "defaultChannelCreatorRoleSid";
        const int    typingIndicatorTimeout       = 5;

        TwilioClient.Init(accountSid, authToken);

        var service = ServiceResource.Update(serviceSid,
                                             friendlyName,
                                             defaultServiceRoleSid,
                                             defaultChannelRoleSid,
                                             defaultChannelCreatorRoleSid,
                                             typingIndicatorTimeout: typingIndicatorTimeout);

        Console.WriteLine(service.FriendlyName);
    }
Ejemplo n.º 6
0
        public ActionResult Create([Bind(Include = "Id,Username,Password,Phone,Email,Code,Status")] User user)
        {
            if (ModelState.IsValid)
            {
                user.Code = "123456";
                db.Users.Add(user);
                db.SaveChanges();

                string accountSid = "ACab37d4ed3d187de2f6ebbeebc0760201";
                string authToken  = "40e188f7867ea9b610fbfe52cc585968";

                TwilioClient.Init(accountSid, authToken);

                var message = MessageResource.Create(
                    body: user.Code,
                    from: new Twilio.Types.PhoneNumber("+84386724333"),
                    to: new Twilio.Types.PhoneNumber(user.Phone)
                    );
                return(RedirectToAction("Confirm"));
            }

            return(View(user));
        }
Ejemplo n.º 7
0
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        // To set up environmental variables, see http://twil.io/secure
        const string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string authToken  = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        const string serviceSid = Environment.GetEnvironmentVariable("TWILIO_SERVICE_SID");
        const string identity   = "00000001";
        const string address    = "device_token";

        TwilioClient.Init(accountSid, authToken);

        var binding = BindingResource.Create(
            serviceSid,
            identity,
            BindingResource.BindingTypeEnum.Apn,
            address,
            tag: new List <string> {
            "preferred device", "new user"
        });

        Console.WriteLine(binding.Sid);
    }
Ejemplo n.º 8
0
        public static string NewAPIKey(string name)
        {
            // Find your Account Sid and Token at twilio.com/console
            // and set the environment variables. See http://twil.io/secure
            //string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
            //string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

            TwilioClient.Init(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);

            var newKey = name != null && name.Length > 0 ? NewKeyResource.Create(friendlyName: name) : NewKeyResource.Create();

            //Console.WriteLine(newKey.Sid);

            return(newKey.Sid);
            //EXAMPLE JSON API RESPONSE
            //{
            //    "sid": "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            //    "friendly_name": "User Joey",
            //    "date_created": "Mon, 13 Jun 2016 22:50:08 +0000",
            //    "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000",
            //    "secret": "foobar"
            //}
        }
Ejemplo n.º 9
0
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            // Twilio Begin
            var accountSid = ConfigurationManager.AppSettings["SMSAccountIdentification"];
            var authToken  = ConfigurationManager.AppSettings["SMSAccountPassword"];
            var fromNumber = ConfigurationManager.AppSettings["SMSAccountFrom"];

            TwilioClient.Init(accountSid, authToken);

            MessageResource result = MessageResource.Create(
                new PhoneNumber(message.Destination),
                from: new PhoneNumber(fromNumber),
                body: message.Body
                );

            //Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
            Trace.TraceInformation(result.Status.ToString());
            //Twilio doesn't currently have an async API, so return success.
            return(Task.FromResult(0));
            // Twilio End
            //return Task.FromResult(0);
        }
Ejemplo n.º 10
0
        public static string UpdateKeySource(string friendlyName)
        {
            // Find your Account Sid and Token at twilio.com/console
            // and set the environment variables. See http://twil.io/secure
            string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
            string authToken  = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

            TwilioClient.Init(accountSid, authToken);

            var key = KeyResource.Update(
                friendlyName: "friendly_name",
                pathSid: "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                );

            return(key.FriendlyName);
            //EXAMPLE JSON API RESPONSE
            //{
            //    "sid": "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            //    "friendly_name": "friendly_name",
            //    "date_created": "Mon, 13 Jun 2016 22:50:08 +0000",
            //    "date_updated": "Mon, 13 Jun 2016 22:50:08 +0000"
            //}
        }
Ejemplo n.º 11
0
        /// <summary>
        /// method to send otp to Phone
        /// </summary>
        /// <param name="otp"></param>
        /// <returns></returns>
        public int SendOtpPhone(long Otp, Users users)
        {
            string messageText = " is SECRET OTP to reset the password. OTP valid for 1 min. Please do not share OTP with anyone.";

            try
            {
                string accountSid = "AC0d53180df655ab1b8daba6d2c972f7f2";
                string authToken  = "9116b682d0940c08f11fa33140e99d04";

                TwilioClient.Init(accountSid, authToken);

                var message = MessageResource.Create(
                    body: Otp.ToString() + messageText,
                    from: new Twilio.Types.PhoneNumber("+14159686771"),
                    to: new Twilio.Types.PhoneNumber("+91" + users.PhoneNumber)
                    );
                return(1);
            }
            catch (Exception)
            {
                return(0);
            }
        }
Ejemplo n.º 12
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var data = new Dictionary <string, Object>()
        {
            { "id", "bob" },
            { "x", 256 },
            { "y", 42 }
        };

        var streamMessage = StreamMessageResource.Create(
            data: data,
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathStreamSid: "MyStream"
            );

        Console.WriteLine(streamMessage.Sid);
    }
Ejemplo n.º 13
0
        public async Task <InvokeResult> SendAsync(string number, string contents)
        {
            try
            {
                TwilioClient.Init(_settings.SmsServer.AccountId, _settings.SmsServer.AccessKey);
                var restClient = new TwilioRestClient(_settings.SmsServer.AccountId, _settings.SmsServer.AccessKey);
                await MessageResource.CreateAsync(to : new PhoneNumber(number), from : new PhoneNumber(_settings.FromPhoneNumber), body : contents);

                _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Verbose, "TwilioSMSSender_SendAsync", "EmailSent",
                                            new System.Collections.Generic.KeyValuePair <string, string>("Subject", number),
                                            new System.Collections.Generic.KeyValuePair <string, string>("to", contents));

                return(InvokeResult.Success);
            }
            catch (Exception ex)
            {
                _adminLogger.AddException("SendGridEmailServices_SendAsync", ex,
                                          new System.Collections.Generic.KeyValuePair <string, string>("number", number),
                                          new System.Collections.Generic.KeyValuePair <string, string>("contents", contents));

                return(InvokeResult.FromException("TwilioSMSSender_SendAsync", ex));
            }
        }
Ejemplo n.º 14
0
        // Twilio SMS notification method, requires input of a message and a phone number as +614 format
        // no-a-touchytouchy
        public static void sendSMS(string message, string phone)
        {
            /// ------------------------------------------------------SUPPLIED BY TWILIO -------------------------- \\\
            // Account Information from Twilio account
            const string accountSid = "ACb3c8b45d687f30b390eace020d89fe75";
            const string authToken  = "964f618c7094b7051e85fb65d13c676d";



            TwilioClient.Init(accountSid, authToken);
            // creates message and specifies numbers
            var smsMessage = MessageResource.Create(
                // contains message to be sent
                body: message,
                // Number supplied by Twilio account
                from: new PhoneNumber("+61447465857"),
                // Destination number
                to: new PhoneNumber(phone)
                );

            Console.WriteLine(smsMessage.Sid);
            /// ------------------------------------------------------SUPPLIED BY TWILIO END-------------------------- \\\
        }
Ejemplo n.º 15
0
        public static async Task <string> StartPhoneVerificationAsync(string phoneNumber, string countryCode)
        {
            if (Env.Production)
            {
                string accountSid    = TwilioConfig.AccountSid;
                string authToken     = TwilioConfig.AuthToken;
                string pathServiceID = TwilioConfig.ServiceSid;

                TwilioClient.Init(accountSid, authToken);

                var verification = VerificationResource.Create(
                    to: "+" + countryCode + phoneNumber,
                    channel: "sms",
                    pathServiceSid: pathServiceID
                    );

                return("success");
            }
            else
            {
                return("success");
            }
        }
Ejemplo n.º 16
0
        public static bool SendMessage(string phone, ref string password, bool checkContent)
        {
            // Find your Account Sid and Token at twilio.com/console
            const string accountSid = "AC66f30d814454e464a8777365b4cb7170";
            const string authToken  = "cbf88a0c476adcdb73995db45cc9fdc5";

            password = PasswordGenerate(6);

            TwilioClient.Init(accountSid, authToken);
            try
            {
                if (checkContent)
                {
                    var message = MessageResource.Create(
                        body: "Код для подтверждения : " + password,
                        from: new Twilio.Types.PhoneNumber("+18654019192"),
                        to: new Twilio.Types.PhoneNumber(phone)
                        );
                }
                else
                {
                    var message = MessageResource.Create(
                        body: "Ваш аккаунт был удален! TRIGGERED",
                        from: new Twilio.Types.PhoneNumber("+18654019192"),
                        to: new Twilio.Types.PhoneNumber(phone)
                        );
                }
            }
            catch (Twilio.Exceptions.ApiException)
            {
                Clear();
                WriteLine("Такого телефона не найдено!");
                ReadKey();
                return(false);
            }
            return(true);
        }
Ejemplo n.º 17
0
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        // To set up environmental variables, see http://twil.io/secure
        const string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string authToken  = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        const string serviceSid = Environment.GetEnvironmentVariable("TWILIO_SERVICE_SID");

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            Number = "001",
            Name   = "Bulbasaur",
            Attack = 49
        };

        var item = SyncListItemResource.Create(serviceSid,
                                               "MyCollection",
                                               data,
                                               864000); // expires in 10 days

        Console.WriteLine(item.Index);
    }
Ejemplo n.º 18
0
        public List <MessageResource> GetMessagesFromTwilio(PluginConfig pluginConfig, int secondsAgo)
        {
            this.Log.LogDebug("Starting GetMessagesFromTwilio");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            TwilioClient.Init(pluginConfig.AccountSID, pluginConfig.AuthToken);

            ReadMessageOptions options = new ReadMessageOptions
            {
                To            = new PhoneNumber(pluginConfig.FromNumber),
                DateSentAfter = DateTime.Now.AddSeconds(secondsAgo * -1)
            };

            ResourceSet <MessageResource> messages = MessageResource.Read(options);

            foreach (MessageResource message in messages)
            {
                string from    = message.From.ToString();
                string body    = message.Body;
                string created = message.DateCreated.GetValueOrDefault(DateTime.MinValue).ToLongDateString();
                this.Log.LogDebug(string.Format("From: {0}, created: {1}, body: {2}", from, created, body));
            }

            return(messages.Where((message) => message.DateCreated.GetValueOrDefault(DateTime.MinValue).CompareTo(options.DateSentAfter) >= 0).ToList());
        }
Ejemplo n.º 19
0
        // To trigger at 8 AM everyday use this : "0 0 8 * * 1-5"
        // To trigger at 9:30 AM everyday use this : "0 30 9 * * 1-5"
        // Currently set to run every 5 minutes :
        public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

            // Initialize O16N params
            string webNodeUri = "http://<server-ip-address>:12800";
            string username   = "******";
            string password   = "******";

            // Login, Obtain access token and set header
            UserApi       userInstance = new UserApi(webNodeUri);
            var           token        = userInstance.Login(new LoginRequest(username, password));
            Configuration config       = new Configuration(new ApiClient(webNodeUri), new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Authorization", $"Bearer {token.AccessToken}" }
            });

            // Call ManualTransmissionService and log output to console window
            WeatherServiceApi instance             = new WeatherServiceApi(config);
            InputParameters   webServiceParameters = new InputParameters(47.648445m, -122.145028m);
            WebServiceResult  response             = instance.GetWeatherReport(webServiceParameters);

            // Parsing the Weather Report Json for current Temperature in Celsius
            var reportJson           = response.OutputParameters.Report;
            var obj                  = JObject.Parse(reportJson);
            var temperatureInKelvin  = obj["list"][0]["main"]["temp"];
            var temperatureInCelsius = Convert.ToInt32(temperatureInKelvin) - 273;

            // SMS the temperature
            TwilioClient.Init("<username>", "<password>");
            var message = MessageResource.Create(
                new PhoneNumber("<phone number>"),
                from: new PhoneNumber("<phone number>"),
                body: $"Temperature : {temperatureInCelsius}�C"
                );
        }
Ejemplo n.º 20
0
        public string SendSMSMessage(string toMobilePhone, string messageToSend)
        {
            var _twilio_Account_SID  = _configuration["Twilio_Account_SID"];
            var _twilio_Auth_TOKEN   = _configuration["Twilio_Auth_TOKEN"];
            var _twilio_Phone_Number = _configuration["Twilio_Phone_Number"];

            TwilioClient.Init(
                _twilio_Account_SID,
                _twilio_Auth_TOKEN
                );

            if (messageToSend.Length > 6)
            {
                messageToSend = messageToSend.Substring(0, 6);
            }

            var message = MessageResource.Create(
                from: new PhoneNumber(_twilio_Phone_Number),
                to: new PhoneNumber("+58" + toMobilePhone),
                body: messageToSend
                );

            return(message.Sid);
        }
Ejemplo n.º 21
0
        public int SendMessage(string phoneNumber)
        {
            const string accountSid = "ACdcc801525e5a94284004100706d3f503";
            const string authToken  = "4429b063acb6af1f7907a8a9ffa15052";

            TwilioClient.Init(accountSid, authToken);

            var randomNumber    = new Random();
            var verificationKey = randomNumber.Next(1000, 9999);

            try
            {
                var message = MessageResource.Create(
                    from: new Twilio.Types.PhoneNumber("+16504926746"),
                    body: verificationKey.ToString(),
                    to: new Twilio.Types.PhoneNumber(phoneNumber)
                    );
            }
            catch (Exception)
            {
                return(-1);
            }
            return(verificationKey);
        }
 public IActionResult DirectMessage(Messages messages)
 {
     try
     {
         string accountSid = _configuration.GetSection("TwilioAccountDetails")["AccountSid"];
         string authToken  = _configuration.GetSection("TwilioAccountDetails")["AuthToken"];
         if (accountSid != null && authToken != null)
         {
             TwilioClient.Init(accountSid, authToken);
             var message = MessageResource.Create(
                 body: $"{messages.Body} (Do not reply)",
                 from: new Twilio.Types.PhoneNumber("+13134665096"),
                 to: new Twilio.Types.PhoneNumber($"+1{messages.To}")
                 );
             Console.WriteLine(message.Sid);
         }
         return(Redirect("/Friend/ListOfFriends"));
     }
     catch
     {
         ViewBag.Error = "Message could not be sent.";
         return(View(messages));
     }
 }
        public int SendOTPhelper(string recipientNumber, string messagebody)
        {
            int    otpValue         = new Random().Next(100000, 999999);
            string TwilioAccountSid = "AC221d2da9b22726fc518e34ae50b41b5f";
            string TwilioAuth       = "362cd71611a4148adfad53cbcfcec040";
            string TwilioNumber     = "+12182755700";

            recipientNumber = "+13194997346";
            messagebody     = "Your OTP is " + otpValue + " sent by:sams project";

            try{
                TwilioClient.Init(TwilioAccountSid, TwilioAuth);
                var msgresult = MessageResource.Create(
                    to: new PhoneNumber(recipientNumber),
                    from: new PhoneNumber(TwilioNumber),
                    body: messagebody);
                return(otpValue);
            }

            catch (Exception e)
            {
                throw (e);
            }
        }
        public void SendMessageToTwilio(PluginConfig pluginConfig, SendMessageActionConfig messageConfig)
        {
            this.Log.LogDebug("Starting SendMessageToTwilio");

            PhoneNumber to;
            PhoneNumber from    = new PhoneNumber(pluginConfig.FromNumber);
            string      message = messageConfig.Message;

            if (message == null || message.Length == 0)
            {
                this.Log.LogWarning("No message configured! Message won't send");
                return;
            }
            if (messageConfig.ToNumber == null || messageConfig.ToNumber.Length == 0)
            {
                this.Log.LogWarning("No 'To' number configured! Message won't send");
                return;
            }
            else
            {
                to = new PhoneNumber(HS.ReplaceVariables(messageConfig.ToNumber));
            }

            message = HS.ReplaceVariables(message);


            TwilioClient.Init(pluginConfig.AccountSID, pluginConfig.AuthToken);

            var publishedMessage = MessageResource.Create(
                to: to,
                from: from,
                body: message
                );

            this.Log.LogInfo("Published message with Sid: " + publishedMessage.Sid);
        }
Ejemplo n.º 25
0
        public OTPMessage SendSMS(string userName)
        {
            OTPMessage   oMessage   = new OTPMessage();
            const string accountSid = "ACedd85e0a7458ffa36d3b957ab5df33d7";
            const string authToken  = "88002d9d184903e55164ad373b1a0cfc";

            TwilioClient.Init(accountSid, authToken);
            Random generator = new Random();
            String otp       = generator.Next(0, 1000000).ToString("D6");

            try
            {
                var customer = customerService.GetUsers(userName);
                if (customer.Count > 0)
                {
                    var to      = new PhoneNumber(customer[0].Country + customer[0].PhonePersonal);
                    var message = MessageResource.Create(
                        to,
                        from: new PhoneNumber("+15592967092"),         //  From number, must be an SMS-enabled Twilio number ( This will send sms from ur "To" numbers ).
                        body: $"Hello {userName} !!Your CMS verification code is:" + otp);
                    customerService.UpdateOTP(userName, otp, false);
                    oMessage.Message = "Verification code has been sent to your register mobile number";
                    return(oMessage);
                }
                else
                {
                    oMessage.Message = "User not found.";
                    return(oMessage);
                }
            }
            catch (Exception ex)
            {
                oMessage.Message = ex.Message;
                return(oMessage);
            }
        }
        public async Task SendNotificationAsync(NotificationMessage message)
        {
            if (!CanSend(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

            TwilioClient.Init(_options.AccountId, _options.AccountPassword);

            var smsNotificationMessage = message as SmsNotificationMessage;

            try
            {
                await MessageResource.CreateAsync(
                    body : smsNotificationMessage.Message,
                    from : new PhoneNumber(_smsSendingOptions.SmsDefaultSender),
                    to : smsNotificationMessage.Number
                    );
            }
            catch (ApiException ex)
            {
                throw new SentNotificationException(ex);
            }
        }
        /// <summary>
        /// Plug in your SMS service here to send a text message.
        /// テキスト メッセージを送信するための SMS サービスをここにプラグインします。</summary>
        /// <param name="message">message</param>
        /// <returns>非同期操作</returns>
        public Task SendAsync(IdentityMessage message)
        {
            if (ASPNETIdentityConfig.IsDebug)
            {
                // Debug.WriteLine
                Debug.WriteLine("< SmsService >");
                Debug.WriteLine("Destination : " + message.Destination);
                Debug.WriteLine("Subject     : " + message.Subject);
                Debug.WriteLine("Body        : " + message.Body);
            }
            else
            {
                TwilioClient.Init(
                    ASPNETIdentityConfig.TwilioAccountSid,
                    ASPNETIdentityConfig.TwilioAuthToken);

                MessageResource mr = MessageResource.Create(
                    to: new PhoneNumber("+" + message.Destination), // "+819074322014"
                    from: new PhoneNumber(ASPNETIdentityConfig.TwilioFromPhoneNumber),
                    body: message.Body);
            }

            return(Task.FromResult(0));
        }
Ejemplo n.º 28
0
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            string accountSid = ConfigurationManager.AppSettings["SMSAccountIdentification"];

            string authToken = ConfigurationManager.AppSettings["SMSAccountPassword"];

            string fromNumber = ConfigurationManager.AppSettings["SMSAccountFrom"];

            // Initialize the Twilio client

            TwilioClient.Init(accountSid, authToken);

            MessageResource result = MessageResource.Create(

                from: new PhoneNumber(fromNumber),

                to: new PhoneNumber(message.Destination),

                body: message.Body);


            return(Task.FromResult(0));
        }
Ejemplo n.º 29
0
 static void Main(string[] args)
 {
     Console.WriteLine(" -- Telecommunication Scammer Flooder -- v1.0");
    
     Console.WriteLine("Enter the number to flood(+1 MUST BE IN FRONT!)");
     NumToCall = Console.ReadLine();
     Console.WrtieLine("Press Enter to start the flooder, Otherwise exit the application right now...")
     Console.ReadLine();
     Console.Clear();
     TwilioClient.Init(accountsid, authtoken);
    
     var count = 1;
     do
     {
         Console.WriteLine("Starting Call Batch " + count.ToString() + " (" + numbers.Count | " Nums.)"
         /*not sure what this first word is*/(string num in numbers)
         {
             Call(num);
             System.Threading.Thread.Sleep(1000);
         }
         count++;
         System.Threading.Thread.Sleep(5000);
     }while(true);
 }
Ejemplo n.º 30
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var to   = new PhoneNumber("+14155551212");
        var from = new PhoneNumber("+18668675310");
        var statusCallbackEvents = new List <string>()
        {
            "initiated", "ringing", "answered", "completed"
        };
        var call = CallResource.Create(
            to,
            from,
            url: new Uri("http://demo.twilio.com/docs/voice.xml"),
            statusCallback: new Uri("https://www.myapp.com/events"),
            statusCallbackMethod: HttpMethod.Post,
            statusCallbackEvent: statusCallbackEvents);

        Console.WriteLine(call.Sid);
    }
        // POST: api/Notifications
        /*  [Route("api/v1/notifications", Name = "PostNotifications")]*/
        public async Task<IHttpActionResult> Post([FromBody]NotificationDTO notificaton)
        {


            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var parsedAccidentId = APIURLParserV1.ParseResouceURIForPrimaryKeyValue(notificaton.Accident);
            var existingObjectInDb = _db.Accidents.Include(x => x.Customer).FirstOrDefault(x => x.Id == parsedAccidentId);

            if (existingObjectInDb == null)
            {
               
GenerateBaseLog(ApiLogType.Warning,
  LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
  GetType(), GetCaller());
                return BadRequest("The supplied Accident was not found.");
            }


            try
            {
                if (await _dataAccessAuthoriser.AuthoriseAccessToClientData(principal, existingObjectInDb.Customer))
                {

                    if (ModelState.IsValid)
                    {

                        var theCustomer = existingObjectInDb.Customer;
                        var theAccident = existingObjectInDb;
                        //try and get the customer 
                        var theNotificationToSave = new ExternalNotification();
                        CustomerViewModel customer = null;
                        theNotificationToSave.Accident = existingObjectInDb;

                        //do something based on notification strategy:


                        //todo:replace with proper stragegy - all take return void as are command. 


                        if (notificaton.NotificationType == NotificationType.AccidentEmail)
                        {
                            theNotificationToSave.NotificationType = NotificationType.AccidentEmail;
                            //get address
                            var address = existingObjectInDb.Customer.EmergencyEmailContact;
                            theNotificationToSave.To = address;

                            if (!String.IsNullOrEmpty(address))
                            {
                                //automailer 
                                var respondants = new List<string>();
                                respondants.Add(address);


                                var GmailLessSecureMailService = new AxiappMailService();




                                if (
                                    GmailLessSecureMailService.SendMessage(respondants, "Axiapp - An accident has occurred",
                                        String.Format(
                                            "<h1>Oh my God, there's been a horrific smash at {0} and everyone's dead!</h1>",
                                            DateTime.Now)))
                                {
                                    theNotificationToSave.Result = "Success";
                                    theNotificationToSave.Created = DateTime.Now;


                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));


                                   
                                        GenerateBaseLog(ApiLogType.Information,
                                            LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created,
                                                __loggingResourceName),
                                            GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }
                                else //failed
                                {
                                    theNotificationToSave.Result = "Failed";
                                    theNotificationToSave.Created = DateTime.Now;


                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));


                                   
                                        GenerateBaseLog(ApiLogType.Information,
                                            LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created,
                                                __loggingResourceName),
                                            GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }



                            }

                            //NO EMAIL IN SYSTEM FOR EMERGENCY CONTACT
                           
                  GenerateBaseLog(ApiLogType.Warning,
  LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
  GetType(), GetCaller());
                            return BadRequest("There is no emergency email contact in the system so this request cannot be processed");

                        }

                        if (notificaton.NotificationType == NotificationType.AccidentSMS)
                        {
                            try
                            {

                                //validate
                                theNotificationToSave.NotificationType = NotificationType.AccidentSMS;

                                var key = "da8e48fd8f5bdfc705965646303a600bc02e8c7f";

                                string phoneNUmber = existingObjectInDb.Customer.EmergencySMSContact;
                                theNotificationToSave.To = phoneNUmber;
                                /*string phoneNUmber = "07476278909";*/
                                string removespaces = phoneNUmber.Replace(" ", String.Empty);

                                string nuewNumber;
                                if (phoneNUmber[0] == '0')
                                {
                                    nuewNumber = "44" + removespaces.Remove(0, 1);

                                }
                                else
                                {
                                    nuewNumber = removespaces;
                                }
                                //todo: check it's a proper number


                                string message = "Hello, there has been an accident. That's not good, is it?";
                                if (customer != null)
                                {
                                    message =
                                        String.Format(
                                            "Hello, there has been an accident involving {0} {1} {2} That's not good, is it?",
                                            customer.FirstName,
                                            customer.LastName);

                                }


                                var twilioClient = new TwilioClient();
                                twilioClient.SetupMessage(nuewNumber, message);
                                var msgSuccess = twilioClient.SendMessage();


                                /* Clockwork.API api = new API(key);
                                 SMSResult result = api.Send(
                                     new SMS
                                     {
                                         To = nuewNumber,
                                         Message = message
                                     });*/

                                if (msgSuccess)
                                {
                                    //todo:no content?? 
                                    theNotificationToSave.Result = "Success";
                                    theNotificationToSave.Created = DateTime.Now;

                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));

                                   
                                    GenerateBaseLog(ApiLogType.Information,
                                       LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created, __loggingResourceName),
                                       GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }
                                else
                                {

                                    var exception = new Exception("Couldn't send SMS notification");

                                   
                                    GenerateBaseLog(ApiLogType.Error,
        LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
         GetType(), GetCaller(), exception);
                                    return InternalServerError(exception);


                                }
                            }
                            catch (Exception ex)
                            {
                               
                                GenerateBaseLog(ApiLogType.Error,
     LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
      GetType(), GetCaller(), ex);
                                //todo:logging
                            }
                        }


                        if (notificaton.NotificationType == NotificationType.AccidentPDF)
                        {
                            //get address

                            try
                            {
                                theNotificationToSave.NotificationType = NotificationType.AccidentPDF;
                                customer = TheModelFactoryV1.Create(await customerRepo.Get(theCustomer.Id));

                                //todo: sort this out
                                var theAccidentSystem =
                                    _db.Accidents
                                        .FirstOrDefault(x=>x.Id == parsedAccidentId);
                                var accident = TheModelFactoryV1.Create(await accidentRepo.Get(theAccident.Id));

                                var otherDriver = _db.OtherDrivers.Where(x => x.Accident.Id == accident.Id)
                                    .Where(x => x.IsPrimary)
                                    .OrderByDescending(x => x.Created).ToList().FirstOrDefault();


                                if (otherDriver?.Email == null)
                                {
                                    return BadRequest("There is no other driver email in the system so this request cannot be processed");
                                }

                                var defendant = TheModelFactoryV1.Create(await otherDriversRepo.Get(otherDriver.Id));



                                if (defendant != null && customer != null && accident != null)
                                {
                                    //make sure we have somewhere to send it
                                    var defendantEmail = "";

                                    if (IsValidEmail(defendant.Email))
                                    {
                                        defendantEmail = defendant.Email;
                                    }
                                    //in case the email is in the wrong field.
                                    else if (IsValidEmail(defendant.Telephone))
                                    {
                                        defendantEmail = defendant.Telephone;
                                    }

                                    if (!String.IsNullOrEmpty(defendantEmail))
                                    //automailer 
                                    {
                                        var respondants = new List<string>();
                                        respondants.Add(defendantEmail);
                                        theNotificationToSave.To = defendantEmail;

                                        var GmailLessSecureMailService =
                                            new GmailLessSecureMailService("*****@*****.**", "Diagonal23",
                                                respondants,
                                                "Your Axiapp Accident Details Swap",
                                                GenerateAccidentHtml(customer, defendant, accident));

                                        if (GmailLessSecureMailService.SendEmail())

                                            theNotificationToSave.Result = "Success";
                                        theNotificationToSave.Created = DateTime.Now;

                                        var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));

                                       
                                        GenerateBaseLog(ApiLogType.Information,
                                           LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created, __loggingResourceName),
                                           GetType(), GetCaller());
                                        return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                    }
                                }


                            }
                            catch (Exception ex)
                            {

                               
                                GenerateBaseLog(ApiLogType.Error,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
    GetType(), GetCaller(), ex);
                                return
                                    InternalServerError(
                                        new Exception("Couldn't process your notification properly", ex));
                            }

                        }

                    }
                   
                    GenerateBaseLog(ApiLogType.Warning,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
    GetType(), GetCaller());
                    return BadRequest(ModelState);
                }

               
                GenerateBaseLog(ApiLogType.Error,
                  LogMessageGenerator.Generate(ApiLogggingBaseMessages.UnauthorisedAccess, __loggingResourceName),
                  GetType(), GetCaller());
                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You are not authorised to access this resource."));
            }
            catch (Exception ex)
            {


                var exce = new Exception("Couldn't process your notification properly", ex);
               
                GenerateBaseLog(ApiLogType.Error,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
    GetType(), GetCaller(), exce);

                return InternalServerError(exce);
            }

        }