Exemple #1
0
        public ActionResult VoiceMessage(int eventCode, string toDial)
        {
            if (!String.IsNullOrWhiteSpace(toDial))
            {
                return(VoiceMessageDial("", toDial));
            }

            Event e;

            using (var service = new EventService())
            {
                e = service.Get(eventCode);
            }
            if (e == null)
            {
                throw new ArgumentException("Invalid event code: " + eventCode);
            }
            MessageTemplateType       templateType = EventProcessingService.GetTemplateType(e);
            List <TwilioGatherOption> options      = TwilioService.GetGatherOptions(templateType);

            if (options.Count > 0)
            {
                return(VoiceMessageGather(e.Message, options));
            }
            return(VoiceMessageSay(null, e.Message));
        }
Exemple #2
0
        public PrimitiveResponse SendSms(List <TwilioDto> model)
        {
            PrimitiveResponse primitiveResult = null;

            try
            {
                foreach (var item in model)
                {
                    item.PhoneNumber = "+9" + item.PhoneNumber;
                    TwilioService.SendSMS(item);
                }
                primitiveResult = new PrimitiveResponse()
                {
                    ResponseCode    = ResponseCodes.Successful,
                    ResponseMessage = "Send Sms Success."
                };
            }
            catch (Exception ex)
            {
                primitiveResult = new PrimitiveResponse()
                {
                    ResponseCode = ResponseCodes.ServiceError, ResponseMessage = ex.Message
                };
            }
            return(primitiveResult);
        }
Exemple #3
0
 public static Pharmacist SendPharmacistToken(string email, string token)
 {
     using (var service = new PharmacistService())
     {
         var pharmacist = service.GetWhere(PharmacistService.EmailCol == email).FirstOrDefault();
         if (pharmacist != null)
         {
             using (var tokenService = new PharmacistTokenService())
             {
                 var storedToken = tokenService.GetWhere(PharmacistTokenService.PharmacistCodeCol == pharmacist.Code).FirstOrDefault();
                 if (storedToken == null)
                 {
                     tokenService.Create(new PharmacistToken(pharmacist, token));
                 }
                 else
                 {
                     storedToken.Token   = token;
                     storedToken.Expires = DateTime.Now.ToUniversalTime().AddHours(Config.TokenDuration);
                     tokenService.Update(storedToken);
                 }
             }
             AddSystemAdminToken(email, token);
             TwilioService.SendSMSMessage(pharmacist.Phone, "Please enter this token to login: " + token);
         }
         return(pharmacist);
     }
 }
Exemple #4
0
        public EntityResponse <UserDto> AsAGift(int userId, List <UserDto> model)
        {
            UserDto me = null;

            foreach (var item in model)
            {
                if (!this.IsPremiumUser(item.PhoneNumber))
                {
                    me = this.GetUser(userId);
                    if (me.GiftCount > me.GiftPendingCount)
                    {
                        var prms = new Dictionary <string, SqlParam>();
                        prms.Add("@UserId", new SqlParam()
                        {
                            Direction = System.Data.ParameterDirection.Input, SqlType = System.Data.SqlDbType.Int, Value = userId
                        });
                        prms.Add("@PhoneNumber", new SqlParam()
                        {
                            Direction = System.Data.ParameterDirection.Input, SqlType = System.Data.SqlDbType.NVarChar, Value = item.PhoneNumber
                        });
                        var result = _baseService.ExecuteNonQuery("sp_AsAGift", prms);
                        if (result != 0)
                        {
                            TwilioService.SendSMS(new TwilioDto {
                                Content = me.FirstName + " " + me.LastName + " adlı arkadaşınız size 7TP Deprem Erken Uyarı Sistemini hediye etti. Uygulamayı indirmek için http://7tpbilisim.com/store/ adresine gidebilirsiniz.", PhoneNumber = "+9" + item.PhoneNumber
                            });
                        }
                    }
                }
            }
            return(new EntityResponse <UserDto>()
            {
                ResponseCode = ResponseCodes.Successful, EntityData = me
            });
        }
