public async Task <OkResult> Post([FromBody] IncomingMessageEvent model)
        {
            var        fromNumber = "+" + model.From.Endpoint;
            Subscriber subscriber = _dbContext.Subscribers.FirstOrDefault(m => m.Number == fromNumber);

            if (model.Message.Trim().ToLower() == "start" || model.Message.Trim().ToLower() == "unstop")
            {
                if (subscriber != null)
                {
                    subscriber = new Subscriber {
                        Number = fromNumber
                    };
                    _dbContext.Subscribers.Add(subscriber);
                    await _dbContext.SaveChangesAsync();
                }
                await _smsSender.SendSMS(new Message { MessageContent = _configuration["Sinch:WelcomeMessage"] }, subscriber);

                return(Ok());
            }

            if (model.Message.Trim().ToLower() == "stop")
            {
                if (_dbContext.Subscribers.Any(m => m.Number == fromNumber))
                {
                    _dbContext.Subscribers.Remove(_dbContext.Subscribers.First(m => m.Number == fromNumber));
                    await _dbContext.SaveChangesAsync();
                }
                //add subscribper

                return(Ok());
            }
            await _smsSender.SendSMS(new Message { MessageContent = "Sorry, we only support Start and stopm if you have any questions please contact TVQMA" }, subscriber);

            return(Ok());
        }
Exemple #2
0
        //手机发送短信验证码,调用平台接口
        static void Main(string[] args)
        {
            //using (ZSZDbContext ct=new ZSZDbContext())
            //{
            //    ct.Database.Delete();
            //    ct.Database.Create();
            //}
            //Console.WriteLine("OK");
            string userName   = "******";
            string appKey     = "8b4de3b31534437b416aaa";
            string templateId = "326";
            string code       = "6666";
            string phoneNum   = "18918918189";

            /*
             *          WebClient wc = new WebClient();
             *          string url = "http://sms.rupeng.cn/SendSms.ashx?userName="******"&appKey=" + Uri.EscapeDataString(appKey) +
             *              "&templateId=" + templateId + "&code=" + Uri.EscapeDataString(code) +
             *              "&phoneNum=" + phoneNum;
             *          wc.Encoding = Encoding.UTF8;
             *          string resp = wc.DownloadString(url);
             *          //发出url这样一个http请求(Get请求)返回值为响应报文体
             *          Console.WriteLine(resp);
             */
            SMSSender sender = new SMSSender();

            sender.AppKey   = appKey;
            sender.UserName = userName;
            var result = sender.SendSMS(templateId, code, phoneNum);

            Console.WriteLine("返回码:" + result.code + ",消息:" + result.msg);
            Console.WriteLine("ok");
            Console.ReadKey();
        }
Exemple #3
0
 public ActionResult Register(RegisterViewModel register)
 {
     if (ModelState.IsValid)
     {
         if (!db.Users.Any(x => x.Mobile == register.Mobile))
         {
             string hash  = FormsAuthentication.HashPasswordForStoringInConfigFile(register.Password, "MD5");
             Random rnd   = new Random();
             int    myrnd = rnd.Next(100000, 900000);
             User   user  = new User()
             {
                 RoleId   = db.Roles.Max(r => r.Id),
                 Mobile   = register.Mobile,
                 Password = hash,
                 Code     = myrnd.ToString()
             };
             db.Users.Add(user);
             db.SaveChanges();
             SMSSender sms = new SMSSender();
             sms.SendSMS(register.Mobile, XamarinMVC.App_GlobalResources.Texts.RegisterSMS + Environment.NewLine + myrnd.ToString());
             return(Redirect("index"));
         }
         else
         {
             ModelState.AddModelError("Mobile", XamarinMVC.App_GlobalResources.Errors.RepeatMobile);
         }
     }
     return(View(register));
 }
Exemple #4
0
        public string SendSMS(string phoneNumber)
        {
            string createdCode = GetCodeVerification();

            SMSSender.SendSMS(phoneNumber, "Doğrulama Kodu : " + createdCode);
            return("4141");
        }
Exemple #5
0
    protected void btnconfirm_Click(object sender, EventArgs e)
    {
        string h    = ddlhour.SelectedItem.Value;
        string m    = ddlminute.SelectedItem.Value;
        string t    = ddltiming.SelectedItem.Value;
        string time = h + ":" + m + " " + t;
        string a    = appid.Text;

        DataBaseManager dbm = new DataBaseManager();
        string          sql = "update Appointment set Time='" + time + "', Status='Confirmed' where Id='" + a + "' ";

        if (dbm.ExecuteIUD(sql))
        {
            DataTable dt   = new DataTable();
            string    sql1 = "select * from Appointment where Id='" + a + "'";
            dt = dbm.ExecuteSelect(sql1);

            string    mobile  = dt.Rows[0]["Mobile"].ToString();
            string    name    = dt.Rows[0]["Name"].ToString();
            string    doctor  = dt.Rows[0]["Doctor"].ToString();
            string    date    = dt.Rows[0]["Date"].ToString();
            string    message = "Dear " + name + ", Your Appointment has been confirmed with " + doctor + " on " + date + " at " + time + ". Thanks";
            SMSSender sms     = new SMSSender();
            sms.SendSMS(mobile, message);
            Response.Write("<script>alert('Appointment Confirmed.');</script>");
        }
        else
        {
            Response.Write("<script>alert('Something went wrong.');</script>");
        }
    }
