public void ShouldAddNewIncomingPhoneNumberAsynchronously()
        {
            manualResetEvent = new ManualResetEvent(false);

            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);

            PhoneNumberOptions options = new PhoneNumberOptions();
            options.PhoneNumber = "+15005550006";
            options.VoiceUrl = "http://example.com/phone";
            options.VoiceMethod = "GET";
            options.VoiceFallbackUrl = "http://example.com/phone";
            options.VoiceFallbackMethod = "GET";
            options.SmsUrl = "http://example.com/sms";
            options.SmsMethod = "GET";
            options.SmsFallbackUrl = "http://example.com/sms";
            options.SmsFallbackMethod = "GET";

            IncomingPhoneNumber result = null;
            client.AddIncomingPhoneNumber(options, number => {
                result = number;
                manualResetEvent.Set();
            });

            manualResetEvent.WaitOne();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Sid);
        }
        public void ShouldKickConferenceParticipant()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.KickConferenceParticipant("", "");

            Assert.Fail();
        }
        public void ShouldGetApplicationAsynchronously()
        {
            manualResetEvent = new ManualResetEvent(false);

            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);

            ApplicationOptions options = new ApplicationOptions();
            var originalApplication = client.AddApplication(Utilities.MakeRandomFriendlyName(), options);

            Assert.IsNotNull(originalApplication.Sid);

            Application result = null;

            client.GetApplication(originalApplication.Sid, app => {
                result = app;
                manualResetEvent.Set();
            });

            manualResetEvent.WaitOne();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.AreEqual(originalApplication.Sid, result.Sid);

            client.DeleteApplication(result.Sid); //cleanup
        }
        public void ShouldListAuthorizedConnectAppUsingFilters()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.ListAuthorizedConnectApps(null,null);

            Assert.Fail();
        }
        public void ShouldGetNotification()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.GetNotification("");

            Assert.Fail();
        }
 public void ShouldDeleteNotification()
 {
     var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
     var status = client.DeleteNotification("");            
     Assert.AreEqual(DeleteStatus.Success, status);
     Assert.Fail();
 }
        public void ShouldListConferenceParticipants()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.ListConferenceParticipants("", null);

            Assert.Fail();
        }
Example #8
0
        public void ShouldFailToSendSmsMessageWithInvalidCredentials()
        {
            var client = new TwilioRestClient("Foo", "Bar");
            var result = client.SendSmsMessage("+15005550006", "+13144586142", ".NET Unit Test Message");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.RestException);
        }
        public void ShouldListAuthorizedConnectApp()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.ListAuthorizedConnectApps();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.AuthorizedConnectApps);
        }
        public void ShouldListOutgoingCallerIds()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.ListOutgoingCallerIds();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.OutgoingCallerIds);
        }
Example #11
0
        public void ShouldSendSmsMessage()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.SendSmsMessage("+15005550006", "+13144586142", ".NET Unit Test Message");

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Sid);
        }
Example #12
0
        public void ShouldSendSmsMessageWithUnicodeCharacters()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.SendSmsMessage("+15005550006", "+13144586142", "رسالة اختبار وحدة.NET");

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Sid);
        }
Example #13
0
        public void ShouldFailToInitiateOutboundCallWithInvalidFromNumber()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.InitiateOutboundCall("+15005550006", "+15005550001", "http://www.example.com/phone/");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.RestException);
            Assert.IsNull(result.Sid);
        }
Example #14
0
        public void ShouldFailToInitiateOutboundCallWithInvalidUrl()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.InitiateOutboundCall("+15005550006", "+13144586142", "/phone");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.RestException);
            Assert.IsNull(result.Sid);
        }
Example #15
0
        public void ShouldGetConference()
        {
            //create a new conference

            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.GetConference("");

            Assert.Fail();
        }
Example #16
0
        public void ShouldGetCurrentAccount()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.GetAccount();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.AreEqual(Credentials.AccountSid, result.Sid);
        }
Example #17
0
        public void ShouldListConferenceUsingFilters()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            
            ConferenceListRequest options = new ConferenceListRequest();
            client.ListConferences(options);

            Assert.Fail();
        }
Example #18
0
        public void ShouldListConferences()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.ListConferences();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Conferences);
        }