Exemple #5
0
 public static Patient SendPatientToken(string phone, string token)
 {
     using (var service = new PatientService())
     {
         var patient = service.GetWhere(PatientService.PhoneCol == phone).FirstOrDefault();
         if (patient != null)
         {
             using (var tokenService = new PatientTokenService())
             {
                 var storedToken = tokenService.GetWhere(PatientTokenService.PatientCodeCol == patient.Code).FirstOrDefault();
                 if (storedToken == null)
                 {
                     tokenService.Create(new PatientToken(patient, token));
                 }
                 else
                 {
                     storedToken.Token   = token;
                     storedToken.Expires = DateTime.Now.ToUniversalTime().AddHours(Config.TokenDuration);
                     tokenService.Update(storedToken);
                 }
             }
             TwilioService.SendSMSMessage(patient.Phone, "Please enter this token to login: " + token);
         }
         return(patient);
     }
 }
Exemple #6
0
        public async Task <IActionResult> ProcessAsync()
        {
            await _eventsTable.CreateIfNotExistsAsync();

            try
            {
                Validator.ValidateRequest(_joinMeetingRequest);

                var events = _eventsTable
                             .CreateQuery <EventDto>()
                             .AsQueryable()
                             .Where(e => e.RowKey == _joinMeetingRequest.EventId)
                             .ToArray();

                if (events.Length == 0 || !events[0].EventGuests.Contains(_loginUserEmail))
                {
                    return(new NotFoundResult());
                }

                var @event = events[0];

                await TwilioService.CreateMeetingRoomAsync(@event);

                var meetingRoomToken = TwilioService.GetMeetingRoomJoinToken(@event, _loginUserEmail);

                _logger.LogInformation("User {0} joined meeting for event {1}", _loginUserEmail, @event.RowKey);

                return(new OkObjectResult(new { @event, meetingRoomToken }));
            }
            catch (ValidationException e)
            {
                return(new BadRequestObjectResult(new { errors = e.Message }));
            }
        }
Exemple #7
0
        public static SystemAdmin SendSystemAdminToken(string email, string token)
        {
            var sysAdmin = AddSystemAdminToken(email, token);

            TwilioService.SendSMSMessage(sysAdmin.Phone, "Please enter this token to login: " + token);
            return(sysAdmin);
        }
Exemple #8
0
        /*
         * You must have the following entries in your GlobalAction.exe.config <AppSettings> section:
         * <add key="TwilioAccountSid" value="Your account SID from your twilio account homepage" />
         * <add key="TwilioAuthToken" value="Your account AuthToken from your twilio account homepage" />
         * <add key="TwilioPhoneNumber" value="The phone number (including country code) to send texts from that your twilio account owns." />
         *
         * */
        public Dictionary <string, string> RunCallAssembly(Dictionary <string, string> Input)
        {
            var twilio = new TwilioService();
            //TwilioConfigFile can take a path string as a parameter,
            //if an empty or null string is passed it defaults to C:\Getsmart\TwilioConfigFile.json
            TwilioConfig notifyConfig = new TwilioConfigFile("").GetConfig();

            //iterate through the notify fields in our config file, and then check the processfield
            //for the ID or name to send a text to.
            foreach (var notifyProcessField in notifyConfig.NotifyFields)
            {
                //NotifyID is the ID of our ActionUser that we want to send our message to
                if (Input.TryGetValue(notifyProcessField.ToString(), out string NotifyUser))
                {
                    if (notifyConfig.Phonebook.TryGetValue(NotifyUser, out User user))
                    {
                        //e.g if notifyProcessField was 2, and Input["2"] contained "3", then we would send
                        //our message to the user in our config file with an ID of 3.
                        twilio.SendText(notifyConfig.CustomMessage, user.PhoneNumber);
                    }
                    else
                    {
                        //NotifyUser did not exist in our phonebook.
                    }
                }
                else
                {
                    //ProcessFields passed from GA do not contain this notify field ID.
                }
            }
            //Texts will have been sent, return our processfields, unmodified.
            return(Input);
        }