Exemple #6
0
        public ActionResult ForgotPassword(string phoneNum,
                                           string verifyCode)
        {
            //从TempData获得图形验证码
            string serverVerifyCode = (string)TempData["verifyCode"];

            if (serverVerifyCode != verifyCode)
            {
                return(Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "验证码错误"
                }));
            }
            var user = userService.GetByPhoneNum(phoneNum);

            if (user == null)
            {
                return(Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "没有这个手机号"
                }));
            }
            string appKey   = settingService.GetValue("如鹏短信平台AppKey");
            string userName = settingService.GetValue("如鹏短信平台UserName");
            string tempId   = settingService.GetValue("如鹏短信平台找回密码短信模板Id");
            //生成一个4位的短信验证码
            string smsCode = new Random().Next(1000, 9999).ToString();
            //发送短信
            SMSSender smsSender = new SMSSender();

            smsSender.AppKey   = appKey;
            smsSender.UserName = userName;
            var sendResult = smsSender.SendSMS(tempId, smsCode, phoneNum);

            //如果发送成功
            if (sendResult.code == 0)
            {
                //把发送短信的时候存入TempData
                TempData["ForgotPasswordPhoneNum"] = phoneNum;
                //发送给手机的验证码也存入TempData
                TempData["SmsCode"] = smsCode;
                return(Json(new AjaxResult {
                    Status = "ok"
                }));
            }
            else
            {
                return(Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = sendResult.msg
                }));
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string       name     = TextBox1.Text;
        string       age      = TextBox2.Text;
        string       mobile   = TextBox3.Text;
        string       gender   = RadioButtonList1.SelectedItem.Text;
        string       email    = TextBox4.Text;
        string       password = TextBox5.Text;
        CryptoGraphy cg       = new CryptoGraphy();

        password = cg.MD5Hash(password);
        string specialmedical = TextBox6.Text;

        Random rnd = new Random();

        string otp       = rnd.Next(100000, 999999).ToString();
        bool   otpstatus = false;

        string date = DateTime.Now.ToString("MM/dd/yyyy");
        string time = DateTime.Now.ToString("HH:mm:ss");

        DataBaseManager dbm = new DataBaseManager();

        string    checkemail = "select * from RegistrationTbl where Email='" + email + "'";
        DataTable dt         = new DataTable();

        dt = dbm.ExecuteSelect(checkemail);
        if (dt.Rows.Count > 0)
        {
            Response.Write("<script>alert('Email ID is already registered. Please use another Email ID')</script>");
        }
        else
        {
            string query = "insert into RegistrationTbl(Name,Age,Mobile,Gender,Email,Password,SpecialMedicalCondition,OTP,OTPStatus,Date,Time) values('" + name + "','" + age + "','" + mobile + "','" + gender + "','" + email + "','" + password + "','" + specialmedical + "','" + otp + "','" + otpstatus + "','" + date + "','" + time + "')";
            if (dbm.ExecuteIUD(query))
            {
                // send OTP and Redirect to OTP Verification page

                SMSSender sms     = new SMSSender();
                string    message = "Dear " + name + ", Your OTP Verification Code is - " + otp;
                bool      smsst   = sms.SendSMS(mobile, message);

                // Create Session for OTP Verification

                Session["RegEmail"] = email;

                Response.Write("<script>alert('Data Saved. We have sent you OTP Code, Please enter to proceed.'); window.location.href='OTPVerification.aspx';</script>");
            }
            else
            {
                // Query Error
                Response.Write("<script>alert('Something went wrong, please try again leter, some technical issue.')</script>");
            }
        }
    }
        private async Task CreateAndSendMessage(Message message)
        {
            message.DateSent = DateTime.UtcNow;
            _context.Add(message);
            await _context.SaveChangesAsync();

            var subscribers = await _context.Subscribers.ToListAsync();

            foreach (var s in subscribers)
            {
                await _smsSender.SendSMS(message, s);
            }
        }
Exemple #9
0
    protected void BtnSendSMS_Click(object sender, EventArgs e)
    {
        SMSSender mss = new SMSSender();
        bool      x   = mss.SendSMS(TxtMobNo.Text, TxtMsg.Text);

        if (x == true)
        {
            TxtMsg.Text   = "";
            TxtMobNo.Text = "";
            Response.Write("<script>alert('SMS Sent Successfully')</script>");
        }
        else
        {
            Response.Write("<script>alert('Unable To Send SMS')</script>");
        }
    }
    protected void Sendbtn_Click(object sender, EventArgs e)
    {
        SMSSender ms = new SMSSender();
        bool      x  = ms.SendSMS(txtMobNo.Text, txtMsg.Text);

        if (x == true)
        {
            txtMobNo.Text = "";
            txtMsg.Text   = "";
            Response.Write("<script>alert('SMS Sent Successfully.')</script>");
        }
        else
        {
            Response.Write("<script>alert('Unable To Send SMS.')</script>");
        }
    }
