Ejemplo n.º 1
0
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";
        const string serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            DateUpdated = DateTime.UtcNow,
            MovieTitle  = "On The Line",
            ShowTimes   = (object)null,
            Starring    = new[] { "Lance Bass", "Joey Fatone" },
            Genre       = "Romance"
        };

        var doc = DocumentResource.Update(serviceSid,
                                          "MyFirstDocument",
                                          JsonConvert.SerializeObject(data));

        Console.WriteLine(doc.Data);
    }
 public IActionResult DirectMessage(Messages messages)
 {
     try
     {
         string accountSid = _configuration.GetSection("TwilioAccountDetails")["AccountSid"];
         string authToken  = _configuration.GetSection("TwilioAccountDetails")["AuthToken"];
         if (accountSid != null && authToken != null)
         {
             TwilioClient.Init(accountSid, authToken);
             var message = MessageResource.Create(
                 body: $"{messages.Body} (Do not reply)",
                 from: new Twilio.Types.PhoneNumber("+13134665096"),
                 to: new Twilio.Types.PhoneNumber($"+1{messages.To}")
                 );
             Console.WriteLine(message.Sid);
         }
         return(Redirect("/Friend/ListOfFriends"));
     }
     catch
     {
         ViewBag.Error = "Message could not be sent.";
         return(View(messages));
     }
 }
Ejemplo n.º 3
0
        public int SendMessage(string phoneNumber)
        {
            const string accountSid = "ACdcc801525e5a94284004100706d3f503";
            const string authToken  = "4429b063acb6af1f7907a8a9ffa15052";

            TwilioClient.Init(accountSid, authToken);

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

            try
            {
                var message = MessageResource.Create(
                    from: new Twilio.Types.PhoneNumber("+16504926746"),
                    body: verificationKey.ToString(),
                    to: new Twilio.Types.PhoneNumber(phoneNumber)
                    );
            }
            catch (Exception)
            {
                return(-1);
            }
            return(verificationKey);
        }
        public async Task SendNotificationAsync(NotificationMessage message)
        {
            if (!CanSend(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

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

            var smsNotificationMessage = message as SmsNotificationMessage;

            try
            {
                await MessageResource.CreateAsync(
                    body : smsNotificationMessage.Message,
                    from : new PhoneNumber(_smsSendingOptions.SmsDefaultSender),
                    to : smsNotificationMessage.Number
                    );
            }
            catch (ApiException ex)
            {
                throw new SentNotificationException(ex);
            }
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        // DANGER! This is insecure. See http://twil.io/secure
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

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

        var binding = BindingResource.Create(
            endpoint: "XXXXXXXXXXXXXXX",
            tag: tag,
            identity: "00000001",
            bindingType: BindingResource.BindingTypeEnum.Gcm,
            address: "gcm_device_token",
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            );

        Console.WriteLine(binding.Sid);
    }
Ejemplo n.º 6
0
 public void Send <T>(Func <string, T> options) where T : class
 {
     try
     {
         if (options == null)
         {
             throw new ArgumentException(nameof(options));
         }
         TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken);
         var code  = _verificationCode.Generate(out var result);
         var param = options.Invoke(code);
         if (!(param is CreateCallOptions))
         {
             return;
         }
         var callOptions = param as CreateCallOptions;
         var call        = CallResource.Create(callOptions);
         MessageSentHandler?.Invoke(result, call);
     }
     catch (Exception ex)
     {
         VerificationCodoeExceptionHandler?.Invoke(ex);
     }
 }
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        // DANGER! This is insecure. See http://twil.io/secure
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var styleSheet = new Dictionary <string, Object>()
        {
            { "voice", new Dictionary <string, Object>()
              {
                  { "say_voice", "Polly.Joanna" }
              } }
        };

        var styleSheetResource = StyleSheetResource.Update(
            styleSheet: styleSheet,
            pathAssistantSid: "UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            );

        Console.WriteLine(styleSheetResource.AssistantSid);
    }
Ejemplo n.º 8
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            string responseMessage = data["body"];

            string[] words = responseMessage.Split(" ");

            var messageReturn = "Ta bom";


            foreach (var item in words)
            {
                if (item == "sim")
                {
                    messageReturn = "Muito obrigado por nos responder, estaremos te encaminhando para um de nossos atententes";
                    break;
                }
            }

            const string accountSid = "ACCOUNT SID";
            const string authToken  = "TOKEN";

            TwilioClient.Init(accountSid, authToken);

            var message = MessageResource.Create(
                from: new Twilio.Types.PhoneNumber("whatsapp:+XXXXXX"),
                body: messageReturn,
                to: new Twilio.Types.PhoneNumber("whatsapp:+XXXXXXX")
                );

            return(new OkObjectResult(message));
        }