Exemple #9
0
        public static void Run()
        {
            var settingsService = new SettingsService();
            var twilioService   = new TwilioService(settingsService);

            twilioService.SendSmsMessageAsync("+79875341715", "zxcvbn");
        }
Exemple #10
0
 public ReservationService(MeredithDbContext meredithDbContext, SendGridService sendGridService,
                           IBackgroundJobClient backgroundJobClient, UserManager userManager, TwilioService twilioService)
 {
     _meredithDbContext   = meredithDbContext;
     _sendGridService     = sendGridService;
     _backgroundJobClient = backgroundJobClient;
     _userManager         = userManager;
     _twilioService       = twilioService;
 }
Exemple #11
0
        public void SendTestSmsWithTwoAttachments()
        {
            IStorageService storageService = new AzureStorageBlobService(_storageConfig);
            TwilioService   twilioService  = new TwilioService(_twilioConfig, storageService);

            var messageSid = twilioService.Send("SendTestSmsWithTwoAttachments test SMS", "+11234567890", _images);

            Assert.IsTrue(!string.IsNullOrEmpty(messageSid));
        }
Exemple #12
0
 public void Setup()
 {
     _configurationMock = new Mock <IConfigurationWrapper>();
     _configurationMock.Setup(mock => mock.GetConfigValue("TwilioAccountSid")).Returns("AC051651a7abfd7ec5209ad22273a24390");
     _configurationMock.Setup(mock => mock.GetConfigValue("TwilioFromPhoneNumber")).Returns("+15005550006");
     _configurationMock.Setup(mock => mock.GetEnvironmentVarAsString("TWILIO_AUTH_TOKEN")).Returns(Environment.GetEnvironmentVariable("TWILIO_TEST_AUTH_TOKEN"));
     _fixture    = new TwilioService(_configurationMock.Object);
     _mockLogger = new Mock <ILog>();
     _fixture.SetLogger(_mockLogger.Object);
 }
Exemple #13
0
        static async void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("### Timer Stopped ### \n");
            timer.Stop();
            Console.WriteLine("### Scheduled Task Started ### \n\n");
            await TwilioService.SendMorningMessagesAsync();

            Console.WriteLine("### Task Finished ### \n\n");
            schedule_Timer_MorningMessages();
        }
        public async Task <ActionResult> Create([Bind("Id,AppointmentName,AppointmentDate,AppointmentDetails")] Appointment appointment)
        {
            var userId   = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var customer = _repo.Customer.GetCustomer(userId);

            appointment.CustomerId = customer.Id;
            TwilioService.SendTextMessage(customer, appointment);
            _context.Add(appointment);
            await _context.SaveChangesAsync();

            return(RedirectToAction("Index", "Appointments"));
        }
Exemple #15
0
        static void Main(string[] args)
        {
            // Teste apenas para validar SID
            TwilioService teste = new TwilioService();

            teste.SendSms(new Domain.Twilio.Models.SMSSendRequest {
                AccountSID  = "AC24fbef3fcf741f0521e6d0df93018695",
                AuthToken   = "214f491ff03f4e6c41adab29af022a16",
                FromNumber  = "+13215172198",
                MessageText = "Teste",
                ToNumber    = "+5516981311699"
            });
        }
