public bool Process(Domain.User user)
        {
            _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}, Starting.", user.UserId));

            if (!String.IsNullOrEmpty(user.MobileNumber))
            {
                _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}. Sending Verification Codes.", user.UserId));

                //get random alpha numerics
                user.MobileVerificationCode1 = "1234";
                user.MobileVerificationCode2 = "4321";

                user.UserStatus = UserStatus.Pending;

                _ctx.SaveChanges();

                string message = String.Format(_mobileValidationMessage, user.MobileVerificationCode1, user.MobileVerificationCode2);

                //sms mobile verification codes
                _smsService.SendSMS(user.ApiKey, user.MobileNumber, message);

                //send registration email
                string emailSubject = _welcomeEmailSubject;

                var replacementElements = new List <KeyValuePair <string, string> >();
                replacementElements.Add(new KeyValuePair <string, string>("EMAILADDRESS", user.EmailAddress));
                replacementElements.Add(new KeyValuePair <string, string>("LINK_ACTIVATION", String.Format(_activationUrl, user.ConfirmationToken)));

                _emailService.SendEmail(user.EmailAddress, emailSubject, _templateName, replacementElements);
            }

            _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}. Finished.", user.UserId));

            return(true);
        }
Esempio n. 2
0
        private static void SendSMS(DSModel db, SMSService sms, NotificationModel notice)
        {
            try
            {
                string   senderNumber      = GLOB.Settings.Get <string>(16);
                string[] managementNumbers = GLOB.Settings.Get <string>(17).Split(';');

                List <string> numbersToSend = new List <string>();
                if (notice.ReminderType == (uint)ReminderType.Driver || notice.ReminderType == (uint)ReminderType.MVR)
                {
                    numbersToSend.Add("1" + notice.CellPhone.Replace("-", string.Empty).Replace(" ", string.Empty).Trim());
                }
                if (notice.ReminderType == (uint)ReminderType.Management || notice.ReminderType == (uint)ReminderType.MVR)
                {
                    numbersToSend.AddRange(managementNumbers);
                }

                bool status = false;
                foreach (string number in numbersToSend)
                {
                    try
                    {
                        if (sms.SendSMS(senderNumber, number, notice.Message))
                        {
                            status = true;
                        }
                    }
                    catch { }
                }

                NotificationRepository.UpdateNotificationStatus(db, notice, status);
            }
            catch { }
        }