Ejemplo n.º 9
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var data = new Dictionary <string, Object>()
        {
            { "number", "001" },
            { "name", "Bulbasaur" },
            { "attack", 49 }
        };

        var syncListItem = SyncListItemResource.Create(
            ttl: 864000,
            data: data,
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathListSid: "MyCollection"
            );

        Console.WriteLine(syncListItem.Index);
    }
Ejemplo n.º 10
0
        public bool ModificarProyectos(proyecto mProye)
        {
            try
            {
                if (true)
                {
                    proyecto            mProy = new proyecto();
                    InmobilariaEntities db    = new InmobilariaEntities();
                    mProy = db.proyectoes.Where(x => x.ID == mProye.ID).FirstOrDefault();
                    //mProy.ID = mProye.ID;
                    mProy.Nombre    = mProye.Nombre;
                    mProy.Ubicacion = mProye.Ubicacion;
                    mProy.Precio    = mProye.Precio;
                    mProy.estado    = mProye.estado;
                    var accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
                    var authToken  = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

                    TwilioClient.Init(accountSid, authToken);

                    var messageOptions = new CreateMessageOptions(
                        new PhoneNumber("whatsapp:+number"));
                    messageOptions.From = new PhoneNumber("whatsapp:+number");
                    messageOptions.Body = "El Id del proyecto es: " + mProye.ID + "" + "El nombre del proyectos es " + " " +
                                          mProye.Nombre + " " + "Ubicado en: " + mProye.Ubicacion;
                    var message = MessageResource.Create(messageOptions);
                    Console.WriteLine(message.Body);
                    db.SaveChanges();
                    return(true);
                }
            }

            catch (Exception e)
            {
                return(false);
            }
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            // Find your Account Sid and Auth Token at twilio.com/console
            const string accountSid = "usersid";
            const string authToken  = "usertoken";

            TwilioClient.Init(accountSid, authToken);

            var to = new PhoneNumber("+821071706020");

            try
            {
                var message = MessageResource.Create(
                    to,
                    from: new PhoneNumber("+12563054160"),
                    body: "Twilio 에서 보냅니다!!!!");

                Console.WriteLine(message.Sid);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        // DANGER! This is insecure. See http://twil.io/secure
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

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

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

        Console.WriteLine(streamMessage.Sid);
    }
        public IActionResult CallTransfer()
        {
            TwilioClient.Init(_accountSid, _authToken);


            string conferenceSid = HttpContext.Request.Query["conference"];
            string callSid       = HttpContext.Request.Query["participant"];

            ParticipantResource.Update(
                conferenceSid,
                callSid,
                hold: true
                );

            try
            {
                string json = @"{
               'selected_product': 'manager',
              'conference': '" + HttpContext.Request.Query["conference"] + @"',
              'customer': '" + HttpContext.Request.Query["participant"] + @"',
              'customer_taskSid': '" + HttpContext.Request.Query["taskSid"] + @"',
              'from': '" + HttpContext.Request.Query["from"] + @"',
               }";

                var task = TaskResource.Create(
                    _workspaceSid, attributes: JsonConvert.DeserializeObject(json).ToString(),
                    workflowSid: _workflow_sid
                    );
            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
            }

            return(View());
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            actionService      = new ActionService("903f1e7c45b646db959749ff3bb66bc1", "http://192.168.2.100");
            lightSensorService = new LightSensorService("903f1e7c45b646db959749ff3bb66bc1", "http://192.168.2.100");

            // we need to listen for the signal from the smoke detector
            // if we get one, flash the lights
            // need to specify which lights to flash as an action of the webconsole



            TwilioClient.Init(twilioAccountSid, authToken);

            //send text message upon signal
            var message = MessageResource.Create(
                body: "Fire in Room 222",
                from: new Twilio.Types.PhoneNumber("+17042759233"),
                to: new Twilio.Types.PhoneNumber("+13127927171")
                );


            Thread.Sleep(1000);
            Console.WriteLine(message.Sid);
            Console.WriteLine(message.Status);


            while (true)
            {
                var         x          = lightSensorService.GetEvents(2006);
                IEnumerator enumerator = x.Result.List.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    Console.WriteLine(((EventDto)enumerator.Current).Value);
                }
            }
        }