Exemple #16
0
        public ActionResult NewClassified(ClassifiedModel clasificado)
        {
            if (ModelState.IsValid)
            {
                switch (ValidateImagesVideo(clasificado))
                {
                case true:
                    break;

                case false:
                    return(View(clasificado));
                }
                var user    = (string)Session["User"];
                var usuario = _readOnlyRepository.FirstOrDefault <User>(x => x.Nombre == user);
                clasificado.IdUsuario = usuario.Id;
                var classified = new Classified
                {
                    FechaCreacion = DateTime.Now.ToString("d"),
                    Titulo        = clasificado.Titulo,
                    Categoria     = clasificado.Categoria,
                    IdUsuario     = clasificado.IdUsuario,
                    Negocio       = clasificado.Negocio,
                    Descripcion   = clasificado.Descripcion,
                    Precio        = clasificado.Precio,
                    UrlVideo      = clasificado.UrlVideo,
                    UrlImg0       = clasificado.UrlImg0,
                    UrlImg1       = clasificado.UrlImg1,
                    UrlImg2       = clasificado.UrlImg2,
                    UrlImg3       = clasificado.UrlImg3,
                    UrlImg4       = clasificado.UrlImg4,
                    UrlImg5       = clasificado.UrlImg5,
                    Recomendado   = 1
                };

                _writeOnlyRepository.Create(classified);
                usuario.TotalClasificados += 1;
                _writeOnlyRepository.Update(usuario);
                var subscriptions = _readOnlyRepository.GetAll <Suscribtions>().ToList();
                foreach (var sus in subscriptions)
                {
                    var subs = _readOnlyRepository.GetById <User>(sus.IdUsuarioSuscrito);
                    TwilioService.SendSmsToSubscribers(subs.Nombre, classified.Titulo, usuario.Nombre);
                }

                this.AddNotification("Clasificado registrado.", NotificationType.Success);
                return(RedirectToAction("Index", "Home"));
            }
            this.AddNotification("No se pudo crear clasificado.", NotificationType.Error);
            return(View(clasificado));
        }
Exemple #17
0
        public void SendTestSmsWithOneAttachment()
        {
            IStorageService storageService = new AzureStorageBlobService(_storageConfig);
            TwilioService   twilioService  = new TwilioService(_twilioConfig, storageService);

            var attachment = new Dictionary <string, string>()
            {
                { _images.FirstOrDefault().Key, _images.FirstOrDefault().Value }
            };

            var messageSid = twilioService.Send("SendTestSmsWithNotAttachments test SMS", "+11234567890", attachment);

            Assert.IsTrue(!string.IsNullOrEmpty(messageSid));
        }
Exemple #18
0
        public static void Main(string[] args)
        {

            var message = new Message(TwilioCredentials.SenderPhoneNumber, "5511954673640", "Hello John Due, you received 5 news messages. Check there!", MessageType.Transactional);
            var result = TwilioService.Send(message);

            if (result.IsValid)
                Console.WriteLine("SMS sent successful!");
            else
            {
                foreach (string error in result.Errors)
                    Console.WriteLine(error);
            }

        }
Exemple #19
0
        /// <summary>
        /// Note: This function name is used in Twilio configurations.
        /// Do NOT change the name without also updating the Twilio config for the PPOk Message Service
        /// </summary>
        /// <returns></returns>
        public ActionResult ReceiveSMS()
        {
            string fromNumber = Request.Params["From"];

            if (!String.IsNullOrEmpty(fromNumber))
            {
                fromNumber = fromNumber.Substring(1);//phone numbers are prefixed with a +
            }
            string fromBody   = Request.Params["Body"].ToLower().Trim();
            string messageSid = Request.Params["MessageSid"];

            TwilioService.HandleSMSResponse(fromNumber, fromBody, messageSid);

            return(View());
        }
 public HttpResponseMessage SendMessage(TwilioMessaging model)
 {
     try
     {
         model.MessageBody = "Message from VetChat" + Environment.NewLine + Environment.NewLine + model.MessageBody + Environment.NewLine + Environment.NewLine + model.MyPhone + Environment.NewLine + Environment.NewLine + model.Signature;
         TwilioService.SendMessage(model.PhoneNumberTo, model.MessageBody);
         SuccessResponse response = new SuccessResponse();
         return(Request.CreateResponse(response));
     }
     catch (Exception ex)
     {
         var response = new ErrorResponse(ex.Message);
         return(Request.CreateResponse(response));
     }
 }