Exemple #11
0
        /// <summary>
        /// 验证手机和图形验证码,然后发送短信
        /// </summary>
        /// <param name="phoneNum">手机</param>
        /// <param name="verifyCode">图形验证码</param>
        /// <returns></returns>
        public ActionResult SendSmsVerifyCode(string phoneNum, string verifyCode)
        {
            string serverVerifyCode = (string)TempData["verifyCode"];//取服务器中保存的图形验证码

            if (serverVerifyCode != verifyCode)
            {
                return(Json(new AjaxResult {
                    Status = "error", ErrorMsg = "图形验证码填写错误"
                }));
            }
            //配置信息从T_Settings 表读取
            string appKey   = settingService.GetValue("如鹏短信平台AppKey");
            string userName = settingService.GetValue("如鹏短信平台UserName");
            string tempId   = settingService.GetValue("如鹏短信平台注册短信模板Id");

            //短信验证码一般都是数字
            string smsCode = new Random().Next(1000, 9999).ToString();

            TempData["smsCode"] = smsCode;//给ActionResult Register(UserRegModel model)用

            //发送短信
            SMSSender smsSender = new SMSSender();

            smsSender.AppKey   = appKey;
            smsSender.UserName = userName;
            var sendResult = smsSender.SendSMS(tempId, smsCode, phoneNum);

            //发送成功
            if (sendResult.code == 0)
            {
                //把发送验证码的手机号放到TempData,在注册的时候再次检查一下注册的是不是这个手机号
                //防止网站漏洞
                TempData["RegPhoneNum"] = phoneNum;

                return(Json(new AjaxResult {
                    Status = "ok"
                }));
            }
            else
            {
                return(Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = sendResult.msg
                }));
            }
        }
Exemple #12
0
        public ActionResult Send(string to, string from, string message)
        {
            var results = SMSSender.SendSMS(to, from, message);

            if (results.messages.Count >= 1)
            {
                if (results.messages[0].status == "0")
                {
                    ViewBag.result = "Message sent successfully.";
                    Debug.WriteLine("Message sent successfully.");
                }
                else
                {
                    ViewBag.result = $"Message failed with error: { results.messages[0].error_text}";
                    Debug.WriteLine($"Message failed with error: {results.messages[0].error_text}");
                }
            }

            return(View("Index"));
        }
Exemple #13
0
 public ActionResult CheckMobile(CheckMobileViewModel checkMobile)
 {
     if (ModelState.IsValid)
     {
         var user = db.Users.FirstOrDefault(u => u.Mobile == checkMobile.Mobile);
         if (user != null)
         {
             SMSSender   sms    = new SMSSender();
             MailMessage mail   = new MailMessage("*****@*****.**", "*****@*****.**", XamarinMVC.App_GlobalResources.Texts.ActivisionCode, user.Code);
             SmtpClient  client = new SmtpClient();
             client.Send(mail);
             sms.SendSMS(user.Mobile, " " + XamarinMVC.App_GlobalResources.Texts.ActivisionCode + ": " + user.Code);
             return(RedirectToAction("ForgetPassword"));
         }
         else
         {
             ModelState.AddModelError("Mobile", XamarinMVC.App_GlobalResources.Errors.CheckMobile);
         }
     }
     return(View());
 }
Exemple #14
0
    protected void Unnamed_ServerClick(object sender, EventArgs e)
    {
        string          regemail = Session["RegEmail"].ToString();
        DataBaseManager dbm      = new DataBaseManager();
        string          sql1     = "select * from RegistrationTbl where Email='" + regemail + "'";
        DataTable       dt       = new DataTable();

        dt = dbm.ExecuteSelect(sql1);

        string name   = dt.Rows[0]["Name"].ToString();
        string mobile = dt.Rows[0]["Mobile"].ToString();
        string otp    = dt.Rows[0]["OTP"].ToString();

        SMSSender sms     = new SMSSender();
        string    message = "Dear " + name + ", Your OTP Verification Code is - " + otp;
        bool      smsst   = sms.SendSMS(mobile, message);

        // Create Session for OTP Verification

        Session["RegEmail"] = regemail;
        Response.Write("<script>alert('We have Resent you OTP Code, Please enter to proceed.'); window.location.href='OTPVerification.aspx';</script>");
    }