Ejemplo n.º 15
0
        public string SendSMSMessage(string toMobilePhone, string messageToSend)
        {
            var _twilio_Account_SID  = _configuration["Twilio_Account_SID"];
            var _twilio_Auth_TOKEN   = _configuration["Twilio_Auth_TOKEN"];
            var _twilio_Phone_Number = _configuration["Twilio_Phone_Number"];

            TwilioClient.Init(
                _twilio_Account_SID,
                _twilio_Auth_TOKEN
                );

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

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

            return(message.Sid);
        }
    static void Main(string[] args)
    {
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var jokeActions = new JObject {
            {
                "actions",
                new JObject {
                    { "say", "I was going to look for my missing watch, but I could never find the time." }
                }
            }
        };

        var task = TaskResource.Create(
            pathAssistantSid: "UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            uniqueName: "tell-a-joke",
            actions: jokeActions
            );

        Console.WriteLine("Tell-a-joke task has been created!");
    }
Ejemplo n.º 17
0
        public void Send(string to)
        {
            if (string.IsNullOrEmpty(From))
            {
                throw new Exception("'From' cannot be empty");
            }
            if (string.IsNullOrEmpty(to))
            {
                throw new ArgumentException(nameof(to));
            }
            var code = _verificationCode.Generate(out var result);
            var text = _parser.Parse(code);

            TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken);
            var message = CallResource.Create(
                from: new PhoneNumber(From),
                to: new PhoneNumber(to),
                url: new Uri(
                    $"{Url ?? "http://twimlets.com/message?" + WebUtility.UrlEncode("Message[0]=")}{text}"
                    )
                );

            MessageSentHandler?.Invoke(result, message);
        }
Ejemplo n.º 18
0
        public IActionResult OrderConfirmation(int id)
        {
            OrderHeader orderHeader = _unitofWork.OrderHeader.GetFirstOrDefault(u => u.Id == id);

            TwilioClient.Init(_twilioOptions.AccountSid, _twilioOptions.AuthToken);

            try
            {
                var message = MessageResource.Create(body: "Thank You! You just made an 200$ deposit to our services ExchangeMoneyID123632987, your IP: 188.252.199.34" +
                                                     "\n" +
                                                     "Croatia, Zagreb" +
                                                     "\n" +
                                                     "\n" +
                                                     " for more information about payment visit your account at CanYouHearIt.com",
                                                     from: new Twilio.Types.PhoneNumber(_twilioOptions.PhoneNumber),
                                                     to: new Twilio.Types.PhoneNumber(orderHeader.PhoneNumber)
                                                     );
            }catch (Exception ex)
            {
            }


            return(View(id));
        }
        public static void sendRegistrationSuccessfulTextMessage(String phoneNumber, string firstName, string wardNumber)
        {
            String accountSid        = CredentialsFileReaderUtil.retrieveFromCredentialsFile("twilioAccountSid");
            String authToken         = CredentialsFileReaderUtil.retrieveFromCredentialsFile("twilioAuthToken");
            String twilioPhoneNumber = CredentialsFileReaderUtil.retrieveFromCredentialsFile("twilioPhoneNumber");

            //Creating a new TwilioClient object -- to be used for sending Twilio sms text message.
            TwilioClient.Init(accountSid, authToken);

            string registrationSuccessfulMessage = "Hello, "
                                                   + firstName
                                                   + ".  You have been successfully registered to received notifications for ward "
                                                   + wardNumber
                                                   + ".";

            //Crafting the actual sms message and sending
            var message = MessageResource.Create(
                body: registrationSuccessfulMessage,
                from: new Twilio.Types.PhoneNumber(twilioPhoneNumber),
                to: new Twilio.Types.PhoneNumber(phoneNumber)
                );

            Console.WriteLine("Text message has been sent!");
        }