Esempio n. 3
0
        public async Task <IActionResult> GetCheckListPointMarkDone(ApiRequest request)
        {
            try
            {
                FMSEmergencyCheck check = await dbContext.FMSEmergencyCheckList.Where(x => x.Id == request.FMSEmergencyCheckId).Select(x => x).SingleOrDefaultAsync();

                Emergency emergency = await dbContext.Emergencies.Where(x => x.Id == check.FMSEmergencyId).SingleOrDefaultAsync();

                check.MaintenanceStatus = CheckMaintenanceStatus.Done;
                emergency.LastUpdated   = PakistanDateTime.Now;
                await dbContext.SaveChangesAsync();

                string title        = $"Accidental Job Vehicle Number {check.VehicleNumber}";
                string notification = $"Check Point {check.Description} marked as done";
                await hubContext.Clients.All.SendAsync("ReceiveMessageAllUsers",
                                                       User.Identity.Name,
                                                       title,
                                                       notification);

                await SMSService.SendSMS(title + ": " + notification, "03035650720");

                SMSService.SendMail(title, notification, "*****@*****.**");

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Esempio n. 4
0
        public ActionResult SendLoginValidSMS(FormCollection form)
        {
            //step one :get customer cellphone from db
            string customerID = form["CustomerID"];

            if (string.IsNullOrEmpty(customerID))
            {
                return(Json("用户名未提供,发送验证码失败。", JsonRequestBehavior.AllowGet));
            }

            string vendorUserCellphone = CommonService.GetVendorCellPhone(customerID);

            //step two :send sms
            if (string.IsNullOrEmpty(vendorUserCellphone))
            {
                return(Json("账户未绑定手机或是未完成验证绑定,获取验证码失败。", JsonRequestBehavior.AllowGet));
            }
            else
            {
                string code = ValidationCodeHelper.CreateValidateCode(5);
                Session["ValidateCode"] = code;
                CookieHelper.SaveCookie <string>("VerifyCode", code.Trim());
                string SMSContent = string.Format(AppSettingManager.GetSetting("SMSTemplate", "CreateConfirmPhoneCode"),
                                                  DateTime.Now.ToString("MM月dd日 HH:mm"), code);
                if (SMSService.SendSMS(vendorUserCellphone, SMSContent))
                {
                    return(Json("s", JsonRequestBehavior.AllowGet));
                }
            }
            return(Json("服务器忙,稍后重试", JsonRequestBehavior.AllowGet));
        }
Esempio n. 5
0
        public async Task <IActionResult> AddCheckListPointComment(FMSEmergencyCheckCommentVM comment)
        {
            try
            {
                var currentUser = (from u in dbContext.Users
                                   where u.Email == User.Identity.Name
                                   select u).FirstOrDefault();
                FMSEmergencyCheckComment newComment = new()
                {
                    Id = Guid.NewGuid(),
                    FMSEmergencyCheckId = comment.FMSEmergencyCheckId,
                    FMSEmergencyId      = comment.FMSEmergencyId,
                    Comment             = comment.Comment,
                    FMSUserId           = new Guid((from u in dbContext.Users where u.Email == User.Identity.Name select u.Id).SingleOrDefault()),
                    FMSVehicleId        = comment.FMSVehicleId,
                    VehicleNumber       = comment.VehicleNumber,
                    LastUpdated         = DateTime.Now,
                    Mentions            = comment.Mentions
                };
                await dbContext.FMSEmergencyCheckComments.AddAsync(newComment);

                await dbContext.SaveChangesAsync();

                FMSEmergencyCheck check = await(from a in dbContext.FMSEmergencyCheckList
                                                where a.Id == comment.FMSEmergencyCheckId
                                                select a).SingleOrDefaultAsync();
                check.CommentCount = await(from c in dbContext.FMSEmergencyCheckComments
                                           where c.FMSEmergencyCheckId == comment.FMSEmergencyCheckId
                                           select c).CountAsync();
                check.MaintenanceStatus = CheckMaintenanceStatus.InProgress;
                await dbContext.SaveChangesAsync();


                if (!string.IsNullOrEmpty(comment.Mentions))
                {
                    string[] mentions = comment.Mentions.Split(',');
                    foreach (var mention in mentions)
                    {
                        ApplicationUser user = (from u in dbContext.Users
                                                where u.Id == mention
                                                select u).FirstOrDefault();

                        await hubContext.Clients.All.SendAsync("ReceiveMessage",
                                                               user.Email,
                                                               $"Notification for Vehicle Number {check.VehicleNumber}",
                                                               $"{currentUser.Name} mentioned you in a comment under emergency check list point {check.Description}");

                        await SMSService.SendSMS($"Notification for Vehicle Number {check.VehicleNumber}: {currentUser.Name} mentioned you in a comment under emergency check list point {check.Description}", "03035650720");

                        SMSService.SendMail($"Notification for Vehicle Number {check.VehicleNumber}", $"{currentUser.Name} mentioned you in a comment under emergency check list point {check.Description}", "*****@*****.**");
                    }
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Esempio n. 6
0
        private static void SendSMS(DSModel db, SMSService sms, NotificationModel notice)
        {
            try
            {
                string senderNumber = GLOB.Settings.Get<string>(16);
                string[] managementNumbers = GLOB.Settings.Get<string>(17).Split(';');

                List<string> numbersToSend = new List<string>();
                if (notice.ReminderType == (uint)ReminderType.Driver || notice.ReminderType == (uint)ReminderType.MVR)
                    numbersToSend.Add("1" + notice.CellPhone.Replace("-", string.Empty).Replace(" ", string.Empty).Trim());
                if (notice.ReminderType == (uint)ReminderType.Management || notice.ReminderType == (uint)ReminderType.MVR)
                    numbersToSend.AddRange(managementNumbers);

                bool status = false;
                foreach (string number in numbersToSend)
                {
                    try
                    {
                        if (sms.SendSMS(senderNumber, number, notice.Message))
                            status = true;
                    }
                    catch { }
                }

                NotificationRepository.UpdateNotificationStatus(db, notice, status);
            }
            catch { }
        }
Esempio n. 7
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SMSService sms = new SMSService();

            bool result = sms.SendSMS("12674443111", "12674443111", "Third test from your number, with international code.");
            Mess.Info("Status: " + result);
        }
Esempio n. 8
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SMSService sms = new SMSService();

            bool result = sms.SendSMS("12674443111", "12674443111", "Third test from your number, with international code.");

            Mess.Info("Status: " + result);
        }
Esempio n. 9
0
        public async Task <IActionResult> CloseJob(ApiRequest request)
        {
            try
            {
                Vehicle fmsVehicle = (from v in dbContext.Vehicles
                                      where v.VehicleNumber == request.VehicleNumber
                                      select v).SingleOrDefault();

                List <Emergency> emergencies = await dbContext.Emergencies
                                               .Where(x => x.FMSVehicleId == fmsVehicle.Id && (x.MaintenanceStatus == MaintenanceStatus.NotInitiated || x.MaintenanceStatus == MaintenanceStatus.Operational)).ToListAsync();

                foreach (var emergency in emergencies)
                {
                    var checkList = await dbContext.FMSEmergencyCheckList.Where(x => x.FMSEmergencyId == emergency.Id).ToListAsync();

                    checkList.ForEach(u => u.MaintenanceStatus = CheckMaintenanceStatus.Done);

                    emergency.MaintenanceStatus  = MaintenanceStatus.Done;
                    emergency.CarOperationalTime = PakistanDateTime.Now;
                    emergency.JobClosingTime     = PakistanDateTime.Now;
                    emergency.LastUpdated        = PakistanDateTime.Now;
                }
                fmsVehicle.EmergencyStatus = EmergencyMaintenanceStatus.Done;
                if (fmsVehicle.AccidentalStatus == AccidentalMaintenanceStatus.Pending)
                {
                    fmsVehicle.Status = "accidental";
                }
                else
                if (fmsVehicle.PeriodicStatus == PeriodicMaintenanceStatus.Pending)
                {
                    fmsVehicle.Status = "periodic";
                }
                else
                {
                    fmsVehicle.Status = "maintained";
                }

                await dbContext.SaveChangesAsync();

                string notification = $"Emergency Job with Vehicle Number {request.VehicleNumber} marked as closed";
                await hubContext.Clients.All.SendAsync("ReceiveMessageAllUsers",
                                                       User.Identity.Name,
                                                       "Notification",
                                                       notification);

                await SMSService.SendSMS(notification, "03035650720");

                SMSService.SendMail("Notification for " + request.VehicleNumber, notification, "*****@*****.**");

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Esempio n. 10
0
        public async Task <IActionResult> CarOperational(ApiRequest vehicle)
        {
            try
            {
                Vehicle fmsVehicle = (from v in dbContext.Vehicles
                                      where v.VehicleNumber == vehicle.VehicleNumber
                                      select v).SingleOrDefault();
                fmsVehicle.Status           = "maintained";
                fmsVehicle.AccidentalStatus = AccidentalMaintenanceStatus.Done;
                dbContext.SaveChanges();

                Accident accident = (from a in dbContext.Accidents
                                     where a.FMSVehicleId == fmsVehicle.Id && a.MaintenanceStatus == MaintenanceStatus.NotInitiated
                                     select a).SingleOrDefault();

                accident.MaintenanceStatus  = MaintenanceStatus.Operational;
                accident.CarOperationalTime = PakistanDateTime.Now;
                accident.LastUpdated        = PakistanDateTime.Now;


                if (fmsVehicle.EmergencyStatus == EmergencyMaintenanceStatus.Pending)
                {
                    fmsVehicle.Status = "emergency";
                }
                else
                if (fmsVehicle.PeriodicStatus == PeriodicMaintenanceStatus.Pending)
                {
                    fmsVehicle.Status = "periodic";
                }
                else
                {
                    fmsVehicle.Status = "maintained";
                }


                dbContext.SaveChanges();

                string title        = $"Accidental Job Vehicle Number {vehicle.VehicleNumber}";
                string notification = $"Vehicle Number {vehicle.VehicleNumber} marked as operational";
                await hubContext.Clients.All.SendAsync("ReceiveMessageAllUsers",
                                                       User.Identity.Name,
                                                       title,
                                                       notification);

                await SMSService.SendSMS(title + ": " + notification, "03035650720");

                SMSService.SendMail(title, notification, "*****@*****.**");

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Esempio n. 11
0
 public override string SendSMS(string custId, string mobile, string sms)
 {
     if (notificationService != null)
     {
         return(notificationService.SendSMS(custId, mobile, sms));
     }
     else
     {
         return("Notification service not initialized!");
     }
 }
Esempio n. 12
0
        public void SendSMSTest()
        {
            // Arrange
            string fromPhoneNumber = "+16263496912";
            string toPhoneNumber   = "+17146148218";

            string messege  = "Hello from Twilio";
            string expected = "Message Sent: " + fromPhoneNumber + " to " + toPhoneNumber + "-" + messege;

            // Act
            var confirmation = SMSService.SendSMS(messege, fromPhoneNumber, toPhoneNumber);

            // Assert
            Assert.AreEqual(expected, confirmation);
        }
        public static string CreateSubscription(string salesId, string clientId, string token, string cellPhone, string campaignName)
        {
            string isCreated = string.Empty;
            string msidsdn   = cellPhone;

            if (msidsdn.Substring(0, 1) == "0")
            {
                msidsdn = "+27" + msidsdn.Substring(1);
            }

            var data = new Dictionary <string, string>
            {
                { "mobileNumber", msidsdn }
            };

            if (!String.IsNullOrWhiteSpace(msidsdn))
            {
                using (var http = new HttpClient())
                {
                    var content = new StringContent(JsonConvert.SerializeObject(data));
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    http.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
                    var request  = http.PostAsync($"baseUrl/oauth/user", content);
                    var response = request.Result.Content.ReadAsStringAsync().Result;

                    JObject jObject        = JObject.Parse(response);
                    string  responeMessage = Convert.ToString(jObject.SelectToken("message"));
                    string  responeCode    = Convert.ToString(jObject.SelectToken("code"));
                    string  mobile         = Convert.ToString(jObject.SelectToken("mobile"));

                    if (responeMessage == "user_creation_success")
                    {
                        SMSService.SendSMS(mobile);
                        //BusinessLogic.TokenRepositary.InsertClientDetails(clientId, salesId, name, surname, cellPhone, emailAddress, campaignName, campaignId, responeMessage, responeCode);
                        BusinessLogic.TokenRepositary.InsertClientDetails(clientId, salesId, cellPhone, campaignName, responeMessage, baseUrl);
                        return(isCreated = responeMessage);
                    }
                    else
                    {
                        var errorMessage = "Unable to create subscription";
                        BusinessLogic.TokenRepositary.InsertClientDetails(clientId, salesId, cellPhone, campaignName, responeMessage, baseUrl);
                        // public static void InsertClientDetails(string clientId, string salesId,  string cellPhone, string campaignName, string responseMessage, string baseUrl)
                        return(isCreated = errorMessage + msidsdn);
                    }
                }
            }
            return(isCreated);
        }
Esempio n. 14
0
        private void SendTestMessage(Amigo amigo)
        {
            if (amigo == null)
            {
                return;
            }

            string mensagem = amigo.Nome + ", isto e um teste para o sorteio do amigo secreto. " +
                              "Se nao recebeu esta mensagem, reclame com o Pai Natal!";

            var result = SMSService.SendSMS(amigo.NTelemovel, mensagem);

            amigo.UltimoEnvioSMS          = DateTime.Now;
            amigo.ResultadoUltimoEnvioSMS = result;
            db.Entry(amigo).State         = EntityState.Modified;
        }
        public void Process(SendMessageArgs args)
        {
            //If the message is a SMS, we send it here, otherwise we let base handle
            var sms = args.EcmMessage as SMSMessageType;

            if (sms == null)
            {
                base.Process(args);
                return;
            }

            //It's an SMS
            var message = args.CustomData["EmailMessage"] as EmailMessage;

            if (message.Recipients.Count < 1)
            {
                args.AddMessage("Missing Recipients from EmailMessage argument.");
                return;
            }

            args.StartSendTime = DateTime.UtcNow;

            var from        = message.Subject;
            var phoneNumber = sms.PersonalizationRecipient.Identifiers.FirstOrDefault(x => x.Source == "mobile").Identifier;

            var text = WebUtility.HtmlDecode(message.PlainTextBody);

            try
            {
                //TODO:  DI this.
                var service = new SMSService();
                service.SendSMS(phoneNumber, text);
                //DO STUFF IN HERE TO SEND SMS
                base.Process(args);
            }
            catch (Exception ex)
            {
                throw new NonCriticalException(ex.Message, ex);
            }

            args.AddMessage("ok", PipelineMessageType.Information);
            args.SendingTime = Util.GetTimeDiff(args.StartSendTime, DateTime.UtcNow);
        }
Esempio n. 16
0
        /// <summary>
        /// 审核通过退换货申请单
        /// </summary>
        /// <param name="rmaRequestSysNo">退换货申请单编号</param>
        /// <param name="userSysNo">操作人用户</param>
        /// <returns></returns>
        public static RMARequestInfo Valid(int rmaRequestSysNo, LoginUser operateUser)
        {
            string serviceCode = RMARequestDA.CreateServiceCode();

            if (string.IsNullOrEmpty(serviceCode) || serviceCode.Length != 6)
            {
                throw new ArgumentNullException("生成服务编号时发生异常");
            }
            RMARequestInfo request = LoadWithRequestSysNo(rmaRequestSysNo, operateUser.SellerSysNo);

            if (request == null)
            {
                throw new BusinessException(L("未找到编号为【{0}】的退换货申请单", rmaRequestSysNo));
            }
            if (request.Status != RMARequestStatus.WaitingAudit)
            {
                throw new BusinessException(L("申请单不是“待审核”,不能审核通过"));
            }

            request.ServiceCode = serviceCode;
            //审核通过后状态变成“待处理”,这个时候可以进行收货操作
            request.Status         = RMARequestStatus.Origin;
            request.AuditTime      = DateTime.Now;
            request.AuditUserSysNo = operateUser.UserSysNo;
            request.AuditUserName  = operateUser.UserDisplayName;

            using (ITransaction trans = TransactionManager.Create())
            {
                UpdateWithRegisters(request);
                trans.Complete();
            }

            if (request.IsReceiveMsg == true && StringUtility.IsPhoneNo(request.Phone))
            {
                string message = L("您好!您的售后单号{0}已审核通过,服务编号:{1},请在快递面单上备注清楚您的售后单号及编号,谢谢您的配合!", request.RequestID, request.ServiceCode);
                SMSService.SendSMS(request.Phone, message);
            }
            return(request);
        }
Esempio n. 17
0
        private static void SendSMS()
        {
            Console.Clear();
            PrintHeader();

            Console.WriteLine("Phone Number (be sure to include +1):");
            string phoneNumber = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine("Message:");
            string message = Console.ReadLine();

            SMSService smsService = new SMSService(Settings.ACSConnectionString, Settings.AzureStorageSettings, Settings.MessageArchiveTable, Settings.ACSPhoneNumber);
            string     messageId  = smsService.SendSMS(phoneNumber, message, true);

            Console.WriteLine();
            Console.WriteLine("Message sent");
            Console.WriteLine($"Message ID: {messageId}");

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Esempio n. 18
0
        public bool Process(Message message)
        {
            _logger.Log(LogLevel.Info, String.Format("Processing Request Message to {0}", message.RecipientUri));

            //Validate Payment Request
            //Batch Transacation WithDrawal

            URIType recipientType = _messageService.GetURIType(message.RecipientUri);

            _logger.Log(LogLevel.Info, String.Format("URI Type {0}", recipientType));

            //Attempt to find the recipient of the request
            var sender = message.Sender;

            _logger.Log(LogLevel.Info, String.Format("Getting Recipient"));

            var recipient = _userService.GetUser(message.RecipientUri);

            message.Recipient = recipient;

            string smsMessage;
            string emailSubject;
            string emailBody;

            _logger.Log(LogLevel.Info, String.Format("Getting Sender"));

            var senderName = _userService.GetSenderName(sender);

            _logger.Log(LogLevel.Info, String.Format("Retrieved Sender Name {0}", senderName));

            var recipientName = message.RecipientUri;

            if (recipient != null)
            {
                _logger.Log(LogLevel.Debug, String.Format("Recipient Found"));

                //if the recipient has a mobile #; send SMS
                if (!String.IsNullOrEmpty(recipient.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient"));

                    smsMessage = String.Format(_recipientSMSMessage, message.Amount, senderName);
                    _smsService.SendSMS(message.ApiKey, recipient.MobileNumber, smsMessage);
                }

                //if the recipient has an email address; send an email
                if (!String.IsNullOrEmpty(recipient.EmailAddress))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send Email to Recipient"));

                    emailSubject = String.Format(_recipientConfirmationEmailSubject, message.Amount, senderName);
                    emailBody    = String.Format(_recipientConfirmationEmailBody, message.Amount, senderName);

                    _emailService.SendEmail(message.ApiKey, _fromAddress, recipient.EmailAddress, emailSubject, emailBody);
                }
                //if the recipient has a device token; send a push notification
                if (!String.IsNullOrEmpty(recipient.DeviceToken))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send Push Notification to Recipient"));
                }
                //if the recipient has a linked facebook account; send a facebook message
                if (recipient.FacebookUser != null)
                {
                    _logger.Log(LogLevel.Info, String.Format("Send Facebook Message to Recipient"));
                }
            }
            else
            {
                //if recipient Uri Type is Mobile Number, Send SMS
                if (recipientType == URIType.MobileNumber)
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS Message to Recipient"));

                    smsMessage = String.Format(_recipientSMSMessage, message.Amount, senderName);
                    _smsService.SendSMS(message.ApiKey, message.RecipientUri, smsMessage);
                }
                //if recipient Uri Type is email address, Send Email
                if (recipientType == URIType.EmailAddress)
                {
                    _logger.Log(LogLevel.Info, String.Format("Send Emaili Message to Recipient"));

                    emailSubject = String.Format(_recipientConfirmationEmailSubject, message.Amount, senderName);
                    emailBody    = String.Format(_recipientConfirmationEmailBody, message.Amount, senderName);

                    _emailService.SendEmail(message.ApiKey, _fromAddress, message.RecipientUri, emailSubject, emailBody);
                }
                //if recipient Uri Type is facebook count, send a facebook message
                if (recipientType == URIType.FacebookAccount)
                {
                    _logger.Log(LogLevel.Info, String.Format("Send Facebook Message to Recipient"));
                }
            }

            //if sender has mobile #, send confirmation email to sender
            if (!String.IsNullOrEmpty(sender.MobileNumber))
            {
                _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient"));

                smsMessage = String.Format(_senderSMSMessage, message.Amount, recipientName);
                _smsService.SendSMS(message.ApiKey, sender.MobileNumber, smsMessage);
            }

            //if sender has email address; send an email
            if (!String.IsNullOrEmpty(sender.EmailAddress))
            {
                _logger.Log(LogLevel.Info, String.Format("Send Email to Recipient"));

                emailSubject = String.Format(_senderConfirmationEmailSubject, recipientName);
                emailBody    = String.Format(_senderConfirmationEmailBody, message.Amount, recipientName);

                _emailService.SendEmail(message.ApiKey, _fromAddress, sender.EmailAddress, emailSubject, emailBody);
            }

            //if sender has a device token; send a push notification
            if (!String.IsNullOrEmpty(sender.DeviceToken))
            {
                _logger.Log(LogLevel.Info, String.Format("Send Push Notification to Recipient"));
            }
            //if sender has a linked facebook account; send a facebook message
            if (sender.FacebookUser != null)
            {
                _logger.Log(LogLevel.Info, String.Format("Send Facebook Message to Recipient"));
            }

            //Update Payment Status
            _logger.Log(LogLevel.Info, String.Format("Updating Payment Request"));

            message.MessageStatus   = MessageStatus.Pending;
            message.LastUpdatedDate = System.DateTime.Now;

            _ctx.SaveChanges();

            return(true);
        }
Esempio n. 19
0
 public void ExecuteSendSMS()
 {
     _smsSvc.SendSMS(SendTo, Message);
     CloseAction();
 }
Esempio n. 20
0
        public async Task <IActionResult> NewEmergency(FMSEmergencyVM emergency)
        {
            try
            {
                Guid    emergencyId = Guid.NewGuid();
                Vehicle vehicle     = await(from v in dbContext.Vehicles where v.VehicleNumber == emergency.VehicleNumber select v).SingleOrDefaultAsync();
                Driver  driver      = await(from d in dbContext.Drivers where d.VehicleNumber == emergency.VehicleNumber select d).SingleOrDefaultAsync();

                vehicle.Breakdowns++;
                driver.Emergencies++;

                vehicle.EmergencyStatus = EmergencyMaintenanceStatus.Pending;
                if (vehicle.Status != "accidental")
                {
                    vehicle.Status = "emergency";
                }

                Emergency newEmergency = new()
                {
                    Id            = emergencyId,
                    Description   = emergency.Description,
                    DriverId      = driver.Id,
                    RegionId      = dbContext.Regions.Where(x => x.XDescription == vehicle.Region).SingleOrDefault().Id,
                    VehicleNumber = emergency.VehicleNumber,
                    SubRegionId   = dbContext.SubRegions.Where(x => x.XDescription == vehicle.SubRegion).SingleOrDefault().Id,
                    StationId     = dbContext.Stations.Where(x => x.XDescription == vehicle.Station).SingleOrDefault().Id,

                    FMSVehicleId      = vehicle.Id,
                    MaintenanceStatus = MaintenanceStatus.NotInitiated,
                    TimeStamp         = DateTime.Now,
                    LastUpdated       = DateTime.Now
                };
                await dbContext.Emergencies.AddAsync(newEmergency);

                List <string> descriptionList = new()
                {
                    "a. Region/Control inform about vehicle incident",
                    "b. Vehicle Lifting / Movement Inform To Risk Department",
                    "c. Assigning Workshop",
                    "d. Driver & Controller Statement / Documents",
                    "e. Work Estimation & Surveyor of Insurance",
                    "f. Work Approval / Work Start",
                    "g. Vehicle Delivery Time",
                    "h. Work Done & Report",
                    "i. Bills Posting / Pics Uploading In System"
                };

                List <FMSEmergencyCheck> fmsEmergencyCheckList = new();
                foreach (var point in descriptionList)
                {
                    fmsEmergencyCheckList.Add(new FMSEmergencyCheck()
                    {
                        Id                = Guid.NewGuid(),
                        Description       = point,
                        FMSEmergencyId    = emergencyId,
                        MaintenanceStatus = CheckMaintenanceStatus.NotInitiated,
                        FMSVehicleId      = vehicle.Id,
                        VehicleNumber     = emergency.VehicleNumber,
                        LastUpdated       = DateTime.Now,
                        CommentCount      = 0,
                        ImageCount        = 0
                    });
                }

                await dbContext.AddRangeAsync(fmsEmergencyCheckList);

                await dbContext.SaveChangesAsync();

                string title        = $"Emergency Job Vehicle Number {emergency.VehicleNumber}";
                string notification = $"Vehicle Number {emergency.VehicleNumber} marked as emergency";
                await hubContext.Clients.All.SendAsync("ReceiveMessageAllUsers",
                                                       User.Identity.Name,
                                                       title,
                                                       notification);

                await SMSService.SendSMS(title + ": " + notification, "03035650720");

                SMSService.SendMail(title, notification, "*****@*****.**");

                return(Ok(fmsEmergencyCheckList));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
        public ForgetPasswordResponseModel ForgetPassword(ForgetPasswordRequestModel model)
        {
            ForgetPasswordResponseModel FPRM = new ForgetPasswordResponseModel();

            try
            {
                Users UserValidEmailId   = _ObjDBContext.Users.FirstOrDefault(u => u.Email.ToLower() == model.EmailId.ToLower() && u.IsActive == true && u.IsDeleted == false);
                Users UserValidMobileNum = _ObjDBContext.Users.FirstOrDefault(u => u.MobilePhoneNumber.ToLower() == model.MobileNum.ToLower() && u.IsActive == true && u.IsDeleted == false);

                Random _random = new Random();
                string otp     = _random.Next(0, 999999).ToString("D6");

                if (UserValidEmailId != null)
                {
                    var UpdateOTPEmail = _ObjDBContext.Users.Where(s => s.Email == model.EmailId).FirstOrDefault();
                    if (UpdateOTPEmail != null)
                    {
                        UpdateOTPEmail.Otp = otp;
                        _ObjDBContext.Entry(UpdateOTPEmail).State = EntityState.Modified;
                        _ObjDBContext.SaveChanges();
                    }

                    SendEmailRequestModel SERM = new SendEmailRequestModel();
                    SERM.CustomerName      = UserValidEmailId.FirstName;
                    SERM.FileAttachmentURL = "";
                    SERM.MessageBody       = "Hi " + UserValidEmailId.FirstName + " Please Use " + otp + " as OTP for Change password!";
                    SERM.Subject           = "Squeeze Bill Forget Password";
                    SERM.ToEmailId         = UserValidEmailId.Email;
                    EmailService ES           = new EmailService();
                    string       EmailService = ES.SendEmail(SERM);
                    FPRM.Response.Message    = "Please check your Email Inbox for change password !";
                    FPRM.Response.StatusCode = 200;
                }
                else if (UserValidEmailId == null)
                {
                    FPRM.Response.Message    = model.EmailId + " Invalid";
                    FPRM.Response.StatusCode = 201;
                }
                else if (UserValidMobileNum != null)
                {
                    var UpdateOTPMobile = _ObjDBContext.Users.Where(s => s.MobilePhoneNumber == model.MobileNum).FirstOrDefault();
                    if (UpdateOTPMobile != null)
                    {
                        UpdateOTPMobile.Otp = otp;
                        _ObjDBContext.Entry(UpdateOTPMobile).State = EntityState.Modified;
                        _ObjDBContext.SaveChanges();
                    }

                    SendSMSRequestModel SSRM = new SendSMSRequestModel();
                    SSRM.CustomerName = UserValidEmailId.FirstName;
                    SSRM.MessageBody  = "Hi " + UserValidEmailId.FirstName + " Please Use " + otp + " as OTP for Change password!";
                    SSRM.ToMobileNum  = UserValidEmailId.MobilePhoneCountryCode + " " + UserValidEmailId.MobilePhoneNumber;
                    SMSService SS         = new SMSService();
                    string     SMSService = SS.SendSMS(SSRM);
                    FPRM.Response.Message    = "Please check your Mobile Message for change password !";
                    FPRM.Response.StatusCode = 200;
                }
                else if (UserValidMobileNum == null)
                {
                    FPRM.Response.Message    = model.MobileNum + " Invalid";
                    FPRM.Response.StatusCode = 201;
                }
            }
            catch (Exception ex)
            {
                _log.LogInformation("UnExpected");
                FPRM.Response.Message    = Convert.ToString(ex);
                FPRM.Response.StatusCode = 401;
            }
            return(FPRM);
        }
Esempio n. 22
0
File: hszxyy.cs Progetto: ewin66/-
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtContent.Text.Trim() == "")
            {
                MessageBox.Show("没有内容可发送");
                return;
            }
            if (txtPhoneNumber.Text.Trim() == "")
            {
                MessageBox.Show("请输入电话号码");
                return;
            }
            if (txtPhoneNumber.Text.Trim().Length != 11)
            {
                MessageBox.Show("电话号码长度有误");
                return;
            }
            //try
            //{
            //    int dh = Convert.ToInt32(textBox7.Text.Trim());
            //}
            //catch
            //{
            //    MessageBox.Show("电话号码有误");
            //    return;
            //}
            if (F_blh == "")
            {
                MessageBox.Show("无法发送");
                return;
            }

            if (bgys != ysmc && shys != ysmc)
            {
                MessageBox.Show("非报告医生或审核医生,无法发送");
                return;
            }
            SMSService fswjz = new SMSService();
            string     url   = f.ReadString("wjz", "url", "");

            if (url != "")
            {
                fswjz.Url = url;
            }
            string msgid = Guid.NewGuid().ToString();
            string ss    = fswjz.SendSMS(msgid, txtPhoneNumber.Text, txtContent.Text.Trim(), "B55E51E062EC377E42C7FF0BC0149B57C4BC3E4224F5631148A3852C64DA398E");

            if (ss.ToLower() == "ok")
            {
                aa.ExecuteSQL("update T_jcxx set F_yl6='" + DateTime.Now.ToString("yyyyMMddHHmmss") + " '+'" + txtPhoneNumber.Text + " " + txtContent.Text.Trim() + " " + msgid + "' where F_blh='" + F_blh + "'");

                //记录到数据库
                InsertCrisisRecord(msgid);
                //推送到平台
                CrisisReportService crs = new CrisisReportService();
                crs.Url = f.ReadString("hszxyy", "wjzurl", "http://172.16.80.174:8081/CrisisReportService.asmx");
                crs.ReportCrisis(F_blh, txtContent.Text);

                writebg(txtContent.Text.Trim(), F_blh, "发送危急值", "危急值");
                MessageBox.Show("危机值消息发送完成");
                btnSend.Enabled = false;
            }
            else
            {
                MessageBox.Show(ss);
            }
        }
Esempio n. 23
0
        public bool Process(Message message)
        {
            _formattingService       = new FormattingServices();
            _transactionBatchService = new TransactionBatchService(_ctx, _logger);
            _validationService       = new ValidationService(_logger);
            _smsService     = new SMSService(_ctx);
            _emailService   = new EmailService(_ctx);
            _userService    = new UserService(_ctx);
            _messageService = new MessageServices(_ctx);

            string  fromAddress   = "*****@*****.**";
            URIType recipientType = _messageService.GetURIType(message.RecipientUri);

            _logger.Log(LogLevel.Info, String.Format("Processing Payment Message to {0}", message.RecipientUri));

            _logger.Log(LogLevel.Info, String.Format("URI Type {0}", recipientType));

            string smsMessage;
            string emailSubject;
            string emailBody;

            var sender    = message.Sender;
            var recipient = _userService.GetUser(message.RecipientUri);

            message.Recipient = recipient;

            var senderName    = _userService.GetSenderName(sender);
            var recipientName = message.RecipientUri;

            //check to see if recipient uri is mobile #, email address, or ME code

            //Validate Payment

            //Batch Transacations
            _logger.Log(LogLevel.Info, String.Format("Batching Transactions for message {0}", message.Id));

            try
            {
                _transactionBatchService.BatchTransactions(message);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, String.Format("Unable to process message {0}. {1}", message.Id, ex.Message));

                throw ex;
            }

            //Attempt to assign payment to Payee
            if (recipient != null)
            {
                recipientName = recipient.UserName;

                if (!String.IsNullOrEmpty(recipient.SenderName))
                {
                    recipientName = recipient.SenderName;
                }
                else if (!String.IsNullOrEmpty(recipient.MobileNumber))
                {
                    recipientName = _formattingService.FormatMobileNumber(recipient.MobileNumber);
                }

                //Send out SMS Message to recipient
                if (!String.IsNullOrEmpty(recipient.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient"));

                    smsMessage = String.Format(_recipientSMSMessage, message.Amount, senderName, _mobileWebSiteUrl);
                    _smsService.SendSMS(message.ApiKey, recipient.MobileNumber, smsMessage);
                }
                //Send SMS Message to sender
                if (!String.IsNullOrEmpty(sender.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Sender"));

                    smsMessage = String.Format(_senderSMSMessage, message.Amount, recipientName, _mobileWebSiteUrl);
                    _smsService.SendSMS(message.ApiKey, sender.MobileNumber, smsMessage);
                }
                //Send confirmation email to sender
                if (!String.IsNullOrEmpty(sender.EmailAddress))
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending Email Confirmation to Sender"));

                    emailSubject = String.Format(_senderConfirmationEmailSubject, recipientName);
                    emailBody    = String.Format(_senderConfirmationEmailBody, recipientName, message.Amount, _mobileWebSiteUrl);

                    _emailService.SendEmail(message.ApiKey, fromAddress, sender.EmailAddress, emailSubject, emailBody);
                }
                //Send confirmation email to recipient
                if (!String.IsNullOrEmpty(recipient.EmailAddress))
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending Email Confirmation to Recipient"));

                    emailSubject = String.Format(_recipientConfirmationEmailSubject, senderName, message.Amount);

                    //Payment Registered Recipient
                    //first_name
                    //last_name
                    //rec_amount
                    //rec_sender
                    //rec_sender_photo_url
                    //rec_datetime formatted dddd, MMMM dd(rd) at hh:mm tt
                    //rec_comments
                    //app_user
                    //link_registration - empty
                    _emailService.SendEmail(recipient.EmailAddress, emailSubject, _paymentReceivedRecipientRegisteredTemplate, new List <KeyValuePair <string, string> >()
                    {
                        new KeyValuePair <string, string>("first_name", recipient.FirstName),
                        new KeyValuePair <string, string>("last_name", recipient.LastName),
                        new KeyValuePair <string, string>("rec_amount", String.Format("{0:C}", message.Amount)),
                        new KeyValuePair <string, string>("rec_sender", senderName),
                        new KeyValuePair <string, string>("rec_sender_photo_url", ""),
                        new KeyValuePair <string, string>("rec_datetime", message.CreateDate.ToString("dddd, MMMM dd at hh:mm tt")),
                        new KeyValuePair <string, string>("rec_comments", message.Comments),
                        new KeyValuePair <string, string>("link_registration", ""),
                        new KeyValuePair <string, string>("app_user", "false")
                    });
                }
                if (recipient.DeviceToken.Length > 0)
                {
                    _logger.Log(LogLevel.Info, String.Format("Sending iOS Push Notification to Recipient"));


                    // We need to know the number of pending requests that the user must take action on for the application badge #
                    // The badge number is the number of PaymentRequests in the Messages database with the Status of (1 - Pending)
                    //      If we are processing a payment, we simply add 1 to the number in this list. This will allow the user to
                    //      Be notified of money received, but it will not stick on the application until the users looks at it. Simplyt
                    //      Opening the application is sufficient
                    var numPending = _ctx.Messages.Where(p => p.MessageTypeValue.Equals((int)Domain.MessageType.PaymentRequest) && p.MessageStatusValue.Equals((int)Domain.MessageStatus.Pending));

                    _logger.Log(LogLevel.Info, String.Format("iOS Push Notification Num Pending: {0}", numPending.Count()));

                    NotificationPayload payload = null;
                    String notification;

                    // Send a mobile push notification
                    if (message.MessageType == Domain.MessageType.Payment)
                    {
                        notification = String.Format(_recipientWasPaidNotification, senderName, message.Amount);
                        payload      = new NotificationPayload(recipient.DeviceToken, notification, numPending.Count() + 1);
                        payload.AddCustom("nType", "recPCNF");
                    }
                    else if (message.MessageType == Domain.MessageType.PaymentRequest)
                    {
                        notification = String.Format(_recipientRequestNotification, senderName, message.Amount);
                        payload      = new NotificationPayload(recipient.DeviceToken, notification, numPending.Count());
                        payload.AddCustom("nType", "recPRQ");
                    }

                    /*
                     *  Payment Notification Types:
                     *      Payment Request [recPRQ]
                     *          - Recipient receives notification that takes them to the
                     *                 paystream detail view about that payment request
                     *      Payment Confirmation [recPCNF]
                     *          - Recipient receices notification that takes them to the paysteam detail view about the payment request
                     */

                    payload.AddCustom("tID", message.Id);
                    var notificationList = new List <NotificationPayload>()
                    {
                        payload
                    };

                    List <string> result;

                    try
                    {
                        var push = new PushNotification(true, @"C:\APNS\DevKey\aps_developer_identity.p12", "KKreap1566");
                        result = push.SendToApple(notificationList); // You are done!
                    }
                    catch (Exception ex)
                    {
                        _logger.Log(LogLevel.Fatal, String.Format("Exception sending iOS push notification. {0}", ex.Message));
                        var exception = ex.InnerException;

                        while (exception != null)
                        {
                            _logger.Log(LogLevel.Fatal, String.Format("Exception sending iOS push notification. {0}", exception.Message));
                        }
                    }
                }
                if (recipient.FacebookUser != null)
                {
                    //Send Facebook Message
                    // I don't think we can do this through the server. Nice try though.
                    // We should, however, publish something to the user's page that says sender sent payment
                }
            }
            else
            {
                _logger.Log(LogLevel.Info, String.Format("Send SMS to Payee not found"));

                var link = String.Format("{0}{1}", _mobileWebSiteUrl, message.Id.ToString());

                //Send out SMS message to sender
                if (!String.IsNullOrEmpty(sender.MobileNumber))
                {
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Sender (Recipient is not an registered user)."));

                    smsMessage = String.Format(_senderSMSMessageRecipientNotRegistered, message.Amount, message.RecipientUri, link);
                    _smsService.SendSMS(message.ApiKey, sender.MobileNumber, smsMessage);
                }
                if (!String.IsNullOrEmpty(sender.EmailAddress))
                {
                    emailSubject = String.Format(_senderConfirmationEmailSubjectRecipientNotRegistered, message.RecipientUri);
                    emailBody    = String.Format(_senderConfirmationEmailBodyRecipientNotRegistered, message.Amount, message.RecipientUri);

                    //Send confirmation email to sender
                    _logger.Log(LogLevel.Info, String.Format("Send Email to Sender (Recipient is not an registered user)."));

                    _emailService.SendEmail(message.ApiKey, fromAddress, sender.EmailAddress, emailSubject, emailBody);
                }
                if (recipientType == URIType.MobileNumber)
                {
                    //Send out SMS message to recipient
                    _logger.Log(LogLevel.Info, String.Format("Send SMS to Recipient (Recipient is not an registered user)."));

                    smsMessage = String.Format(_recipientSMSMessageRecipientNotRegistered, senderName, message.Amount, link);
                    _smsService.SendSMS(message.ApiKey, message.RecipientUri, smsMessage);
                }

                emailSubject = String.Format(_recipientConfirmationEmailSubject, senderName, message.Amount);

                //Payment Registered Recipient
                //first_name
                //last_name
                //rec_amount
                //rec_sender
                //rec_sender_photo_url
                //rec_datetime formatted DayOfWeek, MM dd(rd) at hh:mm:tt
                //rec_comments
                //app_user
                //link_registration - empty
                if (recipientType == URIType.EmailAddress)
                {
                    //Send confirmation email to recipient
                    _logger.Log(LogLevel.Info, String.Format("Send Email to Recipient (Recipient is not an registered user)."));

                    _emailService.SendEmail(message.RecipientUri, emailSubject, _paymentReceivedRecipientNotRegisteredTemplate, new List <KeyValuePair <string, string> >()
                    {
                        new KeyValuePair <string, string>("first_name", ""),
                        new KeyValuePair <string, string>("last_name", ""),
                        new KeyValuePair <string, string>("rec_amount", String.Format("{0:C}", message.Amount)),
                        new KeyValuePair <string, string>("rec_sender", senderName),
                        new KeyValuePair <string, string>("rec_sender_photo_url", ""),
                        new KeyValuePair <string, string>("rec_datetime", message.CreateDate.ToString("MM, dd yyyy hh:mm tt")),
                        new KeyValuePair <string, string>("rec_comments", message.Comments),
                        new KeyValuePair <string, string>("link_registration", link),
                        new KeyValuePair <string, string>("app_user", "false")
                    });
                }
            }

            _logger.Log(LogLevel.Info, String.Format("Updating Payment"));

            message.MessageStatus   = MessageStatus.Pending;
            message.LastUpdatedDate = System.DateTime.Now;

            _ctx.SaveChanges();

            return(true);
        }