Exemple #15
0
        public async Task BroadcastMessage(string message)
        {
            var notifiationMsgRecieved = new
            {
                Notification = string.Empty,
                Value        = string.Empty,
                DeviceId     = string.Empty,
                EmployeeId   = string.Empty,
                PersonName   = string.Empty,
                PersonId     = string.Empty,
                Desc         = string.Empty,
                Timestamp    = string.Empty
            };

            notifiationMsgRecieved = JsonConvert.DeserializeAnonymousType(message, notifiationMsgRecieved);

            //string notificationMessageToSend = message;

            // Prepare push message
            if (notifiationMsgRecieved.Notification == Configuration["TemperaturePolicyName"])
            {
                // Get Config setting for temperature threshold
                decimal thresholdTemperature = ConfigReader.GetTemperatureThreshold(DbContext, Configuration);

                // Parse received teperature
                bool res = decimal.TryParse(notifiationMsgRecieved.Value, out decimal receivedTeperature);

                if (res)
                {
                    // Check threshold
                    if (receivedTeperature >= thresholdTemperature)
                    {
                        // Notify everyone
                        await Clients.All.ReceiveMessage(Configuration["HighTemperatureAlertNotificationString"]);

                        #region SMS
                        // Notify SMS
                        var sendAlertSMSConfig = ConfigReader.GetSendAlertForTemperatureSMSEnabled(DbContext, Configuration);
                        if (sendAlertSMSConfig)
                        {
                            // Prepare SMS
                            string smsBody = ConfigReader.GetTemperatureAlertHeader(DbContext, Configuration);

                            // Get SMS sender
                            string smsSender = ConfigReader.GetSMSSender(DbContext, Configuration);

                            // Get mobile numbers for this site
                            var v = from a in DbContext.Devices
                                    join b in DbContext.Gates on a.GateId equals b.GateId
                                    join c in DbContext.AlertMobileNumbers on b.Floor.Building.SiteId equals c.SiteId
                                    where a.DeviceId == notifiationMsgRecieved.DeviceId
                                    select new
                            {
                                c.MobileNumber,
                                b.Floor.Building.BuildingName,
                                b.GateNumber
                            };

                            // Send SMS
                            foreach (var v1 in v)
                            {
                                var body = smsBody + $"\nName - {notifiationMsgRecieved.PersonName}\n" +
                                           $"Temperature - {notifiationMsgRecieved.Value}\n" +
                                           $"Building - {v1.BuildingName}\n" +
                                           $"Gate - {v1.GateNumber}\n" +
                                           $"Time - {Convert.ToDateTime(notifiationMsgRecieved.Timestamp).ToString("MMMM dd hh:mm tt")}";

                                try
                                {
                                    SMSSender.SendSMS(ApiKey: Configuration["NexmmoApiKey"],
                                                      ApiSecret: Configuration["NexmoApiSecret"],
                                                      from: smsSender,
                                                      to: v1.MobileNumber,
                                                      msg: body);
                                }
                                catch (Exception e)
                                {
                                    _logger.LogError($"Error sending SMS to {v1.MobileNumber}. Error: {e.Message}");
                                }
                            }
                        }
                        #endregion

                        #region Email
                        // Notify email
                        var sendAlertEmailConfig = ConfigReader.GetSendAlertForTemperatureEmailEnabled(DbContext, Configuration);
                        if (sendAlertEmailConfig)
                        {
                            var fromAddress = new MailAddress(Configuration["EmailSenderId"],
                                                              ConfigReader.GetEmailSenderName(DbContext, Configuration));

                            string fromPassword = Configuration["EmailSenderPassword"];

                            // Prepare Email
                            string emailSubject = ConfigReader.GetTemperatureAlertEmailSubject(DbContext, Configuration);

                            // Get Email addresses for this site
                            var v = from a in DbContext.Devices
                                    join b in DbContext.Gates on a.GateId equals b.GateId
                                    join c in DbContext.AlertEmailAddresses on b.Floor.Building.SiteId equals c.SiteId
                                    where a.DeviceId == notifiationMsgRecieved.DeviceId
                                    select new
                            {
                                c.EmailId,
                                c.Name,
                                b.Floor.Building.BuildingName,
                                b.GateNumber
                            };

                            // Send Email
                            foreach (var v1 in v)
                            {
                                var body = $"\nName - {notifiationMsgRecieved.PersonName}\n" +
                                           $"Temperature - {notifiationMsgRecieved.Value}\n" +
                                           $"Building - {v1.BuildingName}\n" +
                                           $"Gate - {v1.GateNumber}\n" +
                                           $"Time - {Convert.ToDateTime(notifiationMsgRecieved.Timestamp).ToString("MMMM dd hh:mm tt")}";

                                var smtp = new SmtpClient
                                {
                                    Host                  = Configuration["SMTPHost"],
                                    Port                  = Convert.ToInt32(Configuration["SMTPPort"]),
                                    EnableSsl             = true,
                                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                                    UseDefaultCredentials = true,
                                    Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                                };

                                var toAddress = new MailAddress(v1.EmailId, v1.Name);

                                using (var mailMessage = new MailMessage(fromAddress, toAddress)
                                {
                                    Subject = emailSubject,
                                    Body = body
                                })
                                {
                                    try
                                    {
                                        smtp.Send(mailMessage);
                                    }
                                    catch (Exception e)
                                    {
                                        _logger.LogError($"Error while sending email: {v1.EmailId}. Error: {e.Message}");
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }

                await Clients.All.ReceiveMessage(Configuration["TemperatureEventNotificationString"]);
            }

            if (notifiationMsgRecieved.Notification == Configuration["NoMaskPolicyName"])
            {
                await Clients.All.ReceiveMessage(Configuration["NoMaskAlertNotificationString"]);

                #region SMS
                // Notify SMS
                var sendAlertSMSConfig = ConfigReader.GetSendAlertForMaskSMSEnabled(DbContext, Configuration);
                if (sendAlertSMSConfig)
                {
                    // Prepare SMS
                    string smsBody = ConfigReader.GetMaskAlertHeader(DbContext, Configuration);

                    // Get SMS sender
                    string smsSender = ConfigReader.GetSMSSender(DbContext, Configuration);

                    // Get mobile numbers for this site
                    var v = from a in DbContext.Devices
                            join b in DbContext.Gates on a.GateId equals b.GateId
                            join c in DbContext.AlertMobileNumbers on b.Floor.Building.SiteId equals c.SiteId
                            where a.DeviceId == notifiationMsgRecieved.DeviceId
                            select new
                    {
                        c.MobileNumber,
                        b.Floor.Building.BuildingName,
                        b.GateNumber
                    };

                    // Send SMS
                    foreach (var v1 in v)
                    {
                        var body = smsBody + $"\nName - {notifiationMsgRecieved.PersonName}\n" +
                                   $"Building - {v1.BuildingName}\n" +
                                   $"Gate - {v1.GateNumber}\n" +
                                   $"Time - {Convert.ToDateTime(notifiationMsgRecieved.Timestamp).ToString("MMMM dd hh:mm tt")}";

                        try
                        {
                            SMSSender.SendSMS(ApiKey: Configuration["NexmmoApiKey"],
                                              ApiSecret: Configuration["NexmoApiSecret"],
                                              from: smsSender,
                                              to: v1.MobileNumber,
                                              msg: body);
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Error sending SMS to {v1.MobileNumber}. Error: {e.Message}");
                        }
                    }
                }
                #endregion

                #region Email
                // Notify email
                var sendAlertEmailConfig = ConfigReader.GetSendAlertForMaskEmailEnabled(DbContext, Configuration);
                if (sendAlertEmailConfig)
                {
                    var fromAddress = new MailAddress(Configuration["EmailSenderId"],
                                                      ConfigReader.GetEmailSenderName(DbContext, Configuration));

                    string fromPassword = Configuration["EmailSenderPassword"];

                    // Prepare Email
                    string emailSubject = ConfigReader.GetMaskAlertEmailSubject(DbContext, Configuration);

                    // Get Email addresses for this site
                    var v = from a in DbContext.Devices
                            join b in DbContext.Gates on a.GateId equals b.GateId
                            join c in DbContext.AlertEmailAddresses on b.Floor.Building.SiteId equals c.SiteId
                            where a.DeviceId == notifiationMsgRecieved.DeviceId
                            select new
                    {
                        c.EmailId,
                        c.Name,
                        b.Floor.Building.BuildingName,
                        b.GateNumber
                    };

                    // Send Email
                    foreach (var v1 in v)
                    {
                        var body = $"\nName - {notifiationMsgRecieved.PersonName}\n" +
                                   $"Building - {v1.BuildingName}\n" +
                                   $"Gate - {v1.GateNumber}\n" +
                                   $"Time - {Convert.ToDateTime(notifiationMsgRecieved.Timestamp).ToString("MMMM dd hh:mm tt")}";

                        var smtp = new SmtpClient
                        {
                            Host                  = Configuration["SMTPHost"],
                            Port                  = Convert.ToInt32(Configuration["SMTPPort"]),
                            EnableSsl             = true,
                            DeliveryMethod        = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = true,
                            Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                        };

                        var toAddress = new MailAddress(v1.EmailId, v1.Name);

                        using (var mailMessage = new MailMessage(fromAddress, toAddress)
                        {
                            Subject = emailSubject,
                            Body = body
                        })
                        {
                            try
                            {
                                smtp.Send(mailMessage);
                            }
                            catch (Exception e)
                            {
                                _logger.LogError($"Error while sending email: {v1.EmailId}. Error: {e.Message}");
                            }
                        }
                    }
                }
            }
            #endregion
        }
        public ActionResult BankCallback()
        {
            bool   Run_bpReversalRequest = false;
            long   saleReferenceId       = -999;
            long   saleOrderId           = -999;
            string resultCode_bpPayRequest;

            BankMellat bankmellat = new BankMellat();

            try
            {
                saleReferenceId         = long.Parse(Request.Params["SaleReferenceId"].ToString());
                saleOrderId             = long.Parse(Request.Params["SaleOrderId"].ToString());
                resultCode_bpPayRequest = Request.Params["ResCode"].ToString();

                //Result Code
                string resultCode_bpinquiryRequest = "-9999";
                string resultCode_bpSettleRequest  = "-9999";
                string resultCode_bpVerifyRequest  = "-9999";

                if (int.Parse(resultCode_bpPayRequest) == (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_ﺑﺎ_ﻣﻮﻓﻘﻴﺖ_اﻧﺠﺎم_ﺷﺪ)
                {
                    resultCode_bpVerifyRequest = bankmellat.VerifyRequest(saleOrderId, saleOrderId, saleReferenceId);

                    if (string.IsNullOrEmpty(resultCode_bpVerifyRequest))
                    {
                        resultCode_bpinquiryRequest = bankmellat.InquiryRequest(saleOrderId, saleOrderId, saleReferenceId);
                        if (int.Parse(resultCode_bpinquiryRequest) != (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_ﺑﺎ_ﻣﻮﻓﻘﻴﺖ_اﻧﺠﺎم_ﺷﺪ)
                        {
                            //the transactrion faild
                            TempData["Message"]   = bankmellat.DesribtionStatusCode(int.Parse(resultCode_bpinquiryRequest.Replace("_", " ")));
                            Run_bpReversalRequest = true;
                        }
                    }

                    if ((int.Parse(resultCode_bpVerifyRequest) == (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_ﺑﺎ_ﻣﻮﻓﻘﻴﺖ_اﻧﺠﺎم_ﺷﺪ)
                        ||
                        (int.Parse(resultCode_bpinquiryRequest) == (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_ﺑﺎ_ﻣﻮﻓﻘﻴﺖ_اﻧﺠﺎم_ﺷﺪ))
                    {
                        resultCode_bpSettleRequest = bankmellat.SettleRequest(saleOrderId, saleOrderId, saleReferenceId);
                        if ((int.Parse(resultCode_bpSettleRequest) == (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_ﺑﺎ_ﻣﻮﻓﻘﻴﺖ_اﻧﺠﺎم_ﺷﺪ) ||
                            (int.Parse(resultCode_bpSettleRequest) == (int)BankMellat.MellatBankReturnCode.ﺗﺮاﻛﻨﺶ_Settle_ﺷﺪه_اﺳﺖ))
                        {
                            TempData["Message"]  = "تراکنش شما با موفقیت انجام شد ";
                            TempData["Message"] += Environment.NewLine + " لطفا شماره پیگیری را یادداشت نمایید" + Environment.NewLine + saleReferenceId;
                        }
                        else
                        {
                            TempData["Message"]   = bankmellat.DesribtionStatusCode(int.Parse(resultCode_bpSettleRequest.Replace("_", " ")));
                            Run_bpReversalRequest = true;
                        }

                        string strToday = PC.GetYear(DateTime.Now).ToString("0000") + "/" + PC.GetMonth(DateTime.Now).ToString("00") + "/" + PC.GetDayOfMonth(DateTime.Now).ToString("00");

                        var factor = db.Factors.FirstOrDefault(f => f.Number == saleOrderId.ToString());

                        factor.IsPay     = true;
                        factor.PayNumber = saleReferenceId.ToString();
                        factor.PayDate   = strToday;
                        factor.PayTime   = DateTime.Now.ToShortTimeString();

                        db.SaveChanges();
                        var details = db.FactorDetail.Where(d => d.FactorId == factor.Id).ToList();
                        foreach (var item in details)
                        {
                            var product = db.Products.Find(item.ProductId);
                            product.Quantity = product.Quantity - item.Count;
                            db.SaveChanges();
                        }
                        var user = db.Users.FirstOrDefault(u => u.Mobile == User.Identity.Name);

                        var setting = db.Settings.FirstOrDefault();

                        try
                        {
                            if (setting.FactorIsSend)
                            {
                                sms.SendSMS(user.Mobile, "صورت حساب جدید شما در فروشگاه با مبلغ " + factor.Price.ToString());
                            }

                            if (setting.PayIsSend)
                            {
                                sms.SendSMS(user.Mobile, "صورت حساب جدید شما در فروشگاه با موفقیت پرداخت شد. شماره پیگیری شما  " + factor.Number.ToString());
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        TempData["Message"]   = bankmellat.DesribtionStatusCode(int.Parse(resultCode_bpVerifyRequest.Replace("_", " ")));
                        Run_bpReversalRequest = true;
                    }
                }
                else
                {
                    TempData["Message"]   = bankmellat.DesribtionStatusCode(int.Parse(resultCode_bpPayRequest)).Replace("_", " ");
                    Run_bpReversalRequest = true;
                }

                return(RedirectToAction("ShowError", "Payment"));
            }
            catch (Exception Error)
            {
                TempData["Message"] = "متاسفانه خطایی رخ داده است، لطفا مجددا عملیات خود را انجام دهید در صورت تکرار این مشکل را به بخش پشتیبانی اطلاع دهید";
                // Save and send Error for admin user
                Run_bpReversalRequest = true;
                return(RedirectToAction("ShowError", "Payment"));
            }
            finally
            {
                if (Run_bpReversalRequest) //ReversalRequest
                {
                    if (saleOrderId != -999 && saleReferenceId != -999)
                    {
                        bankmellat.bpReversalRequest(saleOrderId, saleOrderId, saleReferenceId);
                    }
                    // Save information to Database...
                }
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            #region test component
            //Console.WriteLine(Helper.GenerateCaptchaCode(4));
            //SmtpHelper.SendEmail();
            //ImgHelper.GenerateProcessedImage();
            //ImgHelper.GenerateWatermark();
            //ImgHelper.GenerateCaptchaCodeImage();
            //LogHelper.AddLog();
            //QuartzHelper.ScheduleByDate();
            //QuartzHelper.ScheduleByInterval();

            //Type type = Type.GetType("Long.Utilities.TestJob");
            //Console.WriteLine(type.Name);
            #endregion

            #region autoFac
            //MyIBLL.IDogBll dog = new MyBllImpl.DogBll();

            //ContainerBuilder builder = new ContainerBuilder();

            //builder.RegisterType<DogBll>().As<IDogBll>();//注册实现类Service1,当请求IService1接口的时候返回Service1的对象。原理代码,很少写
            //IContainer resolver = builder.Build();
            //IDogBll dog = resolver.Resolve<IDogBll>();

            //Assembly asm = Assembly.Load("MyBllImpl");
            //builder.RegisterAssemblyTypes(asm).AsImplementedInterfaces().PropertiesAutowired();//这是最常用的用法!
            //IContainer resolver = builder.Build();

            ////IDogBll dog = resolver.Resolve<IDogBll>();
            ////dog.Bark();
            ////ISchool school = resolver.Resolve<ISchool>();
            ////school.FangXue();

            //IEnumerable<IUserBll> userBlls = resolver.Resolve<IEnumerable<IUserBll>>();
            //foreach (var bll in userBlls)
            //{
            //    Console.WriteLine(bll.GetType());
            //    bll.AddNew("dalong","123");
            //}
            #endregion

            #region sms
            //string userName = "******";
            //string appKey = "fdsafasdf@adfasdfa";
            //string templateId = "183";
            //string code = "6666";
            //string phoneNum = "18918918189";
            ///*
            //            WebClient wc = new WebClient();
            //            string url = "http://sms.rupeng.cn/SendSms.ashx?userName="******"&appKey=" + Uri.EscapeDataString(appKey) +
            //                "&templateId=" + templateId + "&code=" + Uri.EscapeDataString(code) +
            //                "&phoneNum=" + phoneNum;
            //            wc.Encoding = Encoding.UTF8;
            //            string resp = wc.DownloadString(url);
            //            //发出url这样一个http请求(Get请求)返回值为响应报文体
            //            Console.WriteLine(resp);
            //            */
            //RuPengSMSSender sender = new RuPengSMSSender();
            //sender.AppKey = appKey;
            //sender.UserName = userName;
            //var result = sender.SendSMS(templateId, code, phoneNum);
            //Console.WriteLine("返回码:" + result.code + ",消息:" + result.msg);
            #endregion

            #region remote powershell

            //WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
            //connectionInfo.ComputerName = "BJLE0005";
            //var pwd = ConvertStringToSecureString("m3diaR00mT3stPl@tform");
            //connectionInfo.Credential = new PSCredential(@"MR.ERICSSON.SE\mtpbot", pwd);

            //connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
            //connectionInfo.OpenTimeout = 1 * 60 * 1000; // 1 minute.


            //using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
            //{
            //    remoteRunspace.Open();

            //    // Create a PowerShell object to run commands in the remote runspace.
            //    using (PowerShell powershell = PowerShell.Create())
            //    {
            //        powershell.Runspace = remoteRunspace;
            //        powershell.AddCommand(@"C:\Users\mtpbot\Desktop\test.bat");
            //        powershell.Invoke();

            //        Collection<PSObject> results = powershell.Invoke();

            //        Console.WriteLine("--------------------------------");
            //        Console.WriteLine("result count:" + results.Count);

            //        for (int i = 0; i < results.Count; i++)
            //        {
            //            Console.WriteLine(
            //                              "{0}:{1}",
            //                              i,
            //                              results[i].ToString()
            //                              );
            //        }
            //    }

            //    remoteRunspace.Close();
            //}
            #endregion

            #region buildService
            //string sql = "select * from T_Tasks";
            //DataTable dataTable= sqlHelper.executeDataTable(sql);
            //foreach (DataRow dataRow in dataTable.Rows)
            //{
            //    Console.WriteLine(dataRow["Status"].ToString()+dataRow["ScriptPath"]);
            //}


            //using (Runspace runspace = RunspaceFactory.CreateRunspace())
            //{
            //    runspace.Open();
            //    // Create a PowerShell object to run commands in the remote runspace.
            //    using (PowerShell powershell = PowerShell.Create())
            //    {
            //        powershell.Runspace = runspace;
            //        powershell.AddCommand(@"C:\Users\banana\Desktop\getProcessId.ps1");

            //        Collection<PSObject> results = powershell.Invoke();

            //        Console.WriteLine("--------------------------------");
            //        Console.WriteLine("result count:" + results.Count);

            //        for (int i = 0; i < results.Count; i++)
            //        {
            //            Console.WriteLine(
            //                              "{0}:{1}",
            //                              i,
            //                              results[i].ToString()
            //                              );
            //        }

            //        powershell.AddCommand(@"C:\Users\banana\Desktop\fakeBuild.ps1");
            //        Collection<PSObject> results2 = powershell.Invoke();

            //        Console.WriteLine("--------------------------------");
            //        Console.WriteLine("result2 count:" + results.Count);

            //        for (int i = 0; i < results2.Count; i++)
            //        {
            //            Console.WriteLine(
            //                              "{0}:{1}",
            //                              i,
            //                              results2[i].ToString()
            //                              );
            //        }
            //    }

            //    runspace.Close();
            //}


            #endregion

            #region hashtable & dictionary
            //Hashtable hashtable = new Hashtable();
            //hashtable.Add("name", "dalong");
            //Console.WriteLine(hashtable["name"]);

            //Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            //keyValuePairs.Add("name", "dalong");
            //keyValuePairs.Add("age", "18");
            //Console.WriteLine(keyValuePairs["name"]);
            //Console.WriteLine("==========");
            //foreach (var keyValuePair in keyValuePairs)
            //{
            //    Console.WriteLine(keyValuePair.Key);
            //    Console.WriteLine(keyValuePair.Value);
            //    Console.WriteLine("==========");
            //}
            #endregion

            #region create database
            //using (ZSZDbContext ctx = new ZSZDbContext())
            //{
            //    ctx.Database.Delete();
            //    ctx.Database.Create();
            //}

            //Console.WriteLine("ok");
            //Console.ReadKey();
            #endregion

            #region test string
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cmbwwsMRnxGJgAAAAIAAAABAAAADwAAAAcAAABMAAAAAAAAAApNaWNyb3NvZnQAAAAAAAAdUGxheVJlYWR5IFNMMCBTZXJ2ZXIgUm9vdCBDQQAAAAAAAAAIMS4wLjAuMQAAAQAIAAAAkAABAEA6OPlVasx9gd4f7dnZoS2EoWubrKGikufmx2HD30bycFu5p31Yw69YLVkeSVF2GEO1/TtRL9juw0D2wEtCl9/zAAACAIZNYc/yJW5CLFaLPCgAHPs+FSdlhYS6BSG3mxgo2TbeHYJqj8Pm5/p6kNXKKUbx9kou+59dz/5+Q060QpP6xas=";
            //Console.WriteLine(s1==s2);
            //string s1 = @"netsh interface ipv4 set subinterface 'Ethernet' mtu=1430 store=persistent";
            //string s2 = @"netsh interface ipv4 set subinterface 'Ethernet' mtu=1430 store=persistent";
            //string s3 = @"netsh interface ipv4 set subinterface 'Ethernet' mtu=1430 store=persistent";

            //Console.WriteLine(s1 == s2);
            //Console.WriteLine(s1 == s3);
            #endregion

            #region testRandom
            //string dT = DateTime.Now.ToFileTimeUtc().ToString();
            //Console.WriteLine(dT);
            //string dT2 = DateTime.Now.ToFileTimeUtc().ToString();
            //Console.WriteLine(dT2);
            //Console.WriteLine(dT.Length);
            //string guid= Guid.NewGuid().ToString();
            //Console.WriteLine(guid);
            //Console.WriteLine(guid.Length);

            //char[] data = { 'a','c','d','e','f','h','k','m',
            //    'n','r','s','t','w','x','y'};
            //StringBuilder sb = new StringBuilder();
            //Random rand = new Random();
            //for (int i = 0; i < 2000; i++)
            //{

            //    int index = rand.Next(data.Length);//[0,data.length)
            //    char ch = data[index];
            //    sb.Append(ch);
            //}
            //Console.WriteLine(sb.ToString());
            #endregion

            //test enum
            //Console.WriteLine((int)TestEnum.le03);

            //sms

            SMSSender sender = new SMSSender {
                AppKey = "65454289d409eef779e808", UserName = "******"
            };
            Long.Utilities.RuPengSMSResult result = sender.SendSMS("1124", "2009", "15771250317");
            Console.WriteLine(result.code + ": " + result.msg);


            Console.WriteLine("ok");
            Console.ReadKey();
        }