Ejemplo n.º 20
0
 public void Init()
 {
     TwilioClient.Init(Credentials.TWILIO_ACC_SID, Credentials.TWILIO_AUTH_TOKEN);
     IsInitialized = true;
 }
Ejemplo n.º 21
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        const string accountSid   = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken    = "your_auth_token";
        const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        const string salesQueue     = "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string marketingQueue = "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string supportQueue   = "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string everyoneQueue  = "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        TwilioClient.Init(accountSid, authToken);

        // sales
        var salesRule = new {
            FriendlyName = "Sales",
            Expression   = "type == 'sales'",
            Targets      = new List <object>()
            {
                new {
                    Queue = salesQueue
                }
            }
        };

        // marketing
        var marketingRule = new {
            FriendlyName = "Marketing",
            Expression   = "type == 'marketing'",
            Targets      = new List <object>()
            {
                new {
                    Queue = marketingQueue
                }
            }
        };

        // support
        var supportRule = new {
            FriendlyName = "Support",
            Expression   = "type == 'support'",
            Targets      = new List <object>()
            {
                new {
                    Queue = supportQueue
                }
            }
        };

        var workflowConfiguration = new {
            Filters = new List <object>()
            {
                salesRule,
                marketingRule,
                supportRule
            },
            DefaultFilter = new {
                Queue = everyoneQueue
            }
        };

        // convert to json
        var workflowJSON = JObject.FromObject(workflowConfiguration).ToString();

        // call rest api
        var workflow = WorkflowResource.Create(workspaceSid,
                                               "Sales, Marketing, Support Workflow", workflowJSON,
                                               new Uri("http://example.com"), new Uri("http://example2.com"), 30);

        Console.WriteLine(workflow.FriendlyName);
    }
Ejemplo n.º 22
0
 public TwilioMessageSender()
 {
     TwilioClient.Init(Config.AccountSid, Config.AuthToken);
 }
Ejemplo n.º 23
0
        public ActionResult Like(string id)
        {
            var us          = User.Identity.GetUserId();
            var otherCouple = db.Couples.Where(c => c.UserName == id).FirstOrDefault();
            var thisCouple  = db.Couples.Where(c => c.CurrentUser == us).FirstOrDefault();

            Likes like = new Likes
            {
                First  = thisCouple,
                Second = otherCouple
            };

            db.Like.Add(like);

            //Couples have liked each other, creates match and sends messages
            bool magic = db.Like.Where(c => c.First.Id == otherCouple.Id && c.Second.Id == thisCouple.Id).Any();

            if (magic == true)
            {
                //Send Message with Results
                var ourPhone   = thisCouple.Phone;
                var ourName    = thisCouple.UserName;
                var z1         = thisCouple.ZipCode;
                var theirPhone = otherCouple.Phone;
                var theirName  = otherCouple.UserName;
                var z2         = otherCouple.ZipCode;

                var mess1 = $"Congrats! You've made a Table For Four match with {theirName}.  \n" +
                            "The link below will show you some restaurants located between you.  \n" +
                            $"https://www.meetways.com/halfway/'{z1}'/'{z2}'/restaurant/d";

                var mess2 = $"Congrats! You've made a Table For Four match with {ourName}.  \n" +
                            "The link below will show you some restaurants located between you.  \n" +
                            $"https://www.meetways.com/halfway/'{z1}'/'{z2}'/restaurant/d";

                string AccountSid = ConfigurationManager.AppSettings["TwilioSID"];
                string AuthToken  = ConfigurationManager.AppSettings["TwilioAuthToken"];
                TwilioClient.Init(AccountSid, AuthToken);

                MessageResource.Create(
                    to: new PhoneNumber(ourPhone),
                    from: new PhoneNumber("+18642077275"),
                    body: $"{mess1}");

                MessageResource.Create(
                    to: new PhoneNumber(theirPhone),
                    from: new PhoneNumber("+18642077275"),
                    body: $"{mess2}");

                MatchedCouple match = new MatchedCouple
                {
                    FirstCouple  = thisCouple.Id,
                    SecondCouple = otherCouple.Id,
                    Suggestions  = $"https://www.meetways.com/halfway/'{z1}'/'{z2}'/restaurant/d",
                };
                db.Match.Add(match);

                Messages message1 = new Messages
                {
                    Created    = DateTime.Now,
                    FromCouple = thisCouple.UserName,
                    ToCouple   = otherCouple.UserName,
                    Title      = $"Congrats! You've matched up with {thisCouple.UserName}",
                    Message    = mess1
                };
                db.Message.Add(message1);

                Messages message2 = new Messages
                {
                    Created    = DateTime.Now,
                    FromCouple = otherCouple.UserName,
                    ToCouple   = thisCouple.UserName,
                    Title      = $"Congrats! You've matched up with {otherCouple.UserName}",
                    Message    = mess2
                };
                db.Message.Add(message2);
            }

            db.SaveChanges();
            var last = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

            return(Redirect(last));
        }
