コード例 #1
1
        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);
        }
コード例 #2
0
        public void ShouldKickConferenceParticipant()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.KickConferenceParticipant("", "");

            Assert.Fail();
        }
コード例 #3
0
        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
        }
コード例 #4
0
        public void ShouldListAuthorizedConnectAppUsingFilters()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.ListAuthorizedConnectApps(null,null);

            Assert.Fail();
        }
コード例 #5
0
        public void ShouldGetNotification()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            var result = client.GetNotification("");

            Assert.Fail();
        }
コード例 #6
0
 public void ShouldDeleteNotification()
 {
     var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
     var status = client.DeleteNotification("");            
     Assert.AreEqual(DeleteStatus.Success, status);
     Assert.Fail();
 }
コード例 #7
0
        public void ShouldListConferenceParticipants()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            client.ListConferenceParticipants("", null);

            Assert.Fail();
        }
コード例 #8
0
ファイル: CoreTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
ファイル: SmsTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #12
0
ファイル: SmsTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #13
0
ファイル: CallTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #14
0
ファイル: CallTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #15
0
        public void ShouldGetConference()
        {
            //create a new conference

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

            Assert.Fail();
        }
コード例 #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);
        }
コード例 #17
0
        public void ShouldListConferenceUsingFilters()
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);
            
            ConferenceListRequest options = new ConferenceListRequest();
            client.ListConferences(options);

            Assert.Fail();
        }
コード例 #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);
        }
コード例 #19
0
ファイル: SmsTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #20
0
        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));
            }
        }
コード例 #21
0
ファイル: SmsTests.cs プロジェクト: vmhung93/twilio-csharp
        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);
        }
コード例 #22
0
        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));
            }
        }
コード例 #23
0
        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();
        }
コード例 #24
0
        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();
        }
コード例 #25
0
        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);
        }
コード例 #26
0
ファイル: QueueTests.cs プロジェクト: vmhung93/twilio-csharp
        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
        }
コード例 #27
0
    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());
    }
コード例 #28
0
        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();
        }
コード例 #29
0
    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");
    }
コード例 #30
0
    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());
    }
コード例 #31
0
ファイル: ITwilioService.cs プロジェクト: wushian/Warden
 public TwilioService(string accountSid, string authToken)
 {
     _twilioRestClient = new TwilioRestClient(accountSid, authToken);
 }
コード例 #32
0
 public NotificationService()
 {
     _client = new TwilioRestClient(Auth.accountSid, Auth.authToken);
 }
コード例 #33
0
ファイル: SmsService.cs プロジェクト: vtdthang/SMSWebApi
 public SmsService()
 {
     _client = new TwilioRestClient(TwilioAccountSid, TwilioAuthToken);
 }
コード例 #34
0
 public MessageSender(TwilioRestClient client)
 {
     _client = client;
 }
コード例 #35
0
ファイル: UserSettings.aspx.cs プロジェクト: tuneis/hps
        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");
            }
        }
コード例 #36
0
ファイル: Sms.cs プロジェクト: carlosap/CSharp
 public Sms(TwilioRestClient client)
 {
     _client = client;
 }
コード例 #37
0
 public RestClient()
 {
     _client = new TwilioRestClient(Credentials.TwilioAccountSid, Credentials.TwilioAuthToken);
 }
コード例 #38
0
 public RestClient(TwilioRestClient client)
 {
     _client = client;
 }
コード例 #39
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public MfaSmsService()
 {
     _twilio      = new TwilioRestClient(AccountSid, AuthToken);
     SmsCallback += OnSmsCallback;
 }
コード例 #40
0
 public SmsService(IOptions <SmsConfig> options)
 {
     smsConfig        = options.Value;
     twilioRestClient = new TwilioRestClient(smsConfig.Sid, smsConfig.Token);
 }
コード例 #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);
 }
コード例 #42
0
ファイル: TwilioPhone.cs プロジェクト: ztcyun/CommunityServer
 public TwilioPhone(TwilioRestClient twilio)
 {
     this.twilio = twilio;
     Settings    = new TwilioVoipSettings();
 }
コード例 #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);
        }
コード例 #44
0
        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);
        }
コード例 #45
0
 public TwilioCallMessageAsyncCollector(TwilioRestClient context)
 {
     _context = context;
 }
コード例 #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;
                }
            }
        }
コード例 #47
0
ファイル: SmsSender.cs プロジェクト: antonysamy931/Email-Sms
 private void Init()
 {
     _twilio = new TwilioRestClient(AccountId, AuthToken);
 }
コード例 #48
0
ファイル: Program.cs プロジェクト: vinneyk/RioValleyChili
        private static void SendMessage(string message)
        {
            var twilio = new TwilioRestClient(TwilioSection.AccountSID, TwilioSection.AuthToken);

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

            return(smsClient);
        }
コード例 #53
0
ファイル: SmsService.cs プロジェクト: vtdthang/SMSWebApi
 public SmsService(TwilioRestClient client)
 {
     _client = client;
 }
コード例 #54
0
 public MessageService()
 {
     _twilioRestClient = new TwilioRestClient(ConfigurationManager.AppSettings.Get("twilio:accountSid"),
                                              ConfigurationManager.AppSettings.Get("twilio:authToken"));
 }