Example #19
0
        public void ShouldFailToSendSmsMessageWithInvalidFromNumberFormat()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.SendSmsMessage("+15005550006", "+15005550001", ".NET Unit Test Message");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.RestException);
            Assert.AreEqual("21211", result.RestException.Code);
            Assert.IsNull(result.Sid);
        }
        protected override void Execute(CodeActivityContext context)
        {
            var client = new TwilioRestClient(this.AccountSid.Get(context), this.AuthToken.Get(context));
            var result = client.InitiateOutboundCall(this.From.Get(context), this.To.Get(context), this.CallbackUri.Get(context));

            if (result.RestException != null)
            {
                throw new Exception(String.Format("Outbound call failed: {0}", result.RestException.Message));
            }
        }
Example #21
0
        public void ShouldFailToSendSmsMessageWithLongMessage()
        {
            var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
            var result = client.SendSmsMessage("+15005550006", "+13144586142", "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.RestException);
            Assert.IsTrue( int.Parse(result.RestException.Status) < 401);
            Assert.IsNull(result.Sid);
        }
        protected override void Execute(CodeActivityContext context)
        {
            var client = new TwilioRestClient(this.AccountSid.Get(context), this.AuthToken.Get(context));
            var result = client.SendSmsMessage(this.From.Get(context), this.To.Get(context), this.Message.Get(context));

            if (result.RestException != null)
            {
                throw new Exception(String.Format("Message send failed: {0}", result.RestException.Message));
            }
        }
        public void ShouldListNotificationUsingFilters()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.ListNotifications();

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Notifications);
            Assert.Fail();
        }
        public void ShouldAddNewOutgoingCallerId()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.AddOutgoingCallerId("", "", null, null);

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.ValidationCode);
            Assert.Fail();
        }
        public void ShouldListAvailableTollFreePhoneNumbers()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);

            AvailablePhoneNumberListRequest options = new AvailablePhoneNumberListRequest();
            var result = client.ListAvailableTollFreePhoneNumbers("US");

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.AvailablePhoneNumbers);
        }
Example #26
0
        public void ShouldCreateNewQueue()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.CreateQueue("ShouldCreateNewQueue");

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Sid);

            client.DeleteQueue(result.Sid); //cleanup
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        var accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var authToken = "your_auth_token";
        var client = new TwilioRestClient(accountSid, authToken);

        var doc = DocumentResource.Fetch("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "MyFirstDocument").Execute(client);

        Console.WriteLine(doc.GetData());
    }
        public void ShouldUpdateOutgoingCallerId()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var originalCallerId = client.AddOutgoingCallerId("", "", null, null);

            var result = client.UpdateOutgoingCallerIdName("", "");

            Assert.IsNotNull(result);
            Assert.IsNull(result.RestException);
            Assert.IsNotNull(result.Sid);            
            Assert.Fail();
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        var accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var authToken = "your_auth_token";
        var client = new TwilioRestClient(accountSid, authToken);

        ServiceResource.Delete("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
          .Execute(client);

        Console.WriteLine("Deleted");
    }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        var accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var authToken = "your_auth_token";
        var client = new TwilioRestClient(accountSid, authToken);

        var service = ServiceResource.Fetch("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
          .Execute(client);

        Console.WriteLine(service.GetFriendlyName());
    }
Example #31
0
 public TwilioService(string accountSid, string authToken)
 {
     _twilioRestClient = new TwilioRestClient(accountSid, authToken);
 }
Example #32
0
 public NotificationService()
 {
     _client = new TwilioRestClient(Auth.accountSid, Auth.authToken);
 }
Example #33
0
 public SmsService()
 {
     _client = new TwilioRestClient(TwilioAccountSid, TwilioAuthToken);
 }
Example #34
0
 public MessageSender(TwilioRestClient client)
 {
     _client = client;
 }