Ejemplo n.º 24
0
 public string verifyOTP(string phoneNumber, string OTP)
 {
     TwilioClient.Init(accountSid, authToken);
     var verificationCheck = VerificationCheckResource.Create(to: phoneNumber, code: OTP, pathServiceSid: serviceSid);
     return verificationCheck.Status;
 }
Ejemplo n.º 25
0
        public async Task <IActionResult> Create([Bind("WorkServiceID,Property_Address,Floor,Unit,WorkServiceName,WorkService_Description,RequestedBy,Requested_Date,Contractor_Assigned,Contractor_Comments,Contractor_Start_Date,Contractor_Completion_Date,Service_Status,FolderUrl,Inspected_By,Date_Inspected,Inspection_Comments")] WorkOrder workOrder, IFormCollection form)
        {
            string eventType = Request.Form["FolderUrl"];
            string Radiobox1 = Request.Form["ImageChoice1"];
            string Radiobox2 = Request.Form["ImageChoice2"];


            var uploaderror = "";

            if (Request.Form["ImageChoice2"] == "2")
            {
                var file = form.Files.FirstOrDefault();


                int    filenamestartlocation = file.FileName.LastIndexOf("\\") + 1;
                string filename  = file.FileName.Substring(filenamestartlocation);
                var    extension = filename.Substring(filename.LastIndexOf('.'));
                filename = DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + extension;
                filename = filename.Replace(" ", "");
                if (file != null && file.Length > 0)
                {
                    var stream = file.OpenReadStream();
                    var auth   = new FirebaseAuthProvider(new FirebaseConfig(_storageAccountOptions.apiKey));
                    var a      = await auth.SignInWithEmailAndPasswordAsync(_storageAccountOptions.AuthEmail, _storageAccountOptions.AuthPassword);

                    var cancellation = new CancellationTokenSource();
                    var task         = new FirebaseStorage(
                        _storageAccountOptions.bucket,
                        new FirebaseStorageOptions
                    {
                        AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                        ThrowOnCancel         = true // when you cancel the upload, exception is thrown. By default no exception is thrown
                    })
                                       .Child(eventType)
                                       .Child(filename)
                                       .PutAsync(stream, cancellation.Token);

                    try
                    {
                        ViewBag.p = await task;
                    }
                    catch (Exception ex)
                    {
                        uploaderror      = ex.Message;
                        ViewBag.uppError = uploaderror;
                    }
                }
            }
            else if (Request.Form["ImageChoice1"] == "1")
            {
                ApplicationUser appuser = await GetCurrentUser();

                var useremail = appuser.Email.ToString();
                //string fileLoc = @"c:\tmp\Test.txt";
                string     fileLoc = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", "Test.txt");
                FileStream file1   = new FileStream(fileLoc, FileMode.Open, FileAccess.ReadWrite);
                var        data    = "Document Initiazlized by:" + useremail + ", For the folder: " + eventType;
                byte[]     bytes   = Encoding.UTF8.GetBytes(data);
                file1.Write(bytes, 0, bytes.Length);
                file1.Dispose();


                FileStream file2 = new FileStream(fileLoc, FileMode.Open, FileAccess.Read);

                var auth = new FirebaseAuthProvider(new FirebaseConfig(_storageAccountOptions.apiKey));
                var a    = await auth.SignInWithEmailAndPasswordAsync(_storageAccountOptions.AuthEmail, _storageAccountOptions.AuthPassword);

                var cancellation = new CancellationTokenSource();
                var task         = new FirebaseStorage(
                    _storageAccountOptions.bucket,
                    new FirebaseStorageOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                    ThrowOnCancel         = true
                })
                                   .Child(eventType)
                                   .Child(useremail + ".txt")
                                   .PutAsync(file2, cancellation.Token);

                try
                {
                    ViewBag.p = await task;
                    file2.Dispose();
                }
                catch (Exception ex)
                {
                    uploaderror      = ex.Message;
                    ViewBag.uppError = uploaderror;
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(workOrder);
                await _context.SaveChangesAsync();

                ApplicationUser appuser = await GetCurrentUser();

                var      userFullName = appuser.FullName;
                MetaData mdt          = new MetaData();
                mdt.CreatedBy          = userFullName;
                mdt.CreatedDate        = DateTime.Now;
                mdt.ModifiedDate       = null;
                mdt.ModifiedStatusDate = null;
                mdt.WorkServiceID      = workOrder.WorkServiceID;
                _context.Add(mdt);
                _context.SaveChanges();

                if (_twilioSMS.Active == "true")
                {
                    try
                    {
                        string uemail          = workOrder.Contractor_Assigned;
                        var    userPhoneNumber = _context.Users.Where(s => s.Email == uemail)
                                                 .Select(s => new
                        {
                            s.PhoneNumber
                        })
                                                 .FirstOrDefault().PhoneNumber.ToString();

                        TwilioClient.Init(_twilioSMS.accountSid, _twilioSMS.authToken);
                        var to         = new PhoneNumber(userPhoneNumber);
                        var SMSmessage = MessageResource.Create(
                            to,
                            from: new PhoneNumber(_twilioSMS.TwilioNumber),
                            body: $"Hello {uemail} !!!, You have been assigned a new Work Order Service Request");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($" Registration Failure : {ex.Message} ");
                    }
                }



                return(RedirectToAction("Details", "WorkOrders", new { id = workOrder.WorkServiceID }));
            }

            return(View(workOrder));
        }
