public async Task <ValidationResult> SaveReportAsync(Sms sms) { if (sms == null) { throw new ArgumentNullException(nameof(sms), "Sms informations are required."); } var result = sms.Validate(); if (result.IsValid) { var dataCollector = await _smsGatewayRepository.GetDataCollectorFromPhoneNumberAsync(sms.Sender); var report = new Report { CreatedAt = DateTime.Now, DataCollector = dataCollector, Location = sms.Location, ReceivedAt = sms.ReceivedAt, IsTraining = false, // TODO }; await _smsGatewayRepository.InsertReportAsync(report); await _smsGatewayRepository.SaveChangesAsync(); } return(result); }
protected override XResp Execute() { var sc = CacheHelper.Get <string>("img.code." + tel); if (sc != code) { throw new XExcep("T图片验证码不正确"); } CacheHelper.Remove("img.code." + tel); try { var smscode = Tools.GetRandRom(4, 1); var re = Sms.SendSms(tel, "您的验证码为:" + smscode + ",请保密。"); var rt = Serialize.JsonToDict(re); if (rt["code"] != "0") { throw new Exception(rt["errorMsg"]); } CacheHelper.Save("sms.code." + tel, smscode, 5 * 60); return(new XResp()); } catch (Exception e) { throw new XExcep("短信发送出错,信息:", e.Message); } }
private async void TapPhone_Tapped(object sender, EventArgs e) { try { var action = await DisplayActionSheet(Property.Vendor.Phone, "Cancel", null, "Call", "SMS"); switch (action) { case "Call": PhoneDialer.Open(Property.Vendor.Phone); break; case "SMS": await Sms.ComposeAsync(new SmsMessage(string.Format("Hej, {0}, angående {1}", Property.Vendor.FirstName, Property.Address), new[] { Property.Vendor.FullName })); break; } } catch (FeatureNotSupportedException fbsEx) { // Email is not supported on this device } catch (Exception ex) { // Some other exception occurred } }
private async void ButtonShare_Clicked(object sender, EventArgs e) { await Task.Run(async() => { HttpClient client = new HttpClient(); Image img = new Image(); System.IO.Stream stream = await client.GetStreamAsync("https://prolist.net.au/WebServices/AgentFileService.asmx/PublicDownload?id=30fe9a79-ea96-46a7-8399-7737bd0bf323&inline=true"); img.Source = ImageSource.FromStream(() => stream); string tempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "imagedata.jpg"); var fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write); using (fileStream) { stream.CopyTo(fileStream); } var message = new SmsMessage("Test", "0415055492"); await Sms.ComposeAsync(message); await Share.RequestAsync(new ShareFileRequest { File = new ShareFile(tempFile) });; File.Delete(path: tempFile); }); }
public async Task <string> SendOneTimeCode(string phoneOrEmail) { using (var db = new QipeilongDbContext()) { var now = DateTime.Now; var ran = new Random((int)now.Ticks); var code = ran.Sample(Com.Range(10).ToList(), 4).AsString(); //send sms var model = new Sms(); model.UID = Com.GetUUID(); model.MsgCode = code; model.Msg = $"汽配龙登录验证码:{code}"; model.TemplateId = "no data"; model.Recipient = phoneOrEmail; model.SmsType = 0; model.Status = (int)YesOrNoEnum.是; model.Sender = "大汉三通"; model.CreatedDate = model.UpdatedDate = now; db.Sms.Add(model); if (await db.SaveChangesAsync() > 0) { return(string.Empty); } throw new Exception("保存验证码失败"); } }
private static async Task <string> SendSmsToApiAsync(Sms sms) { if (httpClient == null) { httpClient = new HttpClient(); } try { var httpContent = new StringContent(JsonConvert.SerializeObject(sms), Encoding.UTF8, "application/json"); var res = await httpClient.PostAsync(apiUrl + "/api/SmsGateway/", httpContent); if (res.IsSuccessStatusCode) { _log.LogInformation("SENDED SMS SUCCESFULL TO THE API - MESSAGESID:{0}", sms.MsgId); var resultString = await res.Content.ReadAsStringAsync(); var answer = JsonConvert.DeserializeObject <Answer>(resultString); return(answer.FeedbackMessage); } _log.LogError("SENDED SMS NOT SUCCESFULL TO THE API - MESSAGESID:{0}", sms.MsgId); return(""); } catch (HttpRequestException e) { _log.LogError("ERROR WHILE SENDING SMS TO THE API - MESSAGESID:{0} - ERROR:{1}", sms.MsgId, e.Message); return(""); } }
private async Task SmsSender() { await Task.Run(async() => { ButtonTitle = " " + "انصراف از ادامه ارسال" + " "; SmsSendingIsRunning = true; foreach (var SmsItem in SmsList.ToList()) { SmsItem.SendSuccessfully = await Sms.SendSms(SmsItem.Cellphone, SmsItem.Message); if (SmsItem.SendSuccessfully) { SmsItem.Status = "با موفقیت ارسال شد"; } else { SmsItem.Status = "ارسال نشد"; } if (AllowToBreakSmsSending) { AllowToBreakSmsSending = false; break; } } SmsSendingIsRunning = false; ButtonOk.Dispatcher.Invoke(() => { ButtonOk.IsEnabled = true; }); ButtonTitle = " " + "بازگشت" + " "; if (SmsList.Any(x => !x.SendSuccessfully)) { ButtonSave.Dispatcher.Invoke(() => { ButtonSave.Visibility = Visibility.Visible; }); } }); }
public IActionResult Register(RegisterViewModel register) { if (ModelState.IsValid) { if (_userService.IsExistUserNumber(register.Number)) { ModelState.AddModelError("Number", "شماره موبایل تکراری می باشد ! از شماره جدیدی استفاده کنید."); return(View(register)); } LindaEShop.DataLayer.Entities.User user = new User() { CreateDate = DateTime.Now, IsActive = true, ActivCode = new Random().Next(100000, 999999).ToString(), Number = register.Number.Trim(), Password = PasswordHelper.EncodePasswordMd5(register.Password), Name = register.Name, RoleId = 2 }; _userService.AddUser(user); Sms.SendSms(register.Number, "فروشگاه اینترنتی لیندا . ثبت نام شما با موفقیت انجام شد ."); ViewBag.register = "ok"; return(Redirect("/")); } return(View(register)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Username,Sms1,Number,Date")] Sms sms) { if (id != sms.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(sms); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SmsExists(sms.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(sms)); }
/// <summary> /// Save SMS to Table /// </summary> /// <param name="sms"></param> /// <param name="state"></param> /// <returns></returns> public async Task <bool> SendSMSAsync(Sms sms, string state) { bool isSent = false; //Grab 3 digits from phone number & grab country code var mobileCC = Convert.ToInt32(string.IsNullOrEmpty(sms.To) ? 0 : int.Parse(sms.To.Substring(0, 3))); if (mobileCC > 0) { //Check with Countries data & fetch associated country for SMS and commercial detail var appliedCountryDetail = GetCountriesAsync().Result.Where(c => c.Mcc == mobileCC).FirstOrDefault(); if (appliedCountryDetail != null) { Sms smsObj = new Sms(); smsObj.From = sms.From; smsObj.To = sms.To; smsObj.Text = sms.To; smsObj.Mcc = appliedCountryDetail.Mcc; smsObj.Price = appliedCountryDetail.PricePerSms; smsObj.State = state; smsObj.CreatedAt = System.DateTime.UtcNow; using (var db = DbConnectionFactory.OpenDbConnection()) { var lastInsertedId = await db.InsertAsync(smsObj); if (lastInsertedId > 0) { isSent = true; } } } } return(await Task.FromResult(isSent)); }
public void SendMessageFromUnknownAccount_SmsWasSaved_AccountWasSaved() { // Arrange var phone = new Phone(7, 999, 9999999); var message = "Hi"; var expected = new Sms { To = phone.ToString(), Message = message }; var unknown = new Account { Type = "sms", Service = "unknown", Login = "******", Balance = 0 }; // Act var result = this._controller.Send( Guid.Empty, unknown.Login, 1, Uri.EscapeUriString(message), phone.ToString() ); // Assert Assert.IsType <OkObjectResult>(result); Assert.Equal(expected.ToJson(), this.Db.SmsBox.First(s => s.To == phone.ToString()).ToJson()); Assert.True( this.Db.Accounts.Any(a => a.Login == unknown.Login), "Unknown account should be saved in Database" ); }
public ActionResult RecoverPass(RecoverPassViewModel model) { if (ModelState.IsValid) { User oUser = db.Users.FirstOrDefault(a => a.CellNum == model.Username); if (oUser != null) { Sms sms = new Sms(); sms.SendSmsForRecoverPassword(oUser.CellNum, oUser.Password); return(RedirectToAction("login")); } else { TempData["WrongPass"] = "******"; } } RecoverPassViewModel recoverPass = new RecoverPassViewModel(); recoverPass.FooterRecentBlog = baseHelper.GetFooterRecentBlog(); recoverPass.MenuServiceGroups = baseHelper.GetMenuServices(); recoverPass.MenuProductGroups = baseHelper.GetMenu(); return(View(recoverPass)); }
private async void BtnPSMS_Click(object sender, EventArgs e) { string text = "Hi, Please find my contact details as requested.Email: " + bundle.GetString("email") + " Phone Number: " + bundle.GetString("phonenumber"); string recipient = "0226329826"; var message = new SmsMessage(text, new[] { recipient }); await Sms.ComposeAsync(message); }
async Task SendText() { try { int i = 0; ObservableCollection <TodoItem> textList = await manager.GetTextNumbersAsync(); string[] recipients = new string[textList.Count]; foreach (TodoItem item in textList) { recipients[i++] = item.TextNumber; } string messageText = "Food available. Login to app for details."; var message = new SmsMessage(messageText, recipients); await Sms.ComposeAsync(message); } catch (FeatureNotSupportedException ex) { // Sms is not supported on this device. } catch (Exception ex) { // Other error has occurred. } }
} //set only via Secret Manager public bool SendSms(Sms sms) { try { var client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); client.QueryString.Add("username", Options.LabUser); client.QueryString.Add("password", Options.LabPassword); client.QueryString.Add("msisdn", sms.msisdn ?? Options.LabDefaultPhone); client.QueryString.Add("message", sms.message); var baseurl = "http://api.labsmobile.com/get/send.php"; using (var data = client.OpenRead(baseurl)) { using (var reader = new StreamReader(data)) { var s = reader.ReadToEnd(); return(Regex.IsMatch(s, @"<code>0<\/code>")); } } } catch (Exception ex) { _logger.LogError(ex.Message); return(false); } }
protected void btnSendMsg_Click(object sender, EventArgs e) { if (txtMsg.Value == "") { JSHelper.Alert(UpdatePanel2, this, "请输入你要发送的短信内容!"); } else if (xlstPerson.Items.Count <= 0) { JSHelper.Alert(UpdatePanel2, this, "请输入你要发送的对象!"); } else { string msg = Sms.Send(txtMsg.Value, xlstPerson, txtSender.Text.Trim()); if (msg == "1") { txtMsg.Value = ""; JSHelper.Alert(UpdatePanel2, this, "已将要发送的短信提交到服务器!"); } else { JSHelper.Alert(UpdatePanel2, this, "已将要发送的短信提交到服务器!\n" + @msg); } } //} }
/// <summary> /// Register user /// </summary> /// <param name="subscriberId">User address</param> private void RegisterUser(string subscriberId) { //Log.TraceStart(); try { CoupleChatDM dm = new CoupleChatDM(); //Generate code and send string code = Common.GenerateCode(_codeLength); while (dm.CodeExists(code)) { code = Common.GenerateCode(_codeLength); } //Save in DB var userId = dm.AddUser(subscriberId, code); if (userId > 0) { var message = string.Format(Resources.Info_RegisterSuccess, code.ToUpper()); Sms.Send(subscriberId, message); } else { Log.Error(string.Format(Resources.Error_UserSaveFailed, subscriberId)); } } catch (Exception ex) { Log.Error(ex.ToString()); throw; } }
public async Task <SmsState> SendSms(Sms sms) { if (!ValidateMobilePhone(sms.To)) { return(SmsState.Failed); } Country country = await GetCountryForSmsAsync(sms); if (country == null) { return(SmsState.Failed); } sms.State = SmsState.Failed; sms.DateTime = DateTime.UtcNow; sms.Mcc = country.MobileCountryCode; sms.Price = country.PricePerSms; _uow.Sms.Add(sms); _uow.Save(); sms.State = await _smsAdapter.SendSms(sms); _uow.Save(); return(sms.State); }
private static bool VerifySms(Sms sms, string to) { ResourceSet <MessageResource> messages; try { TwilioClient.Init(twilioSid, twilioToken); messages = MessageResource.Read( from: new Twilio.Types.PhoneNumber(sms.Sender), to: new Twilio.Types.PhoneNumber(to) ); } catch (Exception e) { _log.LogError("ERROR WHILE FETCHING DATA FROM TWILIO - ERROR:{0}", e.Message); return(false); } foreach (var record in messages) { if (record.Sid == sms.MsgId && record.Body == sms.Text) { _log.LogInformation("SMS FOUND INSIDE TWILIO DATABASE - MESSAGESID:{0}", sms.MsgId); return(true); } } _log.LogWarning("SMS NOT FOUND INSIDE TWILIO DATABASE - MESSAGESID:{0}", sms.MsgId); return(false); }
/// <summary> /// Get user code /// </summary> /// <param name="userAddress">Sender's address</param> private void GetCode(string userAddress) { //Log.TraceStart(); try { CoupleChatDM dm = new CoupleChatDM(); var code = dm.GetUserCode(userAddress); if (!string.IsNullOrEmpty(code)) { var message = string.Format(Resources.Info_GetUserCode, code); Sms.Send(userAddress, message); } else { Log.Error(string.Format(Resources.Error_GetUserCodeFailed)); } } catch (Exception ex) { Log.Error(ex.ToString()); throw; } }
// Controller for message of type SMS private static bool NewSms(Sms sms) { // Check for validity if (!Validator.IsSmsValid(sms)) { error = Validator.Error; return(false); } // Generate ID sms.Id = IdGeneratorSingleton.Instance.NewSmsId(); // Sanitize Sanitizer.SanitizeSms(sms); // Add to the list in memory DataBaseSingleton.Instance.SmsList.Add(sms); // Serialize Persistence.Serialize(); // Display it ProcessedMessage processedMessageWindow = new ProcessedMessage(sms); processedMessageWindow.Show(); return(true); }
//************************************************************************************************** // envoi de la requête vers le web service en https https://domy59efficom.eu/WebServiceSms.asmx // l'utilisateur avec son login est envoyé dans l'entête // le corps du sms est envoyé dans le corps de la requête private void btnEnvoyerMessage_Click(object sender, EventArgs e) { try { if ((UtilisateurConnecte.Login != String.Empty) && (mTxtBoxNumtel.Text != String.Empty))// && (txtBoxMdpEnvoi.Text != String.Empty)) { // On prépare l'objet utilisateur transmis via l'entete soap AuthentificationEnteteSoap authentication = new AuthentificationEnteteSoap(); Utilisateur utilisateur = new Utilisateur(); utilisateur.Login = UtilisateurConnecte.Login; utilisateur.Password = passwordEnvoiSMS; // mot de passe standard pour l'envoi sms authentication.user = utilisateur; // On passe l'utilisateur dans l'entête soap AccesWebServices.ProxySMS.AuthentificationEnteteSoapValue = authentication; // on transmet l'authentification via l'entete http // Envoi du SMS sms = new Sms(); sms.NumDestinataire = mTxtBoxNumtel.Text; sms.TextMessage = richTextBoxMessage.Text; MessageToast.Show(AccesWebServices.ProxySMS.envoyerSms(sms), "Message du webService SMS", 10); } } catch (Exception) { MessageBox.Show("Impossible de joindre le serveur d'envoi SMS"); } }
/// <summary> /// Enviar Email /// </summary> /// <param name="to">Message to address</param> /// /// <param name="cc">Message to address</param> /// <param name="body">Text of message to send</param> /// <param name="subject">Subject line of message</param> public void EnviaSms(string numero, string mensagem, TipoOrigemSms?origemSms = null, int?idEntidadeOrigemSms = null) { try { var usuario = _usuarioRep.GetSingle(SessaoEconomiza.UsuarioId); var sms = new Sms { Numero = numero, Mensagem = mensagem, OrigemSms = origemSms, IdEntidadeOrigem = idEntidadeOrigemSms, UsuarioCriacao = usuario, DtCriacao = DateTime.Now, Ativo = true, Status = StatusSms.NaoEnviado }; _smsRep.Add(sms); _unitOfWork.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } }
private async void SmsFriend(object friendObject) { FriendViewModel friend = friendObject as FriendViewModel; await Sms.ComposeAsync(new SmsMessage { Body = "", Recipients = new List <string> { friend.Phone } }); }
protected override XResp Execute() { var key = GetReqParms("code.send"); var sc = CacheHelper.Get <string>("code." + key); if (sc != code) { throw new XExcep("T图片验证码不正确"); } CacheHelper.Remove("code." + key); var t = true; var smscode = Tools.GetRandRom(4, 1); try { //CacheHelper.Save("sms.code." + tel, smscode); // key :: f5iuwkI1lId3ThcfDS2HyfbKbiAsJ9/!作废!/ //secret: S0DiD9VFx5gC4fhnCKWy3wMONy3J7z //key: LTAIP8aKCv1LUo4P //t = Sms.SendCode(tel, Tools.GetRandRom(4, 1), "LTAIP8aKCv1LUo4P", "优辅家", "SMS_63315079"); //t = Sms.sendSmsViaSDK("优辅家", "LTAIP8aKCv1LUo4P", "S0DiD9VFx5gC4fhnCKWy3wMONy3J7z", "SMS_63315079",tel, Tools.GetRandRom(4, 1)); t = Sms.sendSmsViaMnsSDK("优辅家", "LTAIP8aKCv1LUo4P", "S0DiD9VFx5gC4fhnCKWy3wMONy3J7z", "SMS_63315079", tel, Tools.GetRandRom(4, 1), "https://1625487773132895.mns.cn-hangzhou.aliyuncs.com/", "sms.topic-cn-hangzhou"); } catch (Exception e) { t = false; } if (!t) { throw new XExcep("T短信发送失败"); } return(new XResp() { msg = smscode }); }
private async Task SendSms(string option) { try { var users = (await App.Database.GetItemsAsync()).FirstOrDefault(); //if (users == null) //{ // await Shell.Current.GoToAsync($"AddUserDetails"); //} var smsText = $"{option} {users.FirstName} {users.LastName} {users.Address}"; var message = new SmsMessage(smsText, new[] { "13033" }); await Sms.ComposeAsync(message); } catch (FeatureNotSupportedException ex) { // Sms is not supported on this device. } catch (Exception ex) { // Other error has occurred. } }
public ActionResult Create(Sms new1) // New Message Controller with a HttpPost { if (ModelState.IsValid) //Checks if the Sms model is Valid { MockDB newDb = new MockDB(); // Creates new Database Object string checkList = newDb.findContact(new1.areaCode, new1.phoneNumber); //Checks contacts if (checkList == "Not found") { ViewData["SuccessMsg"] = "Error. Contact does not exist. Go to contacts page above."; //Throws an error if not found } else { //if found passes to success page ViewData["Content"] = new1.textContent; var name2 = newDb.GetName(new1.areaCode, new1.phoneNumber); if (name2 != null) { foreach (var VARIABLE in name2) { ViewData["Receiver"] = VARIABLE; } } return(View("Success")); // Returns success page Logging lognew = new Logging(new1.textContent); // Logs messages } } return(View(new1)); // Returns same page with inputed value if error }
/// <summary> /// Remove linked users /// </summary> /// <param name="userAddress">User address</param> private void RemoveUser(string userAddress) { //Log.TraceStart(); try { CoupleChatDM dm = new CoupleChatDM(); //Save in DB var coupledUserAddress = dm.GetCoupleUserNumberByUserNumber(userAddress); var status = dm.RemoveLinkedUser(userAddress); if (status) { var message = Resources.Info_RemoveLinkedUser; Sms.Send(userAddress, message); if (!string.IsNullOrEmpty(coupledUserAddress)) { Sms.Send(coupledUserAddress, message); } } else { Log.Error(string.Format(Resources.Error_RemoveLinkedUserFailed)); } } catch (Exception ex) { Log.Error(ex.ToString()); throw; } }
public bool SendSMS(string userId, string message) { var user = db.Users.FirstOrDefault(u => u.Id == userId); string mobile_number = user.MobileNumber; string access_token = user.MobileNumberCode; if (!string.IsNullOrEmpty(access_token)) { Sms sms = new Sms(SMSConstants.ShortCode, access_token); // mobile number argument is with format 09, convert it to +639 string globe_format_receiver = "+63" + mobile_number.Substring(1); dynamic response = sms.SetReceiverAddress(globe_format_receiver) .SetMessage(message) .SendMessage() .GetDynamicResponse(); Trace.TraceInformation("Sent a message to " + globe_format_receiver + "."); return(true); } else { return(false); } }
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(); } }
/// <summary> /// 发送短信 /// </summary> public static string SendSms(OpenMasConfig openMasConfig, string message, string[] destinationAddresses, DateTime? expectDateTime = null) { //短信客户端初始化 var client = new Sms(openMasConfig.SmsMasService); if (expectDateTime == null) return client.SendMessage(destinationAddresses, message, openMasConfig.SmsExtensionNo, openMasConfig.SmsAppAccount, openMasConfig.SmsAppPwd); return client.SendMessage(destinationAddresses, message, openMasConfig.SmsExtensionNo, openMasConfig.SmsAppAccount, openMasConfig.SmsAppPwd, expectDateTime.Value); }
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")); }
protected override void OnSetUp() { base.OnSetUp(); _sms = new Sms { Message = "R U There?" }; Repository<Sms>.Save(_sms); UnitOfWork.Current.Flush(); UnitOfWork.Current.Clear(); }
/// <summary> /// Allow entering custom parameters from Console. /// </summary> /// <param name="sms">Sms to modify.</param> private static void CustomParameters(Sms sms) { System.Console.WriteLine("P1:"); sms.P1 = ReadDouble(); System.Console.WriteLine("P2:"); sms.P2 = ReadDouble(); System.Console.WriteLine("R:"); sms.R = ReadDouble(); System.Console.WriteLine("Count:"); sms.TotalCount = (Int32)ReadDouble(); }
public bool Send(Sms sms) { var sentSms = new SentSms {Numbers = sms.Numbers, Message = sms.Message}; using (var session = Store.OpenSession()) { session.Store(sentSms); session.SaveChanges(); } return true; }
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 void textSpeakSucsess() { string _head = "S123456789"; string _body = "+44740296712"; string _expected = "LOL<Laughing out loud>"; Sms testSms = new Sms(_head,_body); testSms.MessageText = "LOL"; Assert.AreEqual(_expected, testSms.MessageText); }
public ActionResult CorreoPagos(FormCollection fc) { int pagos = Convert.ToInt32(Request.Form["idClasePago"]); int ciclos = Convert.ToInt32(Request.Form["idCiclos"]); int evaluacion = Convert.ToInt32(Request.Form["IdEvaluacion"]); var correos = dc.obt_alumnos_en_mora(pagos, ciclos, evaluacion).ToList(); var reglas = (from x in dc.PlantillaCorreos where x.idReglasNegocio == 2 select x).FirstOrDefault(); var calsifica = (from z in dc.ClasificacionReglas where z.idClasificacionReglas == 3 select z).FirstOrDefault(); foreach (var y in correos) { Correos.enviar(y.email, reglas.asunto, string.Format(reglas.cuerpo, evaluacion), calsifica.email, calsifica.contrasenia); try { BitacoraMail bm = new BitacoraMail(); bm.idcarrera = y.Idcarrera; bm.correlativo = y.Correlativo; bm.anioingreso = y.AnyoIngreso; bm.idreglanegocio = reglas.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaenvio = DateTime.Now.TimeOfDay; dc.BitacoraMails.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { return Redirect(Utils.Utilidades.PaginaError()); } try { var X = new Sms(); X.envioMensaje("503" + y.Telefono, "Ha recibido una nueva notificacion, por favor revise su correo", "UNIVERSIDAD EQUIZ"); BitacoraSM bm = new BitacoraSM(); bm.idcarrera = y.Idcarrera; bm.correlativo = y.Correlativo; bm.anioingreso = y.AnyoIngreso; bm.idreglanegocio = reglas.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaingreso = DateTime.Now.TimeOfDay; dc.BitacoraSMs.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { } } return View("MensajeExitoso"); }
static void Main(string[] args) { Sms sms = new Sms() { ContainerCapacity = 1, TotalCount = 50000, P1 = 0.7, P2 = 0.7, R = 0.75 }; //CustomParameters(sms); StatisticResults result = sms.Emulate(); Print(result); result.GenerateTransitionsTable("output.table"); }
protected override void OnTestFixtureSetUp() { base.OnTestFixtureSetUp(); _sms = new Sms { Message = "R U There?" }; Repository<Sms>.SaveOrUpdate(_sms); UnitOfWork.Current.Flush(); Repository<SimpleObject>.Save(new SimpleObject()); Repository<SimpleObject>.Save(new SimpleObject()); Repository<SimpleObject>.Save(new SimpleObject { TwoCharactersMax = "AA" }); Repository<SimpleObject>.Save(new SimpleObject { TwoCharactersMax = "BB" }); UnitOfWork.Current.Flush(); }
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> /// This function send out the sms /// </summary> /// <param name="sms"></param> /// <returns></returns> public string SendSms(Sms sms) { if (string.IsNullOrEmpty(sms.Recipient)) return "Invalid Mobile Number"; // Send a message using the txtLocal transport var transportUrl = ConfigurationManager.AppSettings["appSmsUrl"]; var transportUserName = ConfigurationManager.AppSettings["appSmsUsername"]; var transportPassword = ConfigurationManager.AppSettings["appSmsPassword"]; var testEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["appSmsTestEnabled"]); const bool transportVerbose = true; // Build post String var strPost = "uname=" + transportUserName + "&pword=" + transportPassword + "&message=" + sms.Message + "&from=" + sms.Sender + "&selectednums=" + sms.Recipient; if (testEnabled) strPost += "&test=1"; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (transportVerbose) strPost += "&info=1"; // Create POST var request = WebRequest.Create(transportUrl); request.Method = "POST"; var byteArray = Encoding.UTF8.GetBytes(strPost); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; var dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); // Get the response var response = request.GetResponse(); dataStream = response.GetResponseStream(); if (dataStream == null) return "error"; var reader = new StreamReader(dataStream); var responseFromServer = reader.ReadToEnd(); // Clean upthe streams. reader.Close(); dataStream.Close(); response.Close(); // Return result to calling function return responseFromServer; }
public bool Send(Sms sms) { return false; }
public string SendSms(string Message, string[] destinationAddresses) { //短信客户端初始化 string Url = "http://nb033.openmas.net:9080/OpenMasService"; Sms Client = new Sms(Url); string externcode = "2"; //自定义扩展代码(模块) string ApplicationID = "8035001"; string Password = "******"; //发送短信 return Client.SendMessage(destinationAddresses, Message, externcode, ApplicationID, Password); }
public ActionResult enviar() { var algo = dc.obt_cant_horas_sociales().ToList(); var something = (from x in dc.PlantillaCorreos where x.idReglasNegocio == 1 select x).FirstOrDefault(); var esto = (from z in dc.ClasificacionReglas where z.idClasificacionReglas == 1 select z).FirstOrDefault(); foreach (var mas in algo) { Correos.enviar(mas.email, something.asunto, string.Format(something.cuerpo, mas.total), esto.email, esto.contrasenia); try { BitacoraMail bm = new BitacoraMail(); bm.idcarrera = mas.Idcarrera; bm.correlativo = mas.Correlativo; bm.anioingreso = mas.AnyoIngreso; bm.idreglanegocio = something.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaenvio = DateTime.Now.TimeOfDay; dc.BitacoraMails.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { return Redirect(Utils.Utilidades.PaginaError()); } try { var X = new Sms(); X.envioMensaje("503" + mas.Telefono, "Ha recibido una nueva notificacion, por favor revise su correo", "UNIVERSIDAD EQUIZ"); BitacoraSM bm = new BitacoraSM(); bm.idcarrera = mas.Idcarrera; bm.correlativo = mas.Correlativo; bm.anioingreso = mas.AnyoIngreso; bm.idreglanegocio = something.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaingreso = DateTime.Now.TimeOfDay; dc.BitacoraSMs.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { } } return RedirectToAction("MensajeExitoso"); }
/// <summary> /// Xoa nhieu room /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gridSms_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e) { TransactionManager tm = DataRepository.Provider.CreateTransaction(); tm.BeginTransaction(); try { ASPxGridView grid; switch (e.Parameters) { case "Delete": // Check deleting right if (!RightAccess.CheckUserRight(AccountSession.Session, ScreenCode, OperationConstant.Delete.Key, out _message)) { WebCommon.AlertGridView(sender, _message); tm.Rollback(); return; } grid = sender as ASPxGridView; if (grid == null) { WebCommon.AlertGridView(sender, "Cannot find room."); tm.Rollback(); return; } // Lay danh sach Id cua cac row duoc select var fieldNames = new[] { "Id" }; List<object> columnValues = grid.GetSelectedFieldValues(fieldNames); // Doi trang thai cua cac roster foreach (object roomId in columnValues) { int id; if (!Int32.TryParse(roomId.ToString(), out id)) { WebCommon.AlertGridView(sender, "Room is invalid. You cannot delete it."); tm.Rollback(); return; } var room = DataRepository.RoomProvider.GetById(id); if (room == null || room.IsDisabled) { WebCommon.AlertGridView(sender, "Room is not existed. You cannot delete it."); tm.Rollback(); return; } DataRepository.RoomProvider.DeepLoad(room); // Kiem tra xem co cho nao dang su dung room hay khong if (room.RosterCollection.Exists(x => !x.IsDisabled) || room.DoctorRoomCollection.Exists(x => !x.IsDisabled) || room.AppointmentCollection.Exists(x => !x.IsDisabled)) { WebCommon.AlertGridView(sender, String.Format("Room {0} is using, you cannot delete it.", room.Title)); tm.Rollback(); return; } room.IsDisabled = true; room.UpdateUser = AccountSession.Session; room.UpdateDate = DateTime.Now; DataRepository.RoomProvider.Update(tm, room); } tm.Commit(); WebCommon.AlertGridView(sender, String.Format("{0} deleted successfully.", grid.Selection.Count > 1 ? "Rooms are" : "Room is")); // Set tam duration de lay duoc danh sach moi grid.Selection.UnselectAll(); break; case "Save": // Check deleting right if (!RightAccess.CheckUserRight(AccountSession.Session, ScreenCode, OperationConstant.Create.Key, out _message)) { WebCommon.AlertGridView(sender, _message); tm.Rollback(); return; } grid = sender as ASPxGridView; if (grid == null) { WebCommon.AlertGridView(sender, "Form error."); tm.Rollback(); return; } #region Validation var objMessage = grid.FindEditFormTemplateControl("txtMessage") as ASPxMemo; var objSendTime = grid.FindEditFormTemplateControl("dtSendTime") as ASPxTimeEdit; var objSendDate = grid.FindEditFormTemplateControl("dtSendDate") as ASPxDateEdit; var objIsSendNow = grid.FindEditFormTemplateControl("chkIsSendNow") as ASPxCheckBox; var objPhones = grid.FindEditFormTemplateControl("txtPhones") as ASPxMemo; if (objMessage == null || objSendTime == null || objSendDate == null || objIsSendNow == null || objPhones == null) { WebCommon.AlertGridView(sender, "Form error. Please contact Administrator."); tm.Rollback(); return; } if (string.IsNullOrEmpty(objMessage.Text.Trim()) || objSendTime.Value == null || objSendDate.Value == null || string.IsNullOrEmpty(objPhones.Text.Trim())) { WebCommon.AlertGridView(sender, "Please input value before save."); tm.Rollback(); return; } #endregion var sendTime = (DateTime)objSendTime.Value; var sendDate = (DateTime)objSendDate.Value; var sms = new Sms { Message = objMessage.Text.Trim(), SmsType = SmsType.Other, SendTime = new DateTime(sendDate.Year, sendDate.Month, sendDate.Day, sendTime.Hour, sendTime.Minute, 0), IsSendNow = objIsSendNow.Checked, IsSent = false, SendingTimes = 1, }; string messageCode; WebCommon.AlertGridView(sender, BoFactory.SmsBO.AddSms(sms, objPhones.Text, out messageCode) ? "Your SMS has been created successfully" : BoFactory.MessageConfigBO.GetMessage(messageCode)); grid.CancelEdit(); break; } } catch (Exception ex) { tm.Rollback(); LoggerController.WriteLog(System.Runtime.InteropServices.Marshal.GetExceptionCode(), ex, Network.GetIpClient()); WebCommon.AlertGridView(sender, "Cannot delete service. Please contact Administrator."); } }
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 SaveItem(object sender, EventArgs e) { if (CustomValidation()) { var item = new Sms(); item.Name = textName.Text; item.Content = textContent.Text; if (itemId > 0) { item.Id = itemId; item.Created = created; item.CreatedByUserId = createdBy; item.Modified = DateTime.Now; item.ModifiedByUserId = currentUser; var biz = new SmsBiz(); biz.UpdateItem(item); } else { item.Created = DateTime.Now; item.CreatedByUserId = currentUser; item.Modified = DateTime.Now; item.ModifiedByUserId = currentUser; var biz = new SmsBiz(); biz.SaveItem(item); } this.Close(); } else { this.DialogResult = System.Windows.Forms.DialogResult.None; } }
public ActionResult send() { var eventos = dc.obt_eventos_proximos().ToList(); var reglas = (from x in dc.PlantillaCorreos where x.idReglasNegocio == 3 select x).FirstOrDefault(); var clasifica = (from z in dc.ClasificacionReglas where z.idClasificacionReglas == 4 select z).FirstOrDefault(); foreach (var y in eventos) { Correos.enviar(y.email, reglas.asunto, string.Format(reglas.cuerpo, y.descripcion, y.fechainicio), clasifica.email, clasifica.contrasenia); try { BitacoraMail bm = new BitacoraMail(); bm.idcarrera = y.IdCarrera; bm.correlativo = y.Correlativo; bm.anioingreso = y.AnyoIngreso; bm.idreglanegocio = reglas.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaenvio = DateTime.Now.TimeOfDay; dc.BitacoraMails.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { return Redirect(Utils.Utilidades.PaginaError()); } try { var X = new Sms(); X.envioMensaje("503" + y.Telefono, "Ha recibido una nueva notificacion, por favor revise su correo", "UNIVERSIDAD EQUIZ"); BitacoraSM bm = new BitacoraSM(); bm.idcarrera = y.IdCarrera; bm.correlativo = y.Correlativo; bm.anioingreso = y.AnyoIngreso; bm.idreglanegocio = reglas.idReglasNegocio; bm.fechaenvio = DateTime.Now.Date; bm.horaingreso = DateTime.Now.TimeOfDay; dc.BitacoraSMs.InsertOnSubmit(bm); dc.SubmitChanges(); } catch { } } return RedirectToAction("MensajeExitoso"); }
public AppSettings() { Dms = new Dms(); // need to instantiate (Configuration only sets properties not create the object) Sms = new Sms(); // same IndentityServerSettings = new IndentityServerSettings(); //same }
public ActionResult CheckNum(string num) { AgentBll bll = new AgentBll(); EnterpriseBll eBll = new EnterpriseBll(); Agent model = bll.GetModelByPhone(num); Enterprise emodel = eBll.GetModelById(model.EnterpriseID); if (model == null) { return Content("您所输入的手机号码不存在!请确认号码!"); } if (model.Status != 1) { return Content("您所输入的手机号码不是待验证状态!请确认号码!"); } ISMS test = new Sms(); string checkNum = test.SendbyGSM(num, emodel.EName); return Content(checkNum); }