Example #35
0
        protected void btnSendCellCode_Click(object sender, EventArgs e)
        {
            HelperMethods.ActivityTracker.Track("Sent A Verification Code to a Mobile Phone", (int)UserActionEnum.Clicked);

            //Clear Labels
            lblVerifyCell.Text         = "";
            lblVerifyCellConflict.Text = "";

            try
            {
                TwilioRestClient client =
                    new TwilioRestClient(ConfigurationManager.AppSettings["TwilioSID"],
                                         ConfigurationManager.AppSettings["TwilioTOKEN"]);

                string twilioId = ConfigurationManager.AppSettings["TwilioID"];

                string CELL   = txtVerifyCell.Text;
                string userId = HttpContext.Current.Session["UserId"].ToString();

                if (userId != null)
                {
                    // Query database
                    AspNetUser user = db.AspNetUsers.Where(u => u.Id == userId).SingleOrDefault();

                    if (user.PhoneNumber != txtVerifyCell.Text)
                    {
                        lblVerifyCell.Text = "You Must First Add Your Mobile to your Contact Information before you can Verify it.";
                    }
                    else if (user.PhoneNumber == txtVerifyCell.Text)
                    {
                        // verify and then add phone number entered
                        var callerId = client.AddOutgoingCallerId(CELL, user.UserName + " Cell", null, null);

                        if (callerId.RestException != null)
                        {
                            if (callerId.RestException.Message == "Phone number is already verified.")
                            {
                                lblVerifyCellConflict.Text = callerId.RestException.Message;

                                user.PhoneNumberConfirmed = true;

                                db.Entry(user).State = System.Data.Entity.EntityState.Modified;

                                db.SaveChanges();

                                LogFile.WriteToFile("UserSettings.aspx.cs", "btnSendCellCode_Click", callerId.RestException.Message, "Number already verified with twilio.", "HPSErrorLog.txt");
                            }
                            else
                            {
                                user.PhoneNumberConfirmed = false;

                                db.Entry(user).State = System.Data.Entity.EntityState.Modified;

                                db.SaveChanges();

                                lblVerifyCellConflict.Text = callerId.RestException.Message;
                                LogFile.WriteToFile("UserSettings.aspx.cs", "btnSendCellCode_Click", callerId.RestException.Message, "Error when trying to verify mobile number.", "HPSErrorLog.txt");
                            }
                        }
                        else
                        {
                            // display code to user for them to enter on their phone
                            txtVerifyCellCode.Text = callerId.ValidationCode;

                            user.PhoneNumberConfirmed = true;

                            db.Entry(user).State = System.Data.Entity.EntityState.Modified;

                            db.SaveChanges();
                        }
                    }
                }
                else
                {
                    lblVerifyCell.Text = "Could not find your information in the database, Please refresh the page and try again.";
                }
            }
            catch (DataException dx)
            {
                lblVerifyCell.Text += " An error occured try again. If the problem persists contact your administrator.<br>";
                LogFile.WriteToFile("UserSettings.aspx.cs", "btnSendCellCode_Click", dx, "Data error when searching for user with the entered phone number.", "HPSErrorLog.txt");
            }
            catch (Exception ex)
            {
                lblVerifyCell.Text += " An error occured try again. If the problem persists contact your administrator.<br>";
                LogFile.WriteToFile("UserSettings.aspx.cs", "btnSendCellCode_Click", ex, "error when trying to find user and create rest client.", "HPSErrorLog.txt");
            }
        }
Example #36
0
 public Sms(TwilioRestClient client)
 {
     _client = client;
 }
Example #37
0
 public RestClient()
 {
     _client = new TwilioRestClient(Credentials.TwilioAccountSid, Credentials.TwilioAuthToken);
 }
Example #38
0
 public RestClient(TwilioRestClient client)
 {
     _client = client;
 }
 /// <summary>
 /// Default Constructor
 /// </summary>
 public MfaSmsService()
 {
     _twilio      = new TwilioRestClient(AccountSid, AuthToken);
     SmsCallback += OnSmsCallback;
 }
Example #40
0
 public SmsService(IOptions <SmsConfig> options)
 {
     smsConfig        = options.Value;
     twilioRestClient = new TwilioRestClient(smsConfig.Sid, smsConfig.Token);
 }
Example #41
0
 public async Task SendAsync(string number, string contents)
 {
     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);
 }
Example #42
0
 public TwilioPhone(TwilioRestClient twilio)
 {
     this.twilio = twilio;
     Settings    = new TwilioVoipSettings();
 }