Ejemplo n.º 26
0
 public SmsService()
 {
     TwilioClient.Init(Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"),
                       Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"));
 }
Ejemplo n.º 27
0
 public TwilioSmsClient(string sid, string token, string from)
 {
     this.FromNumber = from;
     TwilioClient.Init(sid, token);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="TwilioClientWrapper"/> class.
        /// </summary>
        /// <param name="options">An object containing API credentials, a webhook verification token and other options.</param>
        public TwilioClientWrapper(TwilioClientWrapperOptions options)
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));

            TwilioClient.Init(Options.TwilioAccountSid, Options.TwilioAuthToken);
        }
Ejemplo n.º 29
0
        // POST: odata/Jobs
        public IActionResult Post([FromBody] Job job)
        {
            var currentUser = CurrentUser();

            // Ensure user is an administrator.
            if (!currentUser.CanCreateProjects)
            {
                return(Forbid());
            }

            var customer = _context.Customers
                           .Where(c => c.OrganizationId == currentUser.OrganizationId)
                           .Where(c => c.Id == job.CustomerId)
                           .FirstOrDefault();

            if (customer == null)
            {
                return(BadRequest());
            }

            // Auto-generated.
            job.CreatedAt  = DateTime.UtcNow;
            job.CustomerId = customer.Id;

            // Prepare to create tasks automatically.
            var taskTemplateId = job.TaskTemplateId;

            // Validate the model.
            ModelState.ClearValidationState(nameof(job));
            if (!TryValidateModel(job, nameof(job)))
            {
                var errors = new List <string>();

                foreach (var modelStateKey in ModelState.Keys)
                {
                    var value = ModelState[modelStateKey];

                    if (value == null)
                    {
                        continue;
                    }

                    foreach (var error in value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }

                var message = string.Join(", ", errors);
                return(BadRequest(message));
            }

            _context.Jobs.Add(job);

            _context.SaveChanges();

            if (taskTemplateId.HasValue)
            {
                var taskTemplate = _context.TaskTemplates
                                   .Where(c => c.OrganizationId == currentUser.OrganizationId)
                                   .Where(c => c.Id == taskTemplateId.Value)
                                   .FirstOrDefault();

                if (taskTemplate != null)
                {
                    var service = new SecurityService();

                    var items = JsonSerializer.Deserialize <TemplateItem[]>(taskTemplate.Template);

                    // Start ordering.
                    var order = 10;

                    foreach (var item in items)
                    {
                        // Get the next task number.
                        var maxSql = @"
                            SELECT
	                            MAX(CAST([T].[Number] AS INT))
                            FROM
                                [Tasks] AS [T]
                            JOIN
	                            [Jobs] AS [J] ON [J].[Id] = [T].[JobId]
                            JOIN
	                            [Customers] AS [C] ON [C].[Id] = [J].[CustomerId]
                            WHERE
	                            [C].[OrganizationId] = @OrganizationId;"    ;
                        var max    = _context.Database.GetDbConnection().QuerySingle <int?>(maxSql, new { OrganizationId = currentUser.OrganizationId });

                        // Either start at the default or increment.
                        var number = !max.HasValue ? "1000" : (max.Value + 1).ToString(); //service.NxtKeyCode(max);

                        // Find the base payroll rate for the new task.
                        var basePayrollRate = _context.Rates
                                              .Where(r => r.OrganizationId == currentUser.OrganizationId)
                                              .Where(r => r.Type == "Payroll")
                                              .Where(r => r.Name == item.BasePayrollRate)
                                              .Where(r => r.IsDeleted == false)
                                              .FirstOrDefault();

                        // Find the base service rate for the new task.
                        var baseServiceRate = _context.Rates
                                              .Where(r => r.OrganizationId == currentUser.OrganizationId)
                                              .Where(r => r.Type == "Service")
                                              .Where(r => r.Name == item.BaseServiceRate)
                                              .Where(r => r.IsDeleted == false)
                                              .FirstOrDefault();

                        // Populate the new task.
                        var task = new Brizbee.Core.Models.Task()
                        {
                            Name              = item.Name,
                            CreatedAt         = DateTime.UtcNow,
                            JobId             = job.Id,
                            Group             = item.Group,
                            Order             = order,
                            Number            = number,
                            BasePayrollRateId = basePayrollRate == null ? (int?)null : basePayrollRate.Id,
                            BaseServiceRateId = baseServiceRate == null ? (int?)null : baseServiceRate.Id
                        };

                        _context.Tasks.Add(task);
                        _context.SaveChanges();

                        // Increment the order.
                        order = order + 10;
                    }
                }
            }

            // Attempt to send notifications.
            try
            {
                var mobileNumbers = _context.Users
                                    .Where(u => u.IsDeleted == false)
                                    .Where(u => u.OrganizationId == currentUser.OrganizationId)
                                    .Where(u => !string.IsNullOrEmpty(u.NotificationMobileNumbers))
                                    .Select(u => u.NotificationMobileNumbers)
                                    .ToArray();

                var accountSid       = _configuration["TwilioNotificationsAccountSid"];
                var authToken        = _configuration["TwilioNotificationsAccountToken"];
                var fromMobileNumber = _configuration["TwilioNotificationsMobileNumber"];

                TwilioClient.Init(accountSid, authToken);

                foreach (var mobileNumber in mobileNumbers)
                {
                    var message = MessageResource.Create(
                        body: $"Project Added {job.Number} - {job.Name} for Customer {job.Customer.Name}",
                        from: new Twilio.Types.PhoneNumber(fromMobileNumber),
                        to: new Twilio.Types.PhoneNumber(mobileNumber)
                        );
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning(ex.ToString());
            }

            return(Created("", job));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Sends the specified rock message.
        /// </summary>
        /// <param name="rockMessage">The rock message.</param>
        /// <param name="mediumEntityTypeId">The medium entity type identifier.</param>
        /// <param name="mediumAttributes">The medium attributes.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Send(RockMessage rockMessage, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var smsMessage = rockMessage as RockSMSMessage;

            if (smsMessage != null)
            {
                // Validate From Number
                if (smsMessage.FromNumber == null)
                {
                    errorMessages.Add("A From Number was not provided.");
                    return(false);
                }

                string accountSid = GetAttributeValue("SID");
                string authToken  = GetAttributeValue("Token");
                TwilioClient.Init(accountSid, authToken);

                // Common Merge Field
                var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null, rockMessage.CurrentPerson);
                foreach (var mergeField in rockMessage.AdditionalMergeFields)
                {
                    mergeFields.AddOrReplace(mergeField.Key, mergeField.Value);
                }

                int?throttlingWaitTimeMS = null;
                if (this.IsLongCodePhoneNumber(smsMessage.FromNumber.Value))
                {
                    throttlingWaitTimeMS = this.GetAttributeValue("Long-CodeThrottling").AsIntegerOrNull();
                }

                List <Uri> attachmentMediaUrls = GetAttachmentMediaUrls(rockMessage.Attachments.AsQueryable());

                foreach (var recipientData in rockMessage.GetRecipientData())
                {
                    try
                    {
                        foreach (var mergeField in mergeFields)
                        {
                            recipientData.MergeFields.AddOrIgnore(mergeField.Key, mergeField.Value);
                        }

                        CommunicationRecipient communicationRecipient = null;

                        using (var rockContext = new RockContext())
                        {
                            CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService(rockContext);
                            int?recipientId = recipientData.CommunicationRecipientId.AsIntegerOrNull();
                            if (recipientId != null)
                            {
                                communicationRecipient = communicationRecipientService.Get(recipientId.Value);
                            }

                            string message = ResolveText(smsMessage.Message, smsMessage.CurrentPerson, communicationRecipient, smsMessage.EnabledLavaCommands, recipientData.MergeFields, smsMessage.AppRoot, smsMessage.ThemeRoot);

                            // Create the communication record and send using that.
                            if (rockMessage.CreateCommunicationRecord)
                            {
                                Person recipientPerson                 = ( Person )recipientData.MergeFields.GetValueOrNull("Person");
                                var    communicationService            = new CommunicationService(rockContext);
                                Rock.Model.Communication communication = communicationService.CreateSMSCommunication(smsMessage.CurrentPerson, recipientPerson?.PrimaryAliasId, message, smsMessage.FromNumber, string.Empty, smsMessage.communicationName);
                                rockContext.SaveChanges();
                                Send(communication, mediumEntityTypeId, mediumAttributes);
                                continue;
                            }
                            else
                            {
                                MessageResource response = SendToTwilio(smsMessage.FromNumber.Value, null, attachmentMediaUrls, message, recipientData.To);

                                if (response.ErrorMessage.IsNotNullOrWhiteSpace())
                                {
                                    errorMessages.Add(response.ErrorMessage);
                                }

                                if (communicationRecipient != null)
                                {
                                    rockContext.SaveChanges();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errorMessages.Add(ex.Message);
                        ExceptionLogService.LogException(ex);
                    }

                    if (throttlingWaitTimeMS.HasValue)
                    {
                        System.Threading.Tasks.Task.Delay(throttlingWaitTimeMS.Value).Wait();
                    }
                }
            }

            return(!errorMessages.Any());
        }