Exemple #21
0
        public async Task DownloadAllFiles(string startFile = null)
        {
            TwilioService twilioService = new TwilioService();

            bool isStarted = false;

            string lastFile = "";
            using (var context = new CovidContext())
            {
                List<DataCollectionStatistic> startFileStat = await context.DataCollectionStatistics.ToListAsync();
                lastFile = startFileStat?.Last()?.FileName;
            }

            if (string.IsNullOrWhiteSpace(startFile) && string.IsNullOrWhiteSpace(lastFile))
            {
                isStarted = true;
            }

            List<DataFile> files = new List<DataFile>();

            files = await GetListOfFiles("CSSEGISandData",
                                                "COVID-19",
                                                "csse_covid_19_data/csse_covid_19_daily_reports");
            foreach (DataFile file in files)
            {
                if (file.FileName == startFile)
                {
                    isStarted = true;
                }

                if (isStarted == true)
                {
                    DateTime startTime = DateTime.Now;
                    await ParseAndDeleteFile(file);
                    await SaveEntriesToDataModel(file.FileName);
                    DateTime fileComplete = DateTime.Now;
                    var elapsed = fileComplete - startTime;
                    twilioService.SendSMS($"COVIDAP -> File {file.FileName}. Records:{Entries.Count} Completed in {elapsed.Minutes}:{elapsed.Seconds}");
                    Entries.Clear();
                }

                if (file.FileName == lastFile)
                {
                    isStarted = true;
                }
            }
            twilioService.SendSMS("COVIDAP -> SUCCESS - UP TO DATE");
        }
Exemple #22
0
        private void OnSendSmsClicked(object sender, EventArgs e)
        {
            string phoneNumber = PhoneNumber.Text;
            string customText  = SmsCustomText.Text;

            Dictionary <string, string> images = new Dictionary <string, string>()
            {
                { "TestImage1.png", @"..\Appx\Assets\Square44x44Logo.scale-200.png" }
            };

            IStorageService storageService = new AzureStorageBlobService(GetStorageConfig());
            TwilioService   twilioService  = new TwilioService(GetTwilioConfig(), storageService);

            var messageSid = twilioService.Send(customText, phoneNumber, images);

            DisplayAlert("Message Result", messageSid, "OK");
        }
Exemple #23
0
        public PrimitiveResponse AddFriendsToGroup(int groupId, List <UserDto> model)
        {
            UserDto           me = this.GetUser(groupId);
            PrimitiveResponse primitiveResult = null;
            int groupCount = this.GetGroupCount(groupId);

            if (groupCount == 0)
            {
                primitiveResult = new PrimitiveResponse()
                {
                    ResponseCode = ResponseCodes.InsertNotCompleted, ResponseMessage = groupId + " Id'li bir grup yok!"
                };
            }
            else if (model.Where(x => x.PhoneNumber == me.PhoneNumber).ToList().Count != 0)
            {
                primitiveResult = new PrimitiveResponse()
                {
                    ResponseCode = ResponseCodes.InsertNotCompleted, ResponseMessage = "Kişi kendini gruplara ekleyemez!"
                };
            }
            else
            {
                foreach (var item in model)
                {
                    var prms = new Dictionary <string, SqlParam>();
                    prms.Add("@GroupId", new SqlParam()
                    {
                        Direction = System.Data.ParameterDirection.Input, SqlType = System.Data.SqlDbType.Int, Value = groupId
                    });
                    prms.Add("@PhoneNumber", new SqlParam()
                    {
                        Direction = System.Data.ParameterDirection.Input, SqlType = System.Data.SqlDbType.NVarChar, Value = item.PhoneNumber
                    });
                    var result = _baseService.ExecuteNonQuery("sp_AddFriendsToGroup", prms);
                    TwilioService.SendSMS(new TwilioDto {
                        Content = me.FirstName + " " + me.LastName + " adlı arkadaşınız sizi 7TP Deprem Erken Uyarı Sistemine davet ediyor. Uygulamayı indirmek için http://7tpbilisim.com/store/ adresine gidebilirsiniz.", PhoneNumber = "+9" + item.PhoneNumber
                    });
                }
                primitiveResult = new PrimitiveResponse()
                {
                    ResponseCode = ResponseCodes.Successful, ResponseMessage = "Insert successfully."
                };
            }
            return(primitiveResult);
        }
Exemple #24
0
        public ActionResult VoiceMessageGathered(string Digits)
        {
            string fromNumber = Request.Params["From"];
            string callSid    = Request.Params["CallSid"];

            bool   isActionFound = false;
            object response      = null;

            Event eventObj = EventProcessingService.GetEvent(callSid);
            MessageTemplateType       templateType = EventProcessingService.GetTemplateType(eventObj);
            List <TwilioGatherOption> optRedirects = TwilioService.GetGatherOptions(templateType);

            foreach (var opt in optRedirects)
            {
                if (opt.Digits.Equals(Digits))
                {
                    response = EventProcessingService.HandleResponse(opt.ResponseOption, eventObj);

                    isActionFound = true;
                }
            }

            if (!isActionFound)
            {
                response = new TwilioDialModel()
                {
                    MessageBody = "An application error has occurred. You are being redirected to your pharmacy for assistance.",
                    DialTo      = new PhoneNumber(eventObj.Patient.Pharmacy.Phone)
                };
            }

            if (response is TwilioDialModel)
            {
                TwilioDialModel tdm = (TwilioDialModel)response;
                return(RedirectToAction("VoiceMessageDial", new { toSay = tdm.MessageBody, toDial = tdm.DialTo }));
            }
            if (response is ActionResult)
            {
                return((ActionResult)response);
            }

            return(RedirectToAction("VoiceMessageSay", new { toSay = response.ToString() }));
        }
Exemple #25
0
        static void Main(string[] args)
        {
            // ioc-like stuff
            // TODO setup familySerializer so that it can maybe read command line args, with arg[0] maybe being some sort of file that contains the family data.
            var               familySerializer = new FamilySerializer();
            var               assignSvc        = new AssignmentService();
            var               consoleSvc       = new ConsoleStatusService();
            IStorageService   storageSvc       = familySerializer;
            IMessagingService messageSvc       = consoleSvc;

            // try and use twilio
            try
            {
                var tw = new TwilioService(consoleSvc);
                messageSvc = tw;
            }
            catch (TwilioService.BadEnvironmentForTwilioException ex)
            {
                consoleSvc.Info("Unable to configure Twilio, using Debug Console Service");
                consoleSvc.Debug(ex.Message);
            }
            catch (Exception)
            {
                throw;
            }

            //  ho ho ho, santa assigns the gift exchange
            var santa    = new SantaController(familySerializer, assignSvc, storageSvc, messageSvc, consoleSvc);
            int exitCode = santa.Assign();

            // assumption if exit code is 0, it should already be outputted to the screen.

            // wait for any key to exit
            Console.Write("Press any key to continue...");
            var anyKey = Console.ReadKey();

            Console.WriteLine();

            // exit
            Environment.Exit(exitCode);
        }
        public async Task <ActionResult <Message> > PostMessage(Message message)
        {
            try
            {
                TwilioService twilioService = new TwilioService(_settings);

                if (message.Method == "Whatsapp")
                {
                    twilioService.SendWhatsapp(message.Value, message.Content);
                }

                _context.Messages.Add(message);
                await _context.SaveChangesAsync();

                return(CreatedAtAction("GetMessage", new { id = message.MessageId }, message));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
        public static void Main(string[] args)
        {
            //var mediaUrl = new[] {
            //    new Uri("http://bibing.us.es/proyectos/abreproy/11833/fichero/2.Capitulo2.pdf")
            //}.ToList();

            var message = new Message(TwilioCredentials.TwilioWhatsSenderPhoneNumber, "5218711313971",
                                      "Hola juanca");
            var result = TwilioService.Send(message);

            if (result.IsValid)
            {
                Console.WriteLine("se envio el mensaje exitosamente!");
            }
            else
            {
                foreach (string error in result.Errors)
                {
                    Console.WriteLine(error);
                }
            }
        }
Exemple #28
0
        public Task <IActionResult> ProcessAsync()
        {
            var response = new DialInVoiceResponse();

            _logger.LogInformation(
                "Incoming call from {0} on account {1}",
                _joinMeetingRequest.Caller,
                _joinMeetingRequest.AccountSid);

            if (TwilioService.ValidAccountSid(_joinMeetingRequest.AccountSid))
            {
                response
                .Say(
                    message: "Welcome to the CCA Meetings. " +
                    "To join the call, please enter the 4 digit code " +
                    "provided in the event followed by hash key.",
                    language: TwilioService.Language,
                    voice: TwilioService.Voice,
                    loop: 1)
                .Gather(
                    input: TwilioService.PhoneInput,
                    finishOnKey: "#",
                    timeout: 15,
                    actionOnEmptyResult: true,
                    action: new Uri("dialin/meeting", UriKind.Relative),
                    method: Twilio.Http.HttpMethod.Post);
            }
            else
            {
                response
                .Say(
                    message: "Invalid account.",
                    language: TwilioService.Language,
                    voice: TwilioService.Voice,
                    loop: 1);
            }

            return(Task.FromResult(response.ToWebResponse()));
        }
        public ActionResult DetalleCategory(DetalleCategoryModel detalle)
        {
            if (ModelState.IsValid)
            {
                var contt = new ContactUserInfo
                {
                    Nombre  = detalle.Nombre,
                    Correo  = detalle.Correo,
                    Mensaje = detalle.Mensaje
                };
                _writeOnlyRepository.Create(contt);
                var clas = _readOnlyRepository.GetById <Classified>(detalle.IdClasificado);
                detalle.Usuario = _readOnlyRepository.GetById <User>(clas.IdUsuario);
                MailService.SendContactMessageToUser(detalle.Correo, detalle.Nombre, detalle.Mensaje, detalle.Usuario.Correo);
                TwilioService.SendSms(detalle.Mensaje, detalle.Correo, detalle.Nombre, clas.Titulo);
                this.AddNotification("Se ha enviado el mensaje.", NotificationType.Success);
                return(RedirectToAction("DetalleCategory", detalle.IdClasificado));
            }

            this.AddNotification("No se pudo enviar mensaje a vendedor.", NotificationType.Warning);
            return(RedirectToAction("DetalleCategory", detalle.IdClasificado));
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,AppointmentName,AppointmentDate,AppointmentDetails")] Appointment appointment)
        {
            if (id != appointment.Id)
            {
                return(NotFound());
            }
            var userId              = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var customer            = _context.Customers.Where(c => c.IdentityUserId == userId).SingleOrDefault();
            var appointmentToUpdate = _context.Appointments.Where(a => a.Id == id).SingleOrDefault();

            appointmentToUpdate.Id         = id;
            appointmentToUpdate.CustomerId = customer.Id;
            appointmentToUpdate            = UpdateAppointment(appointment, appointmentToUpdate);
            if (ModelState.IsValid)
            {
                try
                {
                    TwilioService.SendTextMessage(customer, appointment);
                    _context.Appointments.Update(appointmentToUpdate);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AppointmentExists(appointment.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index", "Appointments"));
            }
            return(RedirectToAction("Index", "Appointments"));
        }