Example #43
0
        public static async Task <Report> GetReport(NotificationResource @event, TwilioRestClient client)
        {
            var report = new Report {
                Sid = @event.Sid, ErrorCode = @event.ErrorCode
            };

            if (otherErrorCodes.Contains(@event.ErrorCode))
            {
                report.ErrorType = ErrorType.Other;
                return(report);
            }
            report.CallSid = @event.CallSid;

            var url = GetUrl(@event);

            if (url == null)
            {
                throw new ArgumentException($"Can't determine url for {@event.Sid}");
            }

            if (url.EndsWith("/InboundCallDialStatusChange") ||
                url.EndsWith("/OutboundCallDialStatusChange") ||
                url.EndsWith("/OutboundCallConnected") || // not necessary for call connection callback
                url.EndsWith("/InboundCallStatus") ||
                url.EndsWith("/OutboundCallStatus")
                )
            {
                report.ErrorType = ErrorType.CallWasConnected;
                return(report);
            }

            if (url.EndsWith("/Tulsa"))
            {
                report.ErrorType   = ErrorType.CallWasntConnected;
                report.TenantPhone = "tulsa";
                return(report);
            }

            if (url.EndsWith("/Okc"))
            {
                report.ErrorType   = ErrorType.CallWasntConnected;
                report.TenantPhone = "okc";
                return(report);
            }

            if (url.EndsWith("/Index"))
            {
                var msg = GetPartOf(@event.MessageText, "Msg");
                if (
                    msg?.StartsWith(
                        "HTTP+Connection+Failure+-+Read+timed+out.+Falling+back+to+http%3A%2F%2Ftwimlets.com%2Fforward%3FPhoneNumber%3D%25") ==
                    true
                    ||
                    msg?.StartsWith(
                        "An+attempt+to+retrieve+content+from+https%3A%2F%2Ftwilio.servicetitan.com%2FTwilioProxy%2FIndex+returned+the+HTTP+status+code+502.+Falling+back+to+http%3A%2F%2Ftwimlets.com%2Fforward%3FPhoneNumber%3D%25") ==
                    true
                    ||
                    msg?.StartsWith(
                        "An+attempt+to+retrieve+content+from+https%3A%2F%2Ftwilio.servicetitan.com%2FTwilioProxy%2FIndex+returned+the+HTTP+status+code+502.+Falling+back+to+https%3A%2F%2Fignorant-goat-7596.twil.io") ==
                    true
                    ||
                    msg?.StartsWith(
                        "HTTP+Connection+Failure+-+Read+timed+out.+Falling+back+to+https%3A%2F%2Fignorant-goat-7596.twil.io") ==
                    true
                    ||
                    GetPartOf(@event.MessageText, "msg")?.StartsWith(
                        "HTTP+Connection+Failure+-+Read+timed+out.+Falling+back+to+http%3A%2F%2Ftwimlets.com%2Fforward%3FPhoneNumber%3D%25") ==
                    true
                    )
                {
                    report.ErrorType = ErrorType.CallWasConnected;
                    return(report);
                }
            }

            var call = await CallResource.FetchAsync(@event.CallSid, client : client);

            if (url.EndsWith("/OutboundCallGather"))
            {
                report.ErrorType   = ErrorType.CallWasntConnected;
                report.TenantPhone = call.From;
            }
            else if (url.EndsWith("/OutboundCallResponse"))
            {
                if (await HasChildren(call, client))
                {
                    throw new NotSupportedException($"OutboundCallResponse - {@event.Sid}");
                }

                report.ErrorType   = ErrorType.CallWasntConnected;
                report.TenantPhone = call.From;
            }
            else if (url.EndsWith("/Index"))
            {
                if (await HasChildren(call, client))
                {
                    throw new NotSupportedException($"Index - {@event.Sid}");
                }

                report.ErrorType   = ErrorType.CallWasntConnected;
                report.TenantPhone = call.To;
            }

            return(report);
        }
        public List <_TwilioMSGViewModel> GetAllMessages()
        {
            // Twilio request of list of messages
            TwilioRestClient   client  = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
            MessageListRequest request = new MessageListRequest();
            DateTime           today   = DateTime.Now;

            request.DateSent = today;
            var messages = client.ListMessages(request);
            List <_TwilioMSGViewModel> msg;

            msg = messages.Messages.Select(s => new _TwilioMSGViewModel()
            {
                Body     = s.Body,
                From     = s.From,
                To       = s.To,
                Sid      = s.Sid,
                DateSent = s.DateSent
            }).ToList();

            // Takes Msg looks into Active Campaigns for Keyword, assigns SurveyClient to Campaign
            List <string> TwilioSid = msg.Select(t => t.Sid).ToList();
            List <_TwilioMSGViewModel> newMessages;
            List <_TwilioMSGViewModel> newSurveyClient;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                List <TwilioMSG> previousMessages = db.TwilioMSGs.Where(m => TwilioSid.Contains(m.TwiilioMSGSid)).ToList();
                newMessages = msg.Where(m => !previousMessages.Any(m2 => m2.TwiilioMSGSid == m.Sid)).ToList();
                if (newMessages.Count != 0)
                {
                    using (ApplicationDbContext context = new ApplicationDbContext())
                    {
                        foreach (_TwilioMSGViewModel element in newMessages)
                        {
                            TwilioMSG dbModel = context.TwilioMSGs.Create();
                            dbModel.TwilioMSGBody = element.Body;
                            dbModel.TwilioMSGFrom = element.From;
                            dbModel.TwilioMSGTo   = element.To;
                            dbModel.TwiilioMSGSid = element.Sid;
                            dbModel.TwilioMSGDate = element.DateSent;
                            context.TwilioMSGs.Add(dbModel);
                        }
                        context.SaveChanges();
                    }
                    List <Campaign>            activeCampaings = db.Campaigns.Where(c => c.CampaignActive == true).ToList();
                    List <string>              activeKeywords  = activeCampaings.Select(k => k.CampaignKeyword).ToList();
                    List <_TwilioMSGViewModel> MsgWithKeywords = newMessages.Where(c => activeKeywords.Contains(c.Body)).ToList();
                    if (MsgWithKeywords.Count != 0)
                    {
                        List <string>       activePhoneNumbers    = db.SurveyClients.Select(p => p.SurveyClientPhone).ToList();
                        List <SurveyClient> previousSurveyClients = db.SurveyClients.Where(s => activePhoneNumbers.Contains(s.SurveyClientPhone)).ToList();
                        newSurveyClient = MsgWithKeywords.Where(q => !previousSurveyClients.Any(q2 => q2.SurveyClientPhone == q.From)).ToList();
                        if (newSurveyClient.Count != 0)
                        {
                            foreach (_TwilioMSGViewModel SClient in newSurveyClient)
                            {
                                using (ApplicationDbContext context = new ApplicationDbContext())
                                {
                                    SurveyClient dbClient = context.SurveyClients.Create();
                                    dbClient.SurveyClientPhone = SClient.From;
                                    context.SurveyClients.Add(dbClient);
                                    context.SaveChanges();
                                }
                                using (ApplicationDbContext context = new ApplicationDbContext())
                                {
                                    SurveyClientControl SCdb = context.SurveyClientControls.Create();
                                    SCdb.SurveyClientId        = context.SurveyClients.Where(x => x.SurveyClientPhone == SClient.From).FirstOrDefault().SurveyClientId;
                                    SCdb.SurveyClientControlId = context.SurveyClients.Where(x => x.SurveyClientPhone == SClient.From).FirstOrDefault().SurveyClientId;
                                    SCdb.SurveyClientPhone     = SClient.From;
                                    SCdb.CampaignId            = context.Campaigns.Where(y => y.CampaignKeyword == SClient.Body).FirstOrDefault().CampaignId;
                                    SCdb.Questions             = context.Questions.Where(q => q.CampaignId == SCdb.CampaignId).ToList();
                                    context.SurveyClientControls.Add(SCdb);
                                    context.SaveChanges();
                                }
                                using (ApplicationDbContext questionDb = new ApplicationDbContext())
                                {
                                    SurveyClientControl dbQuestions = questionDb.SurveyClientControls.Include(s => s.Questions).Where(q => q.SurveyClientPhone == SClient.From).FirstOrDefault();
                                    if (dbQuestions.Questions.Count != 0)
                                    {
                                        foreach (var element in dbQuestions.Questions)
                                        {
                                            using (ApplicationDbContext progressDb = new ApplicationDbContext())
                                            {
                                                Progress dbProgress = progressDb.ProgressSwitches.Create();
                                                dbProgress.ProgressSwitch        = false;
                                                dbProgress.QuestionId            = element.QuestionId;
                                                dbProgress.SurveyClientControlId = dbQuestions.SurveyClientControlId;
                                                progressDb.ProgressSwitches.Add(dbProgress);
                                                progressDb.SaveChanges();
                                            }

                                            using (ApplicationDbContext currentQuestionDb = new ApplicationDbContext())
                                            {
                                                CurrentQuestion dbCQuestion = currentQuestionDb.CurrentQuestionSwitches.Create();
                                                dbCQuestion.CurrentQuestionSwitch = false;
                                                dbCQuestion.QuestionId            = element.QuestionId;
                                                dbCQuestion.SurveyClientControlId = dbQuestions.SurveyClientControlId;
                                                currentQuestionDb.CurrentQuestionSwitches.Add(dbCQuestion);
                                                currentQuestionDb.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // If Msg does not includes a Keyword, is considered as san Answer and it comes here
                    else
                    {
                        using (ApplicationDbContext questionsCompare = new ApplicationDbContext())
                        {
                            List <SurveyClientControl> SurveyClients = questionsCompare.SurveyClientControls.ToList();
                            List <string> Questions             = questionsCompare.Questions.Select(q => q.QuestionBody).ToList();
                            List <_TwilioMSGViewModel> leftMsgs = newMessages.Where(m => !Questions.Contains(m.Body)).ToList();
                            if (leftMsgs.Count != 0)
                            {
                                foreach (var MsgElement in leftMsgs)
                                {
                                    if (MsgElement.From != "+18324101832")
                                    {
                                        using (ApplicationDbContext LogResponse = new ApplicationDbContext())
                                        {
                                            List <int> Progress_QuestionId      = LogResponse.ProgressSwitches.Where(d => d.ProgressSwitch == true).Select(c => c.QuestionId).ToList();
                                            int        Last_Progress_QuestionId = Progress_QuestionId.LastOrDefault();
                                            Response   AddResponse = LogResponse.Responses.Create();
                                            AddResponse.ResponseBody          = MsgElement.Body;
                                            AddResponse.QuestionId            = Last_Progress_QuestionId;
                                            AddResponse.SurveyClientControlId = SurveyClients.Where(b => b.SurveyClientPhone == MsgElement.From).FirstOrDefault().SurveyClientControlId;
                                            LogResponse.Responses.Add(AddResponse);
                                            LogResponse.SaveChanges();
                                            break;
                                        }
                                    }
                                }
                                using (ApplicationDbContext StatusChangeCurrentQuestion = new ApplicationDbContext())
                                {
                                    foreach (var ClientElement in leftMsgs)
                                    {
                                        List <int> Progress_QuestionId      = StatusChangeCurrentQuestion.ProgressSwitches.Where(d => d.ProgressSwitch == true).Select(c => c.QuestionId).ToList();
                                        List <int> Current_Switches_False   = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.CurrentQuestionSwitch == false).Select(d => d.QuestionId).ToList();
                                        int        Last_Progress_QuestionId = Progress_QuestionId.LastOrDefault();
                                        if (Progress_QuestionId.Count != 0 && Current_Switches_False.Count != 0 && ClientElement.From != "+18324101832")
                                        {
                                            SurveyClientControl CurrentClient = SurveyClients.Where(q => q.SurveyClientPhone == ClientElement.From).FirstOrDefault();
                                            CurrentQuestion     CurrentStatus = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.QuestionId == Last_Progress_QuestionId && c.SurveyClientControlId == CurrentClient.SurveyClientControlId).FirstOrDefault();
                                            CurrentStatus.CurrentQuestionSwitch = true;
                                            StatusChangeCurrentQuestion.SaveChanges();
                                            break;
                                        }
                                        if (Progress_QuestionId.Count != 0 && Current_Switches_False.Count != 0 && ClientElement.From == "+18324101832")
                                        {
                                            SurveyClientControl CurrentClient = SurveyClients.Where(q => q.SurveyClientPhone == ClientElement.To).FirstOrDefault();
                                            CurrentQuestion     CurrentStatus = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.QuestionId == Last_Progress_QuestionId && c.SurveyClientControlId == CurrentClient.SurveyClientControlId).FirstOrDefault();
                                            CurrentStatus.CurrentQuestionSwitch = true;
                                            StatusChangeCurrentQuestion.SaveChanges();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // If Not new message, system will send questions to Survey Clients
                else
                {
                    List <SurveyClientControl> SurveyClientsReady;
                    using (ApplicationDbContext serviceReady = new ApplicationDbContext())
                    {
                        SurveyClientsReady = serviceReady.SurveyClientControls.Include(s => s.Questions).Include(s => s.ProgressSwitches).Include(s => s.CurrentQuestionSwitches).Where(q => q.BlackList == false).ToList();
                        foreach (var ClientElement in SurveyClientsReady)
                        {
                            List <int> ProgressIds        = ClientElement.ProgressSwitches.Where(o => o.ProgressSwitch == false).Select(p => p.QuestionId).ToList();
                            List <int> ProgressTrue       = ClientElement.ProgressSwitches.Where(p => p.ProgressSwitch == true).Select(z => z.QuestionId).ToList();
                            List <int> CurrentQuestionIds = ClientElement.CurrentQuestionSwitches.Where(q => q.CurrentQuestionSwitch == true).Select(r => r.CurrentQuestionId).ToList();
                            if (ProgressIds.Count != 0 && CurrentQuestionIds.Count != 0 && ProgressTrue.Count == CurrentQuestionIds.Count)
                            {
                                Question         Question_Filter_Progress = ClientElement.Questions.Where(q => ProgressIds.Contains(q.QuestionId)).FirstOrDefault();
                                TwilioRestClient clientSendMsg            = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                clientSendMsg.SendSmsMessage("832-410-1832", ClientElement.SurveyClientPhone, Question_Filter_Progress.QuestionBody);
                                using (ApplicationDbContext changeProgress = new ApplicationDbContext())
                                {
                                    Progress ProgressChangeStatus = changeProgress.ProgressSwitches.Where(i => i.QuestionId == Question_Filter_Progress.QuestionId).FirstOrDefault();
                                    ProgressChangeStatus.ProgressSwitch = true;
                                    changeProgress.SaveChanges();
                                }
                            }
                            else
                            {
                                if (ProgressTrue.Count == 0 && CurrentQuestionIds.Count == 0)
                                {
                                    Question         Question_Filter_Progress = ClientElement.Questions.Where(q => ProgressIds.Contains(q.QuestionId)).FirstOrDefault();
                                    TwilioRestClient clientSendMsg            = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                    clientSendMsg.SendSmsMessage("832-410-1832", ClientElement.SurveyClientPhone, Question_Filter_Progress.QuestionBody);
                                    using (ApplicationDbContext changeProgress = new ApplicationDbContext())
                                    {
                                        Progress ProgressChangeStatus = changeProgress.ProgressSwitches.Where(i => i.QuestionId == Question_Filter_Progress.QuestionId).FirstOrDefault();
                                        ProgressChangeStatus.ProgressSwitch = true;
                                        changeProgress.SaveChanges();
                                    }
                                }
                            }
                            if (ProgressIds.Count == 0 && ClientElement.BlackList == false)
                            {
                                Campaign Coupon;
                                using (ApplicationDbContext lastMsg = new ApplicationDbContext())
                                {
                                    Coupon = lastMsg.Campaigns.Where(q => q.CampaignId == ClientElement.CampaignId).FirstOrDefault();
                                }
                                TwilioRestClient clientSendMsg = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                clientSendMsg.SendMessage("832-410-1832", ClientElement.SurveyClientPhone, "Thank you for Participating", new string[] { Coupon.CampaignGift });
                                ClientElement.BlackList = true;
                                serviceReady.SaveChanges();
                            }
                        }
                    }
                }
            }
            return(msg);
        }
 public TwilioCallMessageAsyncCollector(TwilioRestClient context)
 {
     _context = context;
 }
Example #46
0
        static void Main(string[] args)
        {
            List <string> sidsWithErrorsToSkip = new List <string>();
            Mutex         sidsToSkipMutex      = new Mutex();

            var toMoveInfo = GetRecordingsToMove();
            List <TwilioRecordingInfo> previousRecordings = new List <TwilioRecordingInfo>();

            while (toMoveInfo.Item2 > 0)
            {
                if (!Directory.Exists("TempRecordings"))
                {
                    Directory.CreateDirectory("TempRecordings");
                }

                //Set the max threads that you would like to use for downloading the recordings from twilio and uploading it to azure
                ParallelOptions options = new ParallelOptions();
                options.MaxDegreeOfParallelism = int.Parse(ConfigurationManager.AppSettings["MaxThreads"]);

                Parallel.ForEach(toMoveInfo.Item1, options, recording =>
                {
                    //We found that some recordings are returned by twilio's api but they dont really have the recording... so after we found one, we add it to this list so we dont try to download it again on next iteration
                    bool skip = false;
                    sidsToSkipMutex.WaitOne();
                    if (sidsWithErrorsToSkip.Contains(recording.SID))
                    {
                        skip = true;
                    }
                    sidsToSkipMutex.ReleaseMutex();

                    if (!skip)
                    {
                        try
                        {
                            var uploaded = UploadAndCheckRecording(recording);
                            if (uploaded)
                            {
                                //The call is only deleted if its uploaded (double checked with a download and md5 comparison)
                                var twilioClient = new TwilioRestClient(ConfigurationManager.AppSettings["Twilio.AccountSID"], ConfigurationManager.AppSettings["Twilio.AuthToken"]);
                                var deleteStatus = twilioClient.DeleteRecording(recording.SID);
                            }
                        }
                        catch (WebException wex)
                        {
                            if (wex.Response != null && wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                            {
                                //We add this recording sid to the list of sids to skip
                                sidsToSkipMutex.WaitOne();
                                sidsWithErrorsToSkip.Add(recording.SID);
                                sidsToSkipMutex.ReleaseMutex();
                            }
                        }
                        catch (Exception ex) { } //Something happened while processing this call, we just skip it and in the next page of recordings, it will be processed again
                    }
                });

                //After each iteration we delete the temp recordings folder to free hdd space
                if (Directory.Exists("TempRecordings"))
                {
                    Directory.Delete("TempRecordings", true);
                }

                previousRecordings = toMoveInfo.Item1;

                //Get the next page of recordings to process
                toMoveInfo = GetRecordingsToMove();

                //Check if in the new "page" the recordings are the same as in the previous one, if this is the case, we need to stop or we would enter in an infinit loop
                if (toMoveInfo.Item2 > 0 && !toMoveInfo.Item1.Any(a => !previousRecordings.Any(b => b.SID == a.SID)))
                {
                    //There only recordings left are the ones in the sidsToSkipMutex, so we stop
                    break;
                }
            }
        }
Example #47
0
 private void Init()
 {
     _twilio = new TwilioRestClient(AccountId, AuthToken);
 }
Example #48
0
        private static void SendMessage(string message)
        {
            var twilio = new TwilioRestClient(TwilioSection.AccountSID, TwilioSection.AuthToken);

            twilio.SendMessage(TwilioSection.FromNumber, TwilioSection.ToNumber, message);
        }
Example #49
0
 public TwilioPhoneNumberLookupService(IOptions <TwilioSettings> twilioSettings, ITwilioWrapper twilioWrapper)
 {
     _twilioSettings = twilioSettings.Value;
     _twilioClient   = new TwilioRestClient(_twilioSettings.Sid, _twilioSettings.Token);
     _twilioWrapper  = twilioWrapper;
 }
Example #50
0
 public Sms()
 {
     _twilio = new TwilioRestClient(AccountSid, AuthToken);
 }
 public NotificationService()
 {
     _client = new TwilioRestClient(Credentials.AccountSID, Credentials.AuthToken);
 }
Example #52
0
        private TwilioRestClient CreateSmsClient()
        {
            var smsClient = new TwilioRestClient(_smsSettings.AccountSid, _smsSettings.AuthToken);

            return(smsClient);
        }
Example #53
0
 public SmsService(TwilioRestClient client)
 {
     _client = client;
 }
Example #54
0
 public MessageService()
 {
     _twilioRestClient = new TwilioRestClient(ConfigurationManager.AppSettings.Get("twilio:accountSid"),
                                              ConfigurationManager.AppSettings.Get("twilio:authToken"));
 }