private async void DoWork(object state) { using (var scope = _services.CreateScope()) { var _context = scope.ServiceProvider .GetRequiredService <PatientsDbContext>(); var citasParaAvisar = _context.CalendarEvents.Where(x => !x.IsSMSSended && x.Start > DateTime.Now && (x.Start - DateTime.Now).Days < 1).Include(x => x.Paciente).Include(x => x.TipoCita); foreach (var cita in citasParaAvisar) { if (cita.Paciente is null && cita.TipoCita.Tipo == "Personal") { var mensaje = new Sms { message = $"Tienes {cita.Subject ?? "SinSujeto"}-{cita.Description ?? "SinDescripcion"} el día {cita.Start.ToString("dd-MM-yyyy")} a las {cita.Start.ToString("HH:mm")}", msisdn = null }; cita.IsSMSSended = _smsService.SendSms(mensaje); } //TODO Añadir esta parte cuando Nuria lo vea bien //else if (!(cita.Paciente.Telefono2 is null)) //{ // string strMessage = $"Le recordamos su cita podológica el {cita.Start.ToString("dd-MM-yyyy")} a las {cita.Start.ToString("HH:mm")}"; // cita.IsSMSSended = _smsService.SendSMS(cita.Paciente.Telefono2, "Akari Podología", strMessage); //} } await _context.SaveChangesAsync(); } }
public async Task <IActionResult> ChangePhoneNumber(string username, string password, string phonenumber, [FromServices] ISmsSender smsSender) { var pars = new[] { username, phonenumber, password }; if (pars.Any(string.IsNullOrWhiteSpace)) { return (Res.PlainUtf8( "One or more of required fields username, phonenumber and password were missing or empty.", 400)); } var user = await _userManager.FindByNameAsync(username); if (user == null) { return(Res.PlainUtf8("User does not exist", 400)); } // Need to do a manual check as the user cannot log in and authorize before confirming the phone number. var pass = await _userManager.CheckPasswordAsync(user, password); if (!pass) { return(Res.PlainUtf8("Invalid password", 400)); } var phoneToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phonenumber); if (!await smsSender.SendSms($"QB sign-up code:{phoneToken}", phonenumber)) { return(Res.PlainUtf8("User created but sms failed, try re-requesting code by changing phonenumber.", 400)); } return(Res.PlainUtf8($"New phone code texted for {username}.")); }
public ActionResult AnalysisFinished(string vmId, string location) { Analysis analysis; // Check if an analysis is found that matches vmID if (_context.VirtualMachines.Select(i => i.Analysis).Any(i => i.VirtualMachine.Id == vmId)) { // if found then change the location to the given string and update the db analysis = _context.VirtualMachines.Select(i => i.Analysis).FirstOrDefault(i => i.VirtualMachine.Id == vmId); if (analysis != null) { var vm = _context.VirtualMachines.FirstOrDefault(i => i.Analysis.Id == analysis.Id); vm.Analysis = null; //TODO: Fix vm.CompletionDate = null; analysis.ResultFilePath = location; _context.Analyses.Update(analysis); _context.VirtualMachines.Update(vm); _context.SaveChanges(); //send message to the user var phone = ""; foreach (var user in _context.Users) { if (user.Analyses.FirstOrDefault(i => i.Id == analysis.Id) != null) { phone = user.Phone; } } _smsSender.SendSms(new AuthMessageSender.Message { Body = "Greetings" + "\nAn analysis that you recently requested has been completed" + "\n" + "Please, login to 3DCytoFlow to see the results\n" }, _sid, _authToken, _number, phone); } // return something else here? Not sure what to return for working result return(Ok()); } // if the analysis does not exist // this should not be triggered return(HttpBadRequest()); }
public string SendCode(string mobile, string content, string codePlaceholder = "{code}") { var code = createRandom(); var textToSendWithCode = content.Replace(codePlaceholder, code); _smsSender.SendSms(mobile, textToSendWithCode); return(code); }
public void Execute(IJobExecutionContext context) { List <SmsToSend> smsTosend = _notificationQueue.GetUnsentSmses(); foreach (var sms in smsTosend) { _smsSender.SendSms(sms); sms.HasBeenSent = true; } }
public void PerformTask(InsideModel.Models.Task taskMessage) { var sendSmsToUserTask = JsonConvert.DeserializeObject <UserSpecificSmsNotificationTaskMessage>(taskMessage.Message); var user = userRepository.Single(u => u.Id == sendSmsToUserTask.UserId); var defintion = smsDefinitionBuilder.GetDefinition(sendSmsToUserTask.ContactId, sendSmsToUserTask.UserId); if (defintion != null) { smsSender.SendSms(user.Phone, defintion); } }
public async Task <IActionResult> Register(string username, string password, string phonenumber, [FromServices] ISmsSender smsSender, [FromServices] QbDbContext db) { var pars = new[] { username, password, phonenumber }; if (pars.Any(string.IsNullOrWhiteSpace)) { return(Res.JsonErrorResult("missing_field", 400, "One or more of required fields missing or empty: username, password, phonenumber.")); } var exists = null != await _userManager.FindByNameAsync(username); if (exists) { return(Res.JsonErrorResult("exists", 400, "Username already exists.")); } var user = new QbUser { UserName = username, PhoneNumberConfirmed = false }; var res = await _userManager.CreateAsync(user, password); if (res.Succeeded) { user = await _userManager.FindByNameAsync(username); // Creates a full user with all edit abilities for own information. var userGuid = new Guid(user.Id); // Create a Person with the same guid as the identity user. await CreatePerson(userGuid, db); var phoneToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phonenumber); // Ignore used for manual admin verified user. if (phonenumber.ToLowerInvariant() != "ignore") { if (!await smsSender.SendSms($"QB sign-up code:{phoneToken}", phonenumber)) { return (Res.JsonErrorResult("invalid_phone", 400, "User created but sms failed, try re-requesting code by changing phonenumber.")); } } return(Res.PlainUtf8($"User {username} successfully created, needs verification.")); } return(Res.JsonErrorResult("identity_error", 400, res.PrettyErrors())); }
public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Address = model.WorkAddress, FirstName = model.FirstName, LastName = model.LastName, City = model.City, DOB = model.DOB, Phone = model.Phone, Zip = model.Zip }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Send an email with this link var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, Request.Scheme); var message = new AuthMessageSender.Message { Subject = "Confirm account", Body = "Please confirm " + user.FirstName + " " + user.LastName + " account by clicking: <a href='" + callbackUrl + "'>this link</a></br>" + "You can login using the following password: "******"</br>" + "Please, once logged in change your password for security reasons. Enjoy" }; await _emailSender.SendEmailAsync(model.Email, message.Subject, message.Body, _userEmailAccount, _userEmailPassword); message.Body = "You have been registered into 3DCytoFlow! Please, check your email to confirm your account"; _smsSender.SendSms(message, _sid, _authToken, _number, user.Phone); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToAction(nameof(HomeController.Index), "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
public ResultMessage SendSms(InstantSmsMessage smsNotification) { ResultMessage smsResult = new ResultMessage { MessageStatus = SmsMessageStatus.Ok }; try { SmsMessage smsMessage = new SmsMessage(smsNotification.MobilePhone, smsNotification.ServerMessageId, smsNotification.MessageText); if (DateTime.Now > smsNotification.ExpiredTime) { smsResult.ErrorDescription = "Время отправки Sms сообщения вышло"; return(smsResult); } var result = smsSender.SendSms(smsMessage); logger.Info($"Отправлено уведомление. Тел.: {smsMessage.MobilePhoneNumber}, результат: {result.Status}"); switch (result.Status) { case SmsSentStatus.InvalidMobilePhone: smsResult.ErrorDescription = $"Неверно заполнен номер мобильного телефона. ({smsNotification.MobilePhone})"; break; case SmsSentStatus.TextIsEmpty: smsResult.ErrorDescription = $"Не заполнен текст сообщения"; break; case SmsSentStatus.SenderAddressInvalid: smsResult.ErrorDescription = $"Неверное имя отправителя"; break; case SmsSentStatus.NotEnoughBalance: smsResult.ErrorDescription = $"Недостаточно средств на счете"; break; case SmsSentStatus.UnknownError: smsResult.ErrorDescription = $"{result.Description}"; break; } } catch (Exception ex) { smsResult.ErrorDescription = $"Ошибка при отправке смс сообщения. {ex.Message}"; logger.Error(ex); } return(smsResult); }
public GetCustomerCreditDto CheckCreditAvailibility(CustomerCreditDto dto) { var customerCredit = new GetCustomerCreditDto { CreditResult = CreditResultType.Reject, CreditLimit = 0, CreditResultReason = string.Empty }; try { if (dto != null) { // Normalde Kredi skoru bilgisi servisten gelmelidir. var customerScore = _customerScore.Get(x => x.IdentityNumber == dto.IdentityNumber); if (customerScore == null) { logger.Info($"Identity number could not found!"); return(customerCredit); } customerCredit = GetCustomerCredit(customerScore, dto.MonthlyIncome); CreateCustomer(dto, customerCredit.CreditLimit); CreateCustomerHistory(dto.IdentityNumber, customerCredit.CreditResult, customerScore.Score); //Sms gönderme işlemi _smsSender.SendSms(new SendSmsDto()); } return(customerCredit); } catch (Exception ex) { logger.Error($"An error occurred : {ex.Message}"); throw new Exception(ex.Message); } }
public Task StartAsync(CancellationToken cancellationToken) { var conf = new ConsumerConfig { GroupId = "st_consumer_group", BootstrapServers = _bootstrapServers, AutoOffsetReset = AutoOffsetReset.Latest }; using (var builder = new ConsumerBuilder <Ignore, string>(conf).Build()) { builder.Subscribe(topic); var cancelToken = new CancellationTokenSource(); try { while (true) { var consumer = builder.Consume(cancelToken.Token); var jObject = JObject.Parse(consumer.Message.Value); var phone = (string)jObject["phone"]; var email = (string)jObject["email"]; _sender.SendSms(new SmsMessage { From = "+19149964683", Message = $"Message: {consumer.Message.Value} received from {consumer.TopicPartitionOffset}", To = "+380638680809" }); Console.WriteLine($"Message: {consumer.Message.Value} received from {consumer.TopicPartitionOffset}"); } } catch (Exception) { builder.Close(); } } return(Task.CompletedTask); }
private void SendNotification(NewClientSmsNotification notification) { try { SmsMessage smsMessage = new SmsMessage(notification.MobilePhone, notification.Id.ToString(), notification.MessageText); var result = smsSender.SendSms(smsMessage); logger.Info($"Отправлено уведомление. Тел.: {smsMessage.MobilePhoneNumber}, результат: {result.Status}"); notification.ServerMessageId = result.ServerId; notification.Status = result.Status == SmsSentStatus.Accepted ? SmsNotificationStatus.Accepted : SmsNotificationStatus.Error; switch (result.Status) { case SmsSentStatus.InvalidMobilePhone: notification.ErrorDescription = $"Неверно заполнен номер мобильного телефона. ({notification.MobilePhone})"; break; case SmsSentStatus.TextIsEmpty: notification.ErrorDescription = $"Не заполнен текст сообщения"; break; case SmsSentStatus.SenderAddressInvalid: notification.ErrorDescription = $"Неверное имя отправителя"; break; case SmsSentStatus.NotEnoughBalance: notification.ErrorDescription = $"Недостаточно средств на счете"; break; case SmsSentStatus.UnknownError: notification.ErrorDescription = $"{result.Description}"; break; } } catch (Exception ex) { notification.ErrorDescription = $"Ошибка при отправке смс сообщения. {ex.Message}"; logger.Error(ex); } }
public ActionResult LoadClients() { var clientToDelete = new List<ClientTableModel>(); try { //create import log var importLogId = FileLoadHelper.AddImportLog();//?? foreach (string upload in Request.Files) { //upload file if (!Request.Files[upload].HasFile()) continue; string path = AppDomain.CurrentDomain.BaseDirectory; string filename = Path.GetFileName(Request.Files[upload].FileName); Request.Files[upload].SaveAs(Path.Combine(path, filename)); //add importLogFile FileLoadHelper.AddImportLogFile(importLogId, Path.Combine(path, filename)); //get filtering constants var clientSheetName = _unitOfWork.SystemConstantsRepository.GetConstantByName<string>(Resource.ClientSheetName); var clientPhoneStartWith = _unitOfWork.SystemConstantsRepository.GetConstantByName<string>(Resource.ClientPhoneStartWith); var defaultCountry = _unitOfWork.SystemConstantsRepository.GetConstantByName<string>(Resource.DefaultCountry); var clientPhoneLength = _unitOfWork.SystemConstantsRepository.GetConstantByName<string>(Resource.ClientPhoneLength); //read clients info from file var excel = new ExcelQueryFactory(); excel.FileName = path + filename; var allClients = from client in excel.Worksheet<ClientExcelModel>(clientSheetName) where client.country == defaultCountry && client.phone != null && client.phone.StartsWith(clientPhoneStartWith) select client; var clientsList = allClients.ToList(); var resultClientList = new List<Client>(); //add clients to resultList (filtering clients) foreach (var client in clientsList) { if (Regex.IsMatch(client.phone, @"^\d{" + clientPhoneLength + "}$") && !resultClientList.Where(t => t.UserName == client.username && t.Phone == client.phone).Any()) { var newClient = new Client { Id = Guid.NewGuid(), UserName = client.username, FirstName = FileLoadHelper.FirstCharToUpper(client.first_name), LastName = FileLoadHelper.FirstCharToUpper(client.last_name), Country = client.country, RegistrationDate = client.registration_date, Phone = client.phone, Dreams = client.number_dreams, Email = client.email, UpdatedDate = DateTime.UtcNow, LoadedDate = DateTime.UtcNow, IsSentReminderSms = false }; resultClientList.Add(newClient); } } // add client to DB and update var updatedClients = FileLoadHelper.UpdateClients(resultClientList, importLogId); var isSMSSendingEnabled = Convert.ToBoolean(Session["isSMSSendingEnabled"]); // add new client AddNewClients(updatedClients.NewClients, isSMSSendingEnabled); //update client with changed UserName UpdateClients(updatedClients.UpdatedClients); //send first dreams sms if (updatedClients.FirstDreamClients.Any()) { //send sms _smsSender = new FirstDreamsSMSSender(); _smsSender.SendSms(isSMSSendingEnabled, updatedClients.FirstDreamClients, new Guid(), string.Empty); } foreach (var client in updatedClients.DeletedClients) { var convertedClient = ClientTableModel.ClientViewModelConverter(client); clientToDelete.Add(convertedClient); } TempData["ClientToDelete"] = clientToDelete; TempData["ClientsWithIncrementedDreams"] = updatedClients.ClientsWithIncrementedDreams; } } catch (Exception exception) { throw; } return RedirectToAction("Clients"); }
void BalanceNotifier_OnBalanceChange(object sender, SmsBalanceEventArgs e) { try { if (e.BalanceType != BalanceType.CurrencyBalance) { return; } decimal currentBalanceLevel = e.Balance; decimal minBalanceLevel = smsNotifierParametersProvider.GetLowBalanceLevel(); var unformedPhone = smsNotifierParametersProvider.GetLowBalanceNotifiedPhone(); if (string.IsNullOrWhiteSpace(unformedPhone)) { return; } string notifiedPhone = FormatPhone(unformedPhone) ?? throw new InvalidProgramException( $"Неверно заполнен номер телефона ({unformedPhone}) для уведомления о низком балансе денежных средств на счете"); string notifyText = smsNotifierParametersProvider.GetLowBalanceNotifyText(); notifyText = notifyText.Replace("$balance$", currentBalanceLevel.ToString("0.##")); using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) { var notification = uow.Session.QueryOver <LowBalanceSmsNotification>() .Where(x => x.Status == SmsNotificationStatus.New) .OrderBy(x => x.NotifyTime).Desc .Take(1) .SingleOrDefault(); if (notification == null) { if (currentBalanceLevel < minBalanceLevel) { notification = new LowBalanceSmsNotification() { Balance = currentBalanceLevel, MessageText = notifyText, MobilePhone = notifiedPhone, NotifyTime = DateTime.Now, Status = SmsNotificationStatus.New }; uow.Save(notification); uow.Commit(); logger.Info("Создано новое уведомление о низком балансе на счете"); var result = smsSender.SendSms(new SmsMessage(notification.MobilePhone, notification.Id.ToString(), notification.MessageText)); if (result.Status == SmsSentStatus.Accepted) { notification.ServerMessageId = result.ServerId; } else { notification.ErrorDescription = $"Ошибка. Статус сообщения: {result.Status}"; } uow.Save(notification); uow.Commit(); } } else { if (currentBalanceLevel < minBalanceLevel) { //Ничего не отправляем, так как уже было уведомление о низком балансе return; } if (currentBalanceLevel > minBalanceLevel) { //Меняем статус уведомления на принятый, так как было поступление средств на счет notification.Status = SmsNotificationStatus.Accepted; uow.Save(notification); uow.Commit(); logger.Info("Баланс был пополнен, уведомление о низком балансе закрыто"); } } } } catch (Exception ex) { logger.Fatal(ex); } }
private void AddNewClients(List<Client> clients, bool isSendWelcomeSms) { try { //add new clients to db foreach (var client in clients) { _unitOfWork.ClientRepository.Add(client); } _unitOfWork.ClientRepository.Save(); FileLoadHelper.AddImportLogClientCreate(clients); if (clients.Any()) { //send sms _smsSender = new WelcomeSmsSender(); _smsSender.SendSms(isSendWelcomeSms, clients, new Guid(), string.Empty); } } catch (Exception) { throw; } }
public JsonResult SentSmsMultipleClient(string[] clientsId, string templateId, bool isSend, SmsSenderType smsSenderType) { var clients = GetClientsToSendSms(smsSenderType, clientsId); if (string.IsNullOrEmpty(templateId)) return Json(false, JsonRequestBehavior.AllowGet); // sent standard sms _smsSender = new DefaultSmsSender(); _smsSender.SendSms(isSend, clients, new Guid(templateId), string.Empty); return Json(true, JsonRequestBehavior.AllowGet); }
public JsonResult SentSmsClient(string clientId, string templateId, bool isSend) { if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(templateId)) { var baseClient = _unitOfWork.ClientRepository.FindBy(t => t.Id == new Guid(clientId)).FirstOrDefault(); if (baseClient != null) { // sent standard sms //create clients list var clients = new List<Client>(); clients.Add(baseClient); //send sms _smsSender = new DefaultSmsSender(); _smsSender.SendSms(isSend, clients, new Guid(templateId), string.Empty); return Json(true, JsonRequestBehavior.AllowGet); } } return Json(false, JsonRequestBehavior.AllowGet); }
public JsonResult SendCustomSMSMultipleClient(string[] clientsId, string smsText, bool isSend, SmsSenderType smsSenderType) { var clients = GetClientsToSendSms(smsSenderType, clientsId); // sent custom sms selected clients _smsSender = new CustomSmsSender(); _smsSender.SendSms(isSend, clients, new Guid(), smsText); return Json(true, JsonRequestBehavior.AllowGet); }
public async Task <IActionResult> CheckPayment(ClaimHubViewModel model) { var secretKey = _paystackOptions.Value.SecretKey; var api = new PayStackApi(secretKey); //if (!string.IsNullOrEmpty(model.Transaction_reference)) //{ try { var verifyResponse = api.Transactions.Verify(model.Transaction_reference); //if (verifyResponse.Status) //{ Claimer claimer = new Claimer { HubbId = model.HubbId, Name = model.ClaimerName, Email = model.ClaimerEmail, PhoneNumber = model.PhoneNumber, HubToClaim = model.HubToClaim, }; _claimerStore.Post(claimer); //compose email to the admin var forAdmin = $"<h3>Hello admin,<h3></br> {model.ClaimerName} wants to claim {model.HubToClaim}," + $"<br> Contact details: <br>" + $"Email : {model.ClaimerEmail}<br>" + $"Phone : {model.PhoneNumber}"; //compose email to the claimer var forClaimer = $"<h3>Hello {model.ClaimerName},<h3></br> <p>Thanks for contacting us to claim {model.HubToClaim}" + $", the verification process has began , so please do expect a mail from us in 120 minutes.<br>" + $"Thanks.</p><br>" + $"Tobby from Spotahub."; //send email to admin await _emailSender.SendMail("*****@*****.**", "We have a new claimer", forAdmin); //send email to claimer await _emailSender.SendMail(model.ClaimerEmail, "Thanks for contacting us", forClaimer); //compose sms to claimer var smsClaimer = $"Hello {model.ClaimerName},Thanks for contacting us to claim {model.HubToClaim}" + $", the verification process has began , so please do expect an email from us in 120 minutes." + $"Thanks." + $"" + $"Tobby from Spotahub."; //send sms to claimer _smsSender.SendSms(smsClaimer, model.PhoneNumber); return(RedirectToAction("ClaimMessage")); //} } catch (Exception ex) { throw ex; } //} //return Ok(new { message = "Invalid reference" }); // }
public bool Notify(string message) { Console.WriteLine("Sms service invoked" + phoneNumber, message); return(sender.SendSms(message)); }