private async void btnSendSMS_Click(object sender, RoutedEventArgs e) { statusProgress.Visibility = Visibility.Visible; txtResult.Visibility = Visibility.Collapsed; btnSendSMS.IsEnabled = false; try { clientId = "your_att_app_key"; clientSecret = "your_att_secret_key"; uriString = "https://api.att.com"; SmsService smsService = new SmsService(new AttServiceSettings(clientId, clientSecret, new Uri(uriString))); List<string> phoneNumbers = txtPhone.Text.Split(';').ToList<string>(); SmsResponse response = await smsService.SendSms(phoneNumbers, txtMessage.Text); if (null != response) { txtResult.Visibility = Visibility.Visible; txtResult.Text = "Message has been sent"; } } catch (Exception ex) { txtResult.Visibility = Visibility.Visible; txtResult.Text = ex.Message; } statusProgress.Visibility = Visibility.Collapsed; btnSendSMS.IsEnabled = true; }
private void AddDefaultSms(bool isSend, List<Client> clients, Guid smsTemplateId) { try { LogIt.Logger.WriteLogMessage(string.Format("Send default Sms to clients, send Sms = " + isSend)); //create sms service SmsService service = new SmsService(); //check credit balance if (service.IsCreditBalance()) { var smsText = GetDefaultSmsText(smsTemplateId); //send sms var isSent = false; if (isSend) { isSent = service.SendClientsSms(clients, smsText); } SaveSentSms(clients, smsTemplateId, isSent); } } catch (Exception ex) { LogIt.Logger.WriteLogMessage(string.Format("EXCEPTION! Default Sms sender: " + ex.InnerException)); } }
private void ButtonConnect_Click_1(object sender, EventArgs e) { if (ButtonConnect.Tag == null) { try { com = new ComConnection(comboBoxCOMList.SelectedItem.ToString(), Convert.ToInt32(comboBoxBIT.SelectedItem.ToString())); com.ReceivedEvent += com_ReceivedOrReceiveEvent; //com.SendingEvent += com_ReceivedOrReceiveEvent; com.Open(); smsService = new SmsService(com); ButtonConnect.Text = "Disconnect"; ButtonConnect.Tag = true; tabControl1.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); com.Dispose(); } } else { smsService.Dispose(); ButtonConnect.Tag = null; ButtonConnect.Text = "Connect"; } }
public ActionResult Index() { SmsService _smsService = new SmsService(); SharpGoogleVoice gv = new SharpGoogleVoice("*****@*****.**", "");//enter email gv.SendSMS("+14148408420", "test message");//- change number, just showing format prbly put this somewhere else^ - console app logic? //public ActionResult SendSMS(SMS sms) - this would be for different text service http://emekaemego.blogspot.com/2010/10/sending-sms-with-aspnet-mvc.html //{ //if (ModelState.IsValid) //{ // try // { // bool isSuccess = false; // string errMsg = null; // string response = _smsService.Send(sms); //Send sms // string code = _smsService.GetResponseMessage(response, out isSuccess, out errMsg); // if (!isSuccess) // { // ModelState.AddModelError("", errMsg); // } // else // { // ViewData["SuccessMsg"] = "Message was successfully sent."; // } // } // catch (Exception ex) // { // ModelState.AddModelError("", ex.Message); // } //} End text code return View(/*sms*/); }
private static void Main(string[] args) { //Console.WriteLine(String.Format("\x01a")); //Console.ReadLine(); //try //{ // // _log.Info("Start Sms Service"); // RemotePrivoder.SmsProvider=new SmsProvider(); // var _smsChannel = new TcpChannel(Configuration.Remoteing.Port); // ChannelServices.RegisterChannel(_smsChannel, false); // RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotePrivoder), // Configuration.Remoteing.ServiceName, // WellKnownObjectMode.Singleton); //} //catch (DeviceConnectionException ex) //{ // // _log.Error("Start sms service have error", ex); //} //catch (Exception ex) //{ // // _log.Error("Start sms service have error", ex); // Thread.Sleep(1000); //} var conn = new ComConnection("COM1", 9600); conn.Open(); try { //while (true) //{ // string command = Console.ReadLine(); // //var com = new Protocol.SendCommands.SetSmsFromatCommand(SmsFormat.Pdu); // conn.Send(command); //} var service = new SmsService(conn, "8613800756500"); service.SetSmsAutoRecieve(); service.ReceiveSmsEvent += new EventHandler<NewMessageEventHandlerArgs>(service_ReceiveSmsEvent); //service.ChinaMobile = false; //service.ServiceCenterNumber = "8613800756500";//service.GetServicePhone(); //ThreadPool.QueueUserWorkItem(MultiSend1, service); //ThreadPool.QueueUserWorkItem(MultiSend2, service); //ThreadPool.QueueUserWorkItem(MultiSend3, service); Console.Read(); } catch (Exception ex) { Console.WriteLine(ex.Message); Exception exx = ex; Console.Read(); } finally { conn.Close(); } Console.Read(); Console.Read(); Console.Read(); }
public void PostInvalidRequestMessageEmpty() { var smsService = new SmsService(); var request = new Sms { Message = string.Empty, Number = "123", RequestId = Guid.Empty }; var response = smsService.OnPost(request) as SmsResponse; Assert.That(response.ResponseStatus.Errors[0].Message, Is.EqualTo("Sms message must be set")); }
public void GetSmsSuccessful() { var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore()).Return(base.DocumentStore); var smsService = new SmsService { RavenDocStore = ravenDocStore }; var request = new Sms { RequestId = smsSuccessful }; var response = smsService.OnGet(request) as Sms; Assert.That(response.RequestId, Is.EqualTo(smsSuccessful)); Assert.That(response.Status, Is.EqualTo("Sent")); ravenDocStore.VerifyAllExpectations(); }
public void GetSmsNotComplete() { var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>(); ravenDocStore.Expect(r => r.GetStore()).Return(base.DocumentStore); var smsService = new SmsService { RavenDocStore = ravenDocStore }; var requestId = Guid.NewGuid(); var request = new Sms { RequestId = requestId }; var response = smsService.OnGet(request) as SmsResponse; Assert.That(response.RequestId, Is.EqualTo(requestId)); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("NotYetComplete")); ravenDocStore.VerifyAllExpectations(); }
public SmsProvider() { try { var com = new ComConnection(Configuration.PortName, Configuration.BaudRate); _handler = Configuration.SmsHandler; if (_handler != null) _handler.Priovider = this; _service = new SmsService(com); _service.ReceiveSmsEvent += ServiceNewSmsEvent; _log = LogManager.GetLogger(GetType()); _service.SetSmsAutoRecieve(); } catch (Exception ex) { _log.Error("Ini error.", ex); } }
public BlaBlaCarJob(BlaBlaCarFinder tripFinder, DataContext dataContext, SmtpService smtpService, SmsService smsService) { this.dataContext = dataContext; this.tripFinder = tripFinder; this.smtpService = smtpService; this.smsService = smsService; }
public UserAuthController(UserAuthService userAuthService, SmsService smsService, ILogger <UserAuthController> logger) { this.logger = logger; this.userAuthService = userAuthService; this.smsService = smsService; }
/// <inheritdoc /> public async Task <TotpResult> Send(ClaimsPrincipal principal, string message, TotpDeliveryChannel channel = TotpDeliveryChannel.Sms, string purpose = null, string securityToken = null, string phoneNumberOrEmail = null) { var totpResult = ValidateParameters(principal, securityToken, phoneNumberOrEmail); if (!totpResult.Success) { return(totpResult); } User user = null; var hasPrincipal = principal != null; if (hasPrincipal) { user = await UserManager.GetUserAsync(principal); if (user?.PhoneNumberConfirmed == false || string.IsNullOrEmpty(user?.PhoneNumber)) { return(TotpResult.ErrorResult(Localizer["Cannot send SMS. User's phone number is not verified."])); } } purpose ??= TotpConstants.TokenGenerationPurpose.StrongCustomerAuthentication; var token = string.Empty; var hasSecurityToken = !string.IsNullOrEmpty(securityToken); if (hasSecurityToken) { var modifier = GetModifier(purpose, phoneNumberOrEmail); var encodedToken = Encoding.Unicode.GetBytes(securityToken); token = Rfc6238AuthenticationService.GenerateCode(encodedToken, modifier).ToString("D6", CultureInfo.InvariantCulture); } if (hasPrincipal) { token = await UserManager.GenerateUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, purpose); } var userName = user?.UserName ?? "Anonymous"; var cacheKey = $"totp{(hasPrincipal ? $":{user.Id}" : string.Empty)}:{channel}:{token}:{purpose}"; if (await CacheKeyExists(cacheKey)) { Logger.LogInformation($"User: '******' - Last token has not expired yet. Throttling."); return(TotpResult.ErrorResult(Localizer["Last token has not expired yet. Please wait a few seconds and try again."])); } Logger.LogInformation($"User: '******' - Token generated successfully."); switch (channel) { case TotpDeliveryChannel.Sms: await SmsService.SendAsync(user?.PhoneNumber ?? phoneNumberOrEmail, Localizer["OTP"], Localizer[message, token]); break; case TotpDeliveryChannel.Email: case TotpDeliveryChannel.Viber: case TotpDeliveryChannel.Telephone: case TotpDeliveryChannel.EToken: throw new NotSupportedException($"EToken delivery channel {channel} is not implemented."); default: break; } await AddCacheKey(cacheKey); return(TotpResult.SuccessResult); }
private void TrataFornecedorNovaCotacao(TipoAvisos pTipoAviso) { try { NotificacoesAlertasService NAService = new NotificacoesAlertasService(); EmailService EmailSrv = new EmailService(); SmsService SmsSrv = new SmsService(); List <EntidadeCotacao.Cotacao> listaPedidoMembro = NAService.ListarCotacoesPendentes(); foreach (EntidadeCotacao.Cotacao item in listaPedidoMembro) { List <RetornoAvisos> listaUsuario = NAService.TrataNovaCotacaoFornecedor(item, pTipoAviso.Id); foreach (RetornoAvisos retAviso in listaUsuario) { //Enviar Email if (retAviso.EnviarEmail) { EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Pendência dar lance na Cotação", retAviso.Usuario.UsuarioEmail, "corpoemail Pendente dar lance na Cotação", Origem.NovaCotacao); } //Enviar SMS if (retAviso.EnviarSMS) { SmsSrv.EnviaSms(retAviso.Usuario.Pessoa.Telefones.Select(t => t.DddCel).FirstOrDefault() + retAviso.Usuario.Pessoa.Telefones.Select(t => t.Celular).FirstOrDefault(), "Economiza Já - Cotação aguardnado seu lance.", TipoOrigemSms.PedidosPendentesAprovacaoMembro); } if (retAviso.EnviarEmail || retAviso.EnviarSMS) { NAService.AtualizaDataAviso(retAviso.Aviso, NAService.UsuarioRobo().Id); } //Grava Aviso ////if (retAviso.NovoAviso) ////{ //// NAService.AddAvisos( //// new Avisos() //// { //// Ativo = true, //// //Pedido = item, //// IdReferencia = item.Id, //// DataUltimoAviso = DateTime.Now, //// ExibeNaTelaAvisos = true, //// TipoAvisosId = pTipoAviso.Id, //// URLPaginaDestino = "/#/cotacoes", //// TituloAviso = "Cotação Pendente de Lance", //// ToolTip = "Cotação Pendente de Lance", //// DescricaoAviso = "Cotação Pendente de Lance " + item.Id, //// ModuloId = pTipoAviso.ModuloId, //Modulo Membro //// UsuarioNotificadoId = retAviso.Usuario.Id //// }); ////} } } NAService.LimparTabelAvisosPorNovasCotacoesFornecedor(listaPedidoMembro, pTipoAviso.Id); } catch (Exception) { throw; } }
public SmsServiceTests() { _service = new SmsService(_smsRepositoryMock.Object, _mapperMock.Object, EmptyLogFactory.Instance); }
public DataParser(SmsService smsService) { SmsService _smsService = smsService; }
public SmsServiceTests() { _service = new SmsService("", _infobipClientMock.Object, EmptyLogFactory.Instance, 1); }
protected void btnSent_Click(object sender, EventArgs e) { MembershipUser u; try { if (string.IsNullOrEmpty(txtemail.Value)) { lblMessage.Text = "Silakan isi email terlebih dahulu."; return; } string newPassword = null; u = Membership.GetUser(txtemail.Value, false); if (u == null) { lblMessage.Text = Server.HtmlEncode(txtemail.Value) + " tidak ditemukan. Silakan isi dengan email yang benar."; return; } try { newPassword = u.ResetPassword(); } catch (MembershipPasswordException e1) { lblMessage.Text = "Gagal melakukan reset password, silakan mencoba kembali."; return; } if (!string.IsNullOrEmpty(newPassword)) { //send email var subject = "Password Akun Sistem Informasi Pelayanan Online Balitanah Anda sudah berhasil di reset"; var message = "Password baru untuk username : "******" adalah " + newPassword; EmailService.SendEmail(subject, message, txtemail.Value); using (var db = new smlpobDB()) { var emp = from x in db.customertbls where x.customerEmail == txtemail.Value select x; foreach (var item in emp) { SmsService.SendSms(message, item.companyPhone).GetAwaiter().GetResult(); } } lblMessage.Visible = true; Response.Redirect("ForgotPasswordDone.aspx"); } else { lblMessage.Visible = true; lblMessage.Text = "Gagal melakukan reset password, silakan mencoba kembali."; } } catch (Exception ex) { LogHelpers.source = this.GetType().ToString(); LogHelpers.message = "Gagal reset password user:" + ex.Message; LogHelpers.user = CommonWeb.GetCurrentUser(); LogHelpers.WriteLog(); } }
public SmsApi(SmsService messagesService) { this._messagesService = messagesService; }
public RaportService(DailyRepsCounterRepository repository, SmsService smsService) { this.repository = repository; this.smsService = smsService; }
public SmsJob(SmsService smsService) { _smsService = smsService; }
public void TestaEfetuarPedido() { try { bool notificarClienteEmail = false; bool notificarClienteSms = true; IProdutoImposto produtoImpostoService = new ProdutoImpostoService(); IEstoque estoqueService = new EstoqueService(); ICarrinho carrinhoService = new CarrinhoService(produtoImpostoService, estoqueService); IGatewayPagamento gatewayPagamentoService = new GatewayPagamentoService(); IPagamento pagamentoService = new PagamentoService(gatewayPagamentoService); IMail mailService = new MailService(); ISms smsService = new SmsService(); IPedido pedidoService = new PedidoService(carrinhoService, pagamentoService, estoqueService, mailService, smsService); Cliente cliente = new Cliente { Cpf = "443", Nome = "ADRIAN", Email = "*****@*****.**", Celular = "900000000" }; Carrinho carrinho = new Carrinho { Produtos = new List <Produto>(), Cliente = cliente, FoiEntregue = false, FoiPago = false, ValorTotalPedido = 0M }; carrinho.Produtos.Add(new Produto { Descricao = "", Valor = 100M, Quantidade = 3, ValorImposto = 0M, TipoProduto = TipoProduto.Alimentos }); carrinho.Produtos.Add(new Produto { Descricao = "", Valor = 100M, Quantidade = 3, ValorImposto = 0M, TipoProduto = TipoProduto.Eletronico }); carrinho.Produtos.Add(new Produto { Descricao = "", Valor = 100M, Quantidade = 3, ValorImposto = 0M, TipoProduto = TipoProduto.Superfulos }); DetalhePagamento detalhePagamento = new DetalhePagamento { FormaPagamento = FormaPagamento.CartaoDebito, NumeroCartao = "12453", MesExpiracao = 4, AnoExpiracao = 2022, NomeImpressoCartao = "ADRIAN" }; pedidoService.EfetuarPedido(carrinho, detalhePagamento, notificarClienteEmail, notificarClienteSms); } catch (Exception ex) { Assert.Fail("Exceção não esperada: " + ex.Message); } }
public HomeController(SmsService smsService) { _smsService = smsService; }
public DashboardModel(UserManager <IdentityUser> userManager, ayushContext context, SmsService smsService) { _userManager = userManager; _context = context; _smsService = smsService; }
public void PostInvalidRequestMessageExceeds160Characters() { var smsService = new SmsService(); var request = new Sms { Message = "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah", Number = "123", RequestId = Guid.Empty }; var response = smsService.OnPost(request) as SmsResponse; Assert.That(response.ResponseStatus.Errors[0].Message, Is.EqualTo("Sms message must not exceed 160 characters")); }
private void GvData_RowCommand(object sender, GridViewCommandEventArgs e) { var IDS = e.CommandArgument.ToString(); switch (e.CommandName) { case "lihat": Response.Redirect("CustomerServiceDetail.aspx?value=" + IDS + "&State=" + FormState + "&Mode=" + e.CommandName); break; case "terima-sampel": Response.Redirect("CustomerServiceDetail.aspx?value=" + IDS + "&State=" + FormState + "&Mode=" + e.CommandName); break; case "proses-lab": using (var db = new smlpobDB()) { var valdata = (from w in db.ordersampletbls where w.orderNo == IDS select w.isReceived).FirstOrDefault(); if (valdata == "1") { var data = (from x in db.ordermastertbls where x.orderNo == IDS select x).FirstOrDefault(); if (data != null) { data.status = Status.OrderStatus[2]; data.isOnLab = "1"; db.SaveChanges(); GoSearch(); CommonWeb.Alert(this, "Data sudah diproses ke lab."); } } else { CommonWeb.Alert(this, "Proses ke Lab gagal. Harap terima sampel terlebih dahulu"); } } //Response.Redirect("CustomerServiceDetail.aspx?value=" + IDS + "&State=" + FormState + "&Mode=" + e.CommandName); break; case "kirim-notif": //Send notif tuk customer using (var db = new smlpobDB()) { var data = (from x in db.ordermastertbls.Include(c => c.customertbl) where x.orderNo == IDS select x).FirstOrDefault(); if (data != null) { if (!string.IsNullOrEmpty(data.customertbl.customerEmail)) { EmailService.SendEmail($"LHP dengan No: {data.orderNo} Sudah Dapat Diambil di BalitTanah", $"Yth. Bpk/Ibu {data.customertbl.customerName}, <br/>LHP dengan No: {data.orderNo} Sudah Dapat Diambil di BalitTanah. Silakan kunjungi situs web kami untuk melihat status order Anda pada tautan berikut : {ConfigurationManager.AppSettings["RootWebUrl"]} <br/> Terima Kasih <br/> Hormat Kami, <br/>Balai Penelitian Tanah", data.customertbl.customerEmail, true); SmsService.SendSms($"Yth. Bpk/Ibu {data.customertbl.customerName}, <br/>LHP dengan No: {data.orderNo} Sudah Dapat Diambil di BalitTanah. Silakan kunjungi situs web kami untuk melihat status order Anda pada tautan berikut : {ConfigurationManager.AppSettings["RootWebUrl"]} <br/> Terima Kasih <br/> Hormat Kami, <br/>Balai Penelitian Tanah", data.customertbl.companyPhone).GetAwaiter().GetResult(); CommonWeb.Alert(this, "Notifikasi sudah dikirim ke customer."); } } } break; case "cetak-barcode": Response.Redirect("CetakBarcodeSampel.aspx?value=" + IDS + "&State=" + FormState + "&Mode=" + e.CommandName); break; case "ambil-lhp": using (var db = new smlpobDB()) { var data = (from x in db.ordermastertbls.Include(c => c.customertbl) where x.orderNo == IDS select x).FirstOrDefault(); if (data != null) { data.status = Status.OrderStatus[8]; db.SaveChanges(); CommonWeb.Alert(this, "Update status LHP berhasil."); GoSearch(); } } break; } }
public ApplicationUserManager(IUserStore <LoginUser, int> store, EmailService emailService, SmsService smsService, IdentityFactoryOptions <ApplicationUserManager> options) : base(store) { // Configure validation logic for usernames this.UserValidator = new UserValidator <LoginUser, int>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <LoginUser, int> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <LoginUser, int> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); EmailService = emailService; SmsService = smsService; var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <LoginUser, int>(dataProtector); } //alternatively use this if you are running in Azure Web Sites UserTokenProvider = new EmailTokenProvider <LoginUser, int>(); }
public SendSmsTest() { repository = new Mock <ISmsRepository>(); service = new SmsService(repository.Object); }
public Return Register(User userModel) { var resultReturn = new Return(); try { #region 检查必须字段是否为空 //安卓ID为空 if (string.IsNullOrEmpty(userModel.Android)) { resultReturn.ReturnCode.Code = 1885; return(resultReturn); } //密码为空 if (string.IsNullOrEmpty(userModel.Password)) { resultReturn.ReturnCode.Code = 1997; return(resultReturn); } //验证码为空 if (string.IsNullOrEmpty(userModel.VCode)) { resultReturn.ReturnCode.Code = 1994; return(resultReturn); } #endregion #region 验证该安卓ID是否被记录 var androidInfo = AndroidService.GetByAndroidId(userModel.Android); //该安卓ID不存在Android表中 if (androidInfo == null) { resultReturn.ReturnCode.Code = 1884; return(resultReturn); } #endregion #region 短信验证 var sms = SmsService.GetSmsByPhone(userModel.Phone); //还没发送短信 if (sms == null) { resultReturn.ReturnCode.Code = 1991; return(resultReturn); } //验证码已过期 if (Convert.ToDateTime(sms.UpdateTime).AddMinutes(5) < DateTime.Now) { resultReturn.ReturnCode.Code = 1990; return(resultReturn); } //已使用 if (sms.IsUse) { resultReturn.ReturnCode.Code = 1888; return(resultReturn); } //验证码不正确 if (sms.Code != userModel.VCode) { resultReturn.ReturnCode.Code = 1889; return(resultReturn); } //避免不同数据库上下文操作出现的错误 var newSms = new Data.Domain.Sms { Code = sms.Code, IsUse = true, Phone = sms.Phone, UpdateTime = DateTime.Now }; //更新Sms IsUse 为 true //若出错,不抛出错误,只做错误记录 SmsService.InsertOrUpdate(newSms); #endregion #region 验证手机号码是否已注册 var userInfo = UserService.GetUserByPhone(userModel.Phone); //该手机号码已注册 if (userInfo != null) { resultReturn.ReturnCode.Code = 1998; return(resultReturn); } #endregion resultReturn = UserService.Register(androidInfo.UserId.ToString(), userModel.Phone, userModel.Password); //将User数据库模型类转换为页面模型类 var user = ModelTransfer.Mapper(resultReturn.Content, new User()); user.Password = ""; resultReturn.Content = user; return(resultReturn); } catch (Exception ex) { LogService.InsertLog(ex); resultReturn.SetWrong(); return(resultReturn); } }
public async Task <IActionResult> GetSmsBalance() => Ok(await SmsService.GetBalance());
public BankController(DBRepository dBRepository, SmsService smsService) { _dBRepository = dBRepository; }
private void TrataPedidosPendentesAceiteFornecedor(TipoAvisos pTipoAviso) { try { NotificacoesAlertasService NAService = new NotificacoesAlertasService(); EmailService EmailSrv = new EmailService(); SmsService SmsSrv = new SmsService(); List <RetornoAvisos> retornoAvisos = new List <RetornoAvisos>(); List <Fornecedor> listaFornecedoresUsuarios = new List <Fornecedor>(); List <Pedido> listaPedidoFornecedor = NAService.ListarPedidosPendentes(TipoCliente.Fornecedor); foreach (Pedido item in listaPedidoFornecedor) { listaFornecedoresUsuarios = NAService.ListaFornecedorPedido(item); foreach (Fornecedor itemFornecedor in listaFornecedoresUsuarios.Distinct()) { retornoAvisos = NAService.TrataPedidoFornecedor(item, itemFornecedor, pTipoAviso.Id); foreach (RetornoAvisos retAviso in retornoAvisos) { //Enviar Email if (retAviso.EnviarEmail) { var template = NAService.GetCorpoEmail(18); var corpoEmail = template.Replace("#NomeFantasia#", retAviso.Usuario.Pessoa.PessoaJuridica.NomeFantasia); EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Pendência Aceite do Pedido " + item.Id, retAviso.Usuario.UsuarioEmail, corpoEmail, Origem.NovaCotacao); } //Enviar SMS if (retAviso.EnviarSMS) { SmsSrv.EnviaSms(retAviso.Usuario.Pessoa.Telefones.Select(t => t.DddCel).FirstOrDefault() + retAviso.Usuario.Pessoa.Telefones.Select(t => t.Celular).FirstOrDefault(), "Economiza Já - Pedido. Aguardando Aprovação do Pedido " + item.Id + ".", TipoOrigemSms.PedidosPendentesAprovacaoMembro); } if (retAviso.EnviarEmail || retAviso.EnviarSMS) { NAService.AtualizaDataAviso(retAviso.Aviso, NAService.UsuarioRobo().Id); } //Grava Aviso ////if (retAviso.NovoAviso) ////{ //// NAService.AddAvisos( //// new Avisos() //// { //// Ativo = true, //// //Pedido = item, //// IdReferencia = item.Id, //// DataUltimoAviso = DateTime.Now, //// ExibeNaTelaAvisos = true, //// TipoAvisosId = pTipoAviso.Id, //// //TipoAviso = pTipoAviso, //// URLPaginaDestino = "/#/pedidos", //// TituloAviso = "Aceite Pendente", //// ToolTip = "", //// DescricaoAviso = "Aceite Pendente do pedido " + item.Id, //email 18 //// ModuloId = 4, //Modulo Fornecedor //// UsuarioNotificadoId = retAviso.Usuario.Id //// }); ////} } } } //Limpa tabela de Avisos NAService.LimparTabelAvisosPorFornecedor(listaPedidoFornecedor, pTipoAviso.Id); } catch (Exception ex) { throw new Exception("Erro TrataPedidosPendentesAceiteFornecedor", ex); } }
public int ReceiveOTP(string phoneNumber = "") { try { NLogManager.LogMessage("ReceiveOTP: " + phoneNumber); var account = AccountDAO.GetAccountById(AccountSession.AccountID); NLogManager.LogMessage("ReceiveOTP: " + JsonConvert.SerializeObject(account)); //chua dang ky sdt if (string.IsNullOrEmpty(account.Tel)) { if (!PhoneDetector.IsValidPhone(phoneNumber)) { NLogManager.LogMessage("FAIL PHONE: " + phoneNumber); return(-54); } //send to phonenumber //this case is for the first time update phone var status = OTP.OTP.GenerateOTP(AccountSession.AccountID, phoneNumber); NLogManager.LogMessage("OTP: " + status); if (int.Parse(status) < 0) { return(int.Parse(status)); } bool deduct = TransactionDAO.DeductGold(account.AccountID, 1000, "Phí dịch vụ OTP", 2); NLogManager.LogMessage("DEDUCT OTP STATUS: " + deduct); if (!deduct) { return(-62); } //send the otp to phone SmsService.SendMessage(phoneNumber, $"Ma xac nhan: " + status); return(1); } else { NLogManager.LogMessage("OTP to phone: " + account.Tel); var status = OTP.OTP.GenerateOTP(AccountSession.AccountID, account.Tel); NLogManager.LogMessage("OTP: " + status); if (int.Parse(status) < 0) { return(int.Parse(status)); } bool deduct = TransactionDAO.DeductGold(account.AccountID, 1000, "Phí dịch vụ OTP", 2); NLogManager.LogMessage("deduct: " + deduct); if (!deduct) { return(-62); } //send the otp to phone SmsService.SendMessage(account.Tel, $"Ma xac nhan: " + status); return(1); } } catch (Exception ex) { NLogManager.PublishException(ex); NLogManager.LogMessage("ERROR ReceiveOTP: " + ex); } return(-99); }
private void NovoFornecedorAvisoMembro(TipoAvisos pTipoAviso) { try { NotificacoesAlertasService NAService = new NotificacoesAlertasService(); EmailService EmailSrv = new EmailService(); SmsService SmsSrv = new SmsService(); DateTime DtExec = NAService.UltimaExecucaoRotina(pTipoAviso.Id, "NotificacoesAlertas"); List <RetornoAvisos> listaUsuario = NAService.VerificaNovoFornecedorCadastrado(pTipoAviso.Id, DtExec); NAService.GravaExecucaoRotina(pTipoAviso.Id, "NotificacoesAlertas"); foreach (RetornoAvisos retAviso in listaUsuario) { //Enviar Email if (retAviso.EnviarEmail) { EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Novos fornecedores", retAviso.Usuario.UsuarioEmail, "corpoemailNovos Fornecedores para se segmento", Origem.NovaCotacao); } //Enviar SMS if (retAviso.EnviarSMS) { SmsSrv.EnviaSms(retAviso.Usuario.Pessoa.Telefones.Select(t => t.DddCel).FirstOrDefault() + retAviso.Usuario.Pessoa.Telefones.Select(t => t.Celular).FirstOrDefault(), "Economiza Já - Novos Fornecedores foram cadastrados para seu segmento.", TipoOrigemSms.PedidosPendentesAprovacaoMembro); } if (retAviso.EnviarEmail || retAviso.EnviarSMS) { NAService.AtualizaDataAviso(retAviso.Aviso, NAService.UsuarioRobo().Id); } //Grava Aviso if (retAviso.NovoAviso) { NAService.AddAvisos( new Avisos() { Ativo = true, //Pedido = item, IdReferencia = retAviso.Usuario.PessoaId, DataUltimoAviso = DateTime.Now, ExibeNaTelaAvisos = true, TipoAvisosId = pTipoAviso.Id, URLPaginaDestino = "/#/fornecedor", TituloAviso = "Novos Fornecedores", ToolTip = "Novos Fornecedores", DescricaoAviso = "Corre envie uma solicitação de cadastro de compra", ModuloId = pTipoAviso.ModuloId, //Modulo Membro UsuarioNotificadoId = retAviso.Usuario.Id }); } } } catch (Exception ex) { throw new Exception("Erro NovoFornecedorAvisoMembro", ex); } }
public static void StartServices() { // DI ready ServiceLocator.Start = (IServiceLocator locator) => { IProfiler profiler = new WebProfiler(); IUserLocale userLocale = new WebUserLocale(); IApplicationHost host = new WebApplicationHost(profiler, userLocale); ILocalizer localizer = new WebLocalizer(host, userLocale); ITokenProvider tokenProvider = new WebTokenProvider(); IDbContext dbContext = new SqlDbContext( profiler as IDataProfiler, host as IDataConfiguration, localizer as IDataLocalizer, host as ITenantManager, tokenProvider); ILogger logger = new WebLogger(host, dbContext); IMessageService emailService = new IdentityEmailService(logger, host); IMessaging messaging = new MessageProcessor(host, dbContext, emailService, logger); IRenderer renderer = new XamlRenderer(profiler, host); IWorkflowEngine workflowEngine = new WorkflowEngine(host, dbContext, messaging); IDataScripter scripter = new VueDataScripter(host, localizer); ISmsService smsService = new SmsService(dbContext, logger); IExternalLoginManager externalLoginManager = new ExternalLoginManager(dbContext); IUserStateManager userStateManager = new WebUserStateManager(host, dbContext); IExternalDataProvider dataProvider = new ExternalDataContext(); IScriptProcessor scriptProcessor = new ScriptProcessor(scripter, host); IHttpService httpService = new HttpService(); IJavaScriptEngine javaScriptEngine = new JavaScriptEngine(dbContext, host); locator.RegisterService <IDbContext>(dbContext); locator.RegisterService <IProfiler>(profiler); locator.RegisterService <IApplicationHost>(host); locator.RegisterService <IRenderer>(renderer); locator.RegisterService <IWorkflowEngine>(workflowEngine); locator.RegisterService <IMessaging>(messaging); locator.RegisterService <IUserLocale>(userLocale); locator.RegisterService <ILocalizer>(localizer); locator.RegisterService <IDataScripter>(scripter); locator.RegisterService <ILogger>(logger); locator.RegisterService <IMessageService>(emailService); locator.RegisterService <ISmsService>(smsService); locator.RegisterService <IExternalLoginManager>(externalLoginManager); locator.RegisterService <IUserStateManager>(userStateManager); locator.RegisterService <IExternalDataProvider>(dataProvider); locator.RegisterService <IScriptProcessor>(scriptProcessor); locator.RegisterService <IHttpService>(httpService); locator.RegisterService <IJavaScriptEngine>(javaScriptEngine); locator.RegisterService <ITokenProvider>(tokenProvider); if (HttpContext.Current != null) { HttpContext.Current.Items.Add("ServiceLocator", locator); } }; ServiceLocator.GetCurrentLocator = () => { if (HttpContext.Current == null) { throw new InvalidProgramException("There is no http context"); } var currentContext = HttpContext.Current; var locator = currentContext.Items["ServiceLocator"]; if (locator == null) { new ServiceLocator(); } return(HttpContext.Current.Items["ServiceLocator"] as IServiceLocator); }; }
public MainService(IBus bus, SmsService smsService) { _bus = bus; _smsService = smsService; }
protected async void BtnDaftar_Click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(txtemail.Text)) { var seldata = context.customertbls.Where(x => x.customerEmail == txtemail.Text).ToList(); if (seldata != null && seldata.Count > 0) { CommonWeb.Alert(this, "Email ini sudah terdaftar"); } else { try { //register to asp membership first! MembershipUser user = Membership.CreateUser(txtemail.Text, txtpassword.Text, txtemail.Text); //account string pwd = Crypto.Encrypt(txtpassword.Text); var NewItem = new accounttbl() { username = txtemail.Text, password = pwd, roleName = "pelanggan", creaBy = "registration system", creaDate = DatetimeHelper.GetDatetimeNow(), isEmailVerified = "0" }; //customers var IDS = txtemail.Text; var idacc = (from x in context.accounttbls where x.username == IDS select x.accountNo).FirstOrDefault(); var NewItem2 = new customertbl() { customerName = txtusername.Text, customerEmail = txtemail.Text, companyName = txtcompanyname.Text, companyAddress = txtaddress.Text, companyPhone = txtphone.Text, companyEmail = txtcompanyemail.Text, accountNo = idacc, creaBy = "registration system", creaDate = DatetimeHelper.GetDatetimeNow() }; context.accounttbls.Add(NewItem); context.customertbls.Add(NewItem2); context.SaveChanges(); var roleFromAccountTable = registerControls.GetRole(txtemail.Text); string role = roleFromAccountTable; Roles.AddUserToRole(txtemail.Text, role); //kirim email var subject = "Aktivasi Akun untuk Sistem Informasi Pelayanan Online Balitanah"; var mainMessage = "Silahkan klik link berikut untuk mengaktivasi akun anda:"; var message = mainMessage + $"<br> <a href='{ConfigurationManager.AppSettings["RootWebUrl"]}/Pages/Public/Activation.aspx?userId={txtemail.Text}'>Aktivasi Akun</a>"; var msgPhone = mainMessage + $" { ConfigurationManager.AppSettings["RootWebUrl"]}/Pages/Public/Activation.aspx?userId={txtemail.Text}"; var ret = EmailService.SendEmail(subject, message, txtemail.Text); await SmsService.SendSms(msgPhone, txtphone.Text); //var userAdded = Membership.GetUser(txtemail.Text); //if (userAdded != null) //{ // userAdded.IsApproved = true; // userAdded.UnlockUser(); // Membership.UpdateUser(userAdded); //} Response.Redirect("RegisterDone.aspx", false); Context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { TxtStatus.Text = "Gagal menyimpan data registrasi, silakan isi dengan lengkap data-data yang diperlukan."; LogHelpers.source = this.GetType().ToString(); LogHelpers.message = "fail to register user:"******"Gagal menyimpan data registrasi, silakan isi dengan lengkap data-data yang diperlukan."; } }
private async void btnSendSMS_Click(object sender, RoutedEventArgs e) { txtResult.Text = string.Empty; if (string.IsNullOrEmpty(txtSpeechOutput.Text)) { txtResult.Text = "Specify message"; return; } if (string.IsNullOrEmpty(txtPhoneNumber.Text)) { txtResult.Text = "Specify Phone Number"; return; } statusProgress.Visibility = Visibility.Visible; txtResult.Visibility = Visibility.Collapsed; btnSendSMS.IsEnabled = false; btnRecord.IsEnabled = false; try { //clientId = "your client id here"; //clientSecret = "your client secret"; SmsService smsService = new SmsService(new AttServiceSettings(clientId, clientSecret, new Uri(uriString))); List<string> phoneNumbers = txtPhoneNumber.Text.Split(';').ToList<string>(); SmsResponse response = await smsService.SendSms(phoneNumbers, txtSpeechOutput.Text); if (null != response) { txtResult.Visibility = Visibility.Visible; txtResult.Text = "Message has been sent"; } } catch (Exception ex) { txtResult.Visibility = Visibility.Visible; txtResult.Text = ex.Message; } statusProgress.Visibility = Visibility.Collapsed; btnSendSMS.IsEnabled = true; btnRecord.IsEnabled = true; }
private void TrataPedidosPendentesAceiteMembro(TipoAvisos pTipoAviso) { try { NotificacoesAlertasService NAService = new NotificacoesAlertasService(); EmailService EmailSrv = new EmailService(); SmsService SmsSrv = new SmsService(); List <Pedido> listaPedidoMembro = NAService.ListarPedidosPendentes(TipoCliente.Membro); foreach (Pedido item in listaPedidoMembro) { List <RetornoAvisos> listaUsuario = NAService.TrataPedidoMembro(item, pTipoAviso.Id); foreach (RetornoAvisos retAviso in listaUsuario) { //Enviar Email if (retAviso.EnviarEmail) { var template = NAService.GetCorpoEmail(22); if (retAviso.Usuario.Pessoa.TipoPessoa == TipoPessoa.PessoaJuridica) { var corpoEmail = template.Replace("#NomeFantasia#", retAviso.Usuario.Pessoa.PessoaJuridica.NomeFantasia); EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Corra aprove seu pedido " + item.Id + " valores validos por 2 dias a partir da data de retorno da cotacao, Evite o CANCELAMENTO", retAviso.Usuario.UsuarioEmail, corpoEmail, Origem.NovaCotacao); } else { var corpoEmail = template.Replace("#NomeFantasia#", retAviso.Usuario.Pessoa.PessoaFisica.Nome); EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Corra aprove seu pedido " + item.Id + " valores validos por 2 dias a partir da data de retorno da cotacao, Evite o CANCELAMENTO", retAviso.Usuario.UsuarioEmail, corpoEmail, Origem.NovaCotacao); } } //Enviar SMS if (retAviso.EnviarSMS) { SmsSrv.EnviaSms(retAviso.Usuario.Pessoa.Telefones.Select(t => t.DddCel).FirstOrDefault() + retAviso.Usuario.Pessoa.Telefones.Select(t => t.Celular).FirstOrDefault(), // "Economiza Já - Aguardando Aprovação de Pedido " + item.Id + ".", "Economiza Já-Corra aprove seu pedido " + item.Id + " valores validos por 2 dias a partir da data de retorno da cotacao, Evite o CANCELAMENTO", TipoOrigemSms.PedidosPendentesAprovacaoMembro); } if (retAviso.EnviarEmail || retAviso.EnviarSMS) { NAService.AtualizaDataAviso(retAviso.Aviso, NAService.UsuarioRobo().Id); } //Grava Aviso ////if (retAviso.NovoAviso) ////{ //// NAService.AddAvisos( //// new Avisos() //// { //// Ativo = true, //// //Pedido = item, //// IdReferencia = item.Id, //// DataUltimoAviso = DateTime.Now, //// ExibeNaTelaAvisos = true, //// TipoAvisosId = pTipoAviso.Id, //// URLPaginaDestino = "/#/meusPedidos", //// TituloAviso = "Aceite Pendente", //// ToolTip = "", //// DescricaoAviso = "Aceite Pendente do pedido " + item.Id, //// ModuloId = 3, //Modulo Membro //// UsuarioNotificadoId = retAviso.Usuario.Id //// }); ////} } } //testar melhor esse trecho para limpar avisos. NAService.LimparTabelAvisosPorMembro(listaPedidoMembro, pTipoAviso.Id); } catch (Exception ex) { throw new Exception("Erro TrataPedidosPendentesAceiteMembro", ex); } }
public DeliveryReportController(SmsService smsService) { _smsService = smsService; }
private void TrataAceiteFornecedorParaMembro(TipoAvisos pTipoAviso) { try { NotificacoesAlertasService NAService = new NotificacoesAlertasService(); EmailService EmailSrv = new EmailService(); SmsService SmsSrv = new SmsService(); List <RetornoAvisos> retornoAvisos = new List <RetornoAvisos>(); //Recupera fornecedores Que precisam dar o Aceite para solicitacao do Membro List <MembroFornecedor> listaMembroFornecedor = NAService.ListaPendenciasAceiteFornecedorParaMembro(); foreach (MembroFornecedor item in listaMembroFornecedor) { //Trata Permissão de Envio se Fornecedor quer receber essas informações por Email/SMS retornoAvisos = NAService.TrataPendenciasAceiteFornecedorParaMembro(item, pTipoAviso.Id); foreach (RetornoAvisos retAviso in retornoAvisos) { //Enviar Email if (retAviso.EnviarEmail) { var template = NAService.GetCorpoEmail(9); var corpoEmail = template.Replace("#NomeFornecedor#", retAviso.Usuario.Pessoa.PessoaJuridica.NomeFantasia); if (item.Membro.Pessoa.TipoPessoa == TipoPessoa.PessoaJuridica) { corpoEmail = template.Replace("#NomeMembro#", item.Membro.Pessoa.PessoaJuridica.NomeFantasia); } else { corpoEmail = template.Replace("#NomeMembro#", item.Membro.Pessoa.PessoaFisica.Nome); } EmailSrv.EnviarEmailViaRobo( NAService.UsuarioRobo(), "Pendência Aceite dos Pedidos", retAviso.Usuario.UsuarioEmail, corpoEmail, Origem.NovaCotacao); } //Enviar SMS if (retAviso.EnviarSMS) { SmsSrv.EnviaSms(retAviso.Usuario.Pessoa.Telefones.Select(t => t.DddCel).FirstOrDefault() + retAviso.Usuario.Pessoa.Telefones.Select(t => t.Celular).FirstOrDefault(), "Economiza Já - Pedido. Aguardando Aprovação dos Pedidos.", TipoOrigemSms.PedidosPendentesAprovacaoMembro); } //Grava Aviso ////if (retAviso.NovoAviso) ////{ //// NAService.AddAvisos( //// new Avisos() //// { //// Ativo = true, //// //Pedido = item, //// IdReferencia = item.MembroId, //// DataUltimoAviso = DateTime.Now, //// ExibeNaTelaAvisos = true, //// TipoAvisosId = pTipoAviso.Id, //// //TipoAviso = pTipoAviso, //// URLPaginaDestino = "/#/membro", //// TituloAviso = "Pendente aceite novo Membro", //// ToolTip = "Novo Membro", //// DescricaoAviso = ("Pendente aceite novo Membro " + item.Membro.Pessoa.PessoaJuridica.NomeFantasia).Substring(0,99), //// ModuloId = 4, //Modulo Fornecedor //// UsuarioNotificadoId = retAviso.Usuario.Id //// }); ////} } } //Limpa tabela de avisos solicitação novo membro para fornecedor NAService.LimparTabelAvisosPorSolicitacaoMembroFornecedor(listaMembroFornecedor, pTipoAviso.Id); } catch (Exception ex) { throw new Exception("Erro TrataAceiteFornecedorParaMembro", ex); } }
public void PostWithRequestIdSmsSuccess() { var bus = MockRepository.GenerateMock<IBus>(); bus.Expect(b => b.Send(Arg<SendOneMessageNow>.Is.Anything)); var smsService = new SmsService { Bus = bus }; var request = new Sms { Message = "m", Number = "n", RequestId = Guid.NewGuid() }; var response = smsService.OnPost(request) as SmsResponse; Assert.That(response.RequestId, Is.EqualTo(request.RequestId)); bus.VerifyAllExpectations(); }
/// <summary> /// 发送短信验证码 /// </summary> /// <param name="phone">手机号码</param> /// <param name="code">短信验证码</param> /// <returns></returns> public async Task <SendResult> SendCodeAsync(string phone, string code) { var sms = new AliyunSmsService(); return(await SmsService.SendCodeAsync(phone, code)); }
public Notification(SmsService smsService) { _smsService = smsService; _emailService = new EmailService(); }