Ejemplo n.º 1
0
        /// <summary>
        /// 是否具有查询客户信息权限
        /// </summary>
        private string CanSearchtCust(DataRow row)
        {
            int commId = AppGlobal.StrToInt(row["CommID"].ToString());

            return(new ApiResult(true, HasFunctionCode(commId, "1028")).toJson());
        }
Ejemplo n.º 2
0
        public string GenerateOrder(DataRow row)
        {
            #region 获取基本参数
            string CommunityId = string.Empty;
            if (row.Table.Columns.Contains("CommunityId"))
            {
                CommunityId = row["CommunityId"].ToString();
            }
            string RoomID = string.Empty;
            if (row.Table.Columns.Contains("RoomID"))
            {
                RoomID = row["RoomID"].ToString();
            }
            string CustID = string.Empty;
            if (row.Table.Columns.Contains("CustID"))
            {
                CustID = row["CustID"].ToString();
            }
            if (!row.Table.Columns.Contains("PayChannel") || string.IsNullOrEmpty(row["PayChannel"].ToString()))
            {
                return(new ApiResult(false, "参数PayChannel有误").toJson());
            }

            var payChannel = row["PayChannel"].ToString();
            var payType    = 0;
            if (payChannel.ToLower() == "allinpay_alipay")
            {
                payChannel = "A03";
                payType    = 1;
            }
            else if (payChannel.ToLower() == "allinpay_wechatpay")
            {
                payChannel = "W06";
                payType    = 2;
            }
            else
            {
                return(new ApiResult(false, "参数PayChannel有误").toJson());
            }

            #endregion

            var community = PubInfo.GetCommunity(CommunityId);
            if (community == null)
            {
                return(JSONHelper.FromString(false, "未查询到小区信息"));
            }

            int CommID = AppGlobal.StrToInt(community.CommID);
            PubConstant.hmWyglConnectionString = PubInfo.GetConnectionStr(community);

            // 获取对应支付配置
            AllinConfig allinConfig;
            using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString))
            {
                dynamic tb_Payment_Config = erpConn.QueryFirstOrDefault <dynamic>("SELECT * FROM Tb_Payment_Config WITH(NOLOCK) WHERE CommID = @CommID", new { CommID });
                if (null == tb_Payment_Config)
                {
                    return(new ApiResult(false, "该项目未开通对应支付方式").toJson());
                }
                try
                {
                    allinConfig = JsonConvert.DeserializeObject <AllinConfig>(tb_Payment_Config.Config);
                    if (null == allinConfig)
                    {
                        return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                    }
                }
                catch (Exception)
                {
                    return(new ApiResult(false, "该项目支付类型对应配置有误").toJson());
                }

                #region 计算金额
                if (!row.Table.Columns.Contains("PayData") || string.IsNullOrEmpty(row["PayData"].ToString()))
                {
                    return(new ApiResult(false, "缺少参数PayData").toJson());
                }
                string PayData = row["PayData"].ToString();
                if (!PubInfo.CheckPayData(Global_Fun.BurstConnectionString(CommID, Global_Fun.BURST_TYPE_CHARGE), Convert.ToInt64(CustID), Convert.ToInt64(RoomID), PayData, out decimal Amt, out string errMsg, true, false, !"1940".Equals(Global_Var.LoginCorpID)))
                {
                    return(new ApiResult(false, errMsg).toJson());
                }
                if (Amt <= 0.00M)
                {
                    return(new ApiResult(false, "金额必须大于0").toJson());
                }
                #endregion

                JObject PayDataObj = JObject.Parse(PayData);
                int     Type       = (int)PayDataObj["Type"];

                #region 查询项目名称和房屋编号,拼接费用备注
                string FeesMemo = string.Empty;
                string RoomSign = string.Empty;
                if (Type == 1)
                {
                    FeesMemo = "物业综合费用缴纳";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                else
                {
                    FeesMemo = "物业综合费用预存";
                    string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID });
                    if (string.IsNullOrEmpty(CommName))
                    {
                        CommName = Convert.ToString(CommID);
                    }
                    RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID });
                    if (string.IsNullOrEmpty(RoomSign))
                    {
                        RoomSign = Convert.ToString(RoomID);
                    }

                    FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign);
                }
                #endregion

                string NoticeId = Guid.NewGuid().ToString();

                // 生成订单
                if (erpConn.Execute("INSERT INTO Tb_Notice(Id, CommID, RoomID, CustID, PayData, CreateTime) VALUES(@Id, @CommID, @RoomID, @CustID, @PayData, @CreateTime)", new { Id = NoticeId, CommID, RoomID, CustID, PayData, CreateTime = DateTime.Now.ToString() }) <= 0)
                {
                    return(new ApiResult(false, "创建收款订单失败,请重试").toJson());
                }
                string ChargeMode = "业主APP缴费";
                #region 修改收款方式
                if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Tb_Notice') AND name = 'ChargeMode'") > 0)
                {
                    erpConn.Execute("UPDATE Tb_Notice SET ChargeMode = @ChargeMode WHERE Id = @Id", new { ChargeMode, Id = NoticeId });
                }
                #endregion
                #region 请求通联微信支付
                DateTime dateNow = DateTime.Now;
                string   OrderSN = dateNow.ToString("yyyyMMddHHmmssfff") + Utils.BuildRandomStr(3);

                #region 获取对应类型的下账地址
                string PaymentNotifyUrl = string.Empty;
                if (Type == 1)
                {
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Notify_Url") + "?CommID=" + CommID;
                }
                else
                {
                    PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Prec_Notify_Url") + "?CommID=" + CommID;
                }
                #endregion

                Dictionary <string, string> param;
                try
                {
                    param = SybWxPayService.Pay(Convert.ToInt64(Amt * 100), OrderSN, payChannel, FeesMemo, RoomSign, "", "", PaymentNotifyUrl, "", "", "", "", allinConfig.orgid, allinConfig.appid, allinConfig.custid, allinConfig.appkey, allinConfig.subbranch);

                    if (param == null)
                    {
                        return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                    }
                }
#pragma warning disable CS0168 // 声明了变量“ex”,但从未使用过
                catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”,但从未使用过
                {
                    return(new ApiResult(false, "生成支付订单失败,请重试").toJson());
                }
                #endregion
                if (erpConn.Execute(@"INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) 
                                            VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)",
                                    new { PayType = payType, OrderSN = OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0)
                {
                    return(new ApiResult(false, "生成支付订单失败,请重试(1003)").toJson());
                }
                return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = param["payinfo"].ToString() }).toJson());
            }
        }
Ejemplo n.º 3
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                List <string> list = new List <string>();
                foreach (var item in context.Request.Params.AllKeys)
                {
                    list.Add($"{item}={context.Request.Params[item]}");
                }
                Business.Alipay.Log("收到微信通知" + context.Request.RawUrl + "?" + string.Join("&", list));

                HttpRequest Request = context.Request;
                context.Response.ContentType = "text/plain";

                string respcode    = "";
                string respmsg     = "";
                string orderId     = "";
                string CommunityId = "";

                //返回报文中不包含UPOG,表示Server端正确接收交易请求,则需要验证Server端返回报文的签名
                bool      IsValidate = false;
                WxPayData WxPostData = new WxPayData();
                string    Result     = Notify.NotifyDataFromContext(context, ref IsValidate, ref WxPostData);

                respcode    = WxPostData.GetValue("result_code").ToString();
                respmsg     = WxPostData.GetValue("result_code").ToString();
                orderId     = WxPostData.GetValue("out_trade_no").ToString();
                CommunityId = WxPostData.GetValue("attach").ToString();
                string userId = null;
                if (CommunityId.Contains(","))
                {
                    userId      = CommunityId.Split(',')[1];
                    CommunityId = CommunityId.Split(',')[0];
                }

                if (IsValidate == false)
                {
                    Business.WeiXinPay.Log("验签失败:" + CommunityId + "," + orderId.ToString());
                    Result = SetNotifyResult("FAIL", Result);
                    context.Response.Write(Result);
                    return;
                }

                Business.WeiXinPay.Log("微信支付验签成功:" + CommunityId + "," + orderId.ToString());

                if (IsValidate == true)
                {
                    //初始化参数
                    new Business.WeiXinPay().GenerateConfig(CommunityId);
                    //更新订单返回状态
                    Business.WeiXinPay.UpdateProperyOrder(CommunityId, orderId, respcode, respmsg);
                    //已收到应答,无需再通知
                    context.Response.Write(SetNotifyResult("SUCCESS", "OK"));
                    if (respcode == "SUCCESS")
                    {
                        string useHistoryId = null;

                        if (!string.IsNullOrEmpty(userId))
                        {
                            // 查询是否使用了积分
                            UsePoint(orderId, userId, out useHistoryId);
                        }

                        decimal total_fee = AppGlobal.StrToDec(WxPostData.GetValue("total_fee").ToString()) / 100.0m;

                        //下账
                        string ReceResult = Business.WeiXinPay.ReceProperyOrder(total_fee, CommunityId, orderId, useHistoryId);

                        if (!string.IsNullOrEmpty(userId))
                        {
                            // 下账成功,赠送积分
                            PresentedPoint(CommunityId, orderId, userId, useHistoryId, total_fee);
                        }

                        Business.WeiXinPay.Log("微信支付下账:" + CommunityId.ToString() + "," + orderId + "," + ReceResult);
                    }

                    Business.WeiXinPay.Log("微信支付流程:" + CommunityId.ToString() + "," + orderId + ",SUCCESS");
                }
            }
            catch (Exception E)
            {
                Business.WeiXinPay.Log(E.Message.ToString());
                context.Response.ContentType = "text/plain";
                context.Response.Write(SetNotifyResult("FAIL", E.Message.ToString()));
            }
        }
        /// <summary>
        /// 获取首页Banner列表
        /// </summary>
        public void GetBanners()
        {
            var source = this.mBannerService.GetBanners();

            AppGlobal.RenderResult <IList <Banner> >(ApiCode.Success, source);
        }
        protected override void Process()
        {
            switch (this.ActionName.ToLower())
            {
            case "login":

                this.Login();
                break;

            case "verificationuser":
                VerificationUser();
                break;

            case "login_progress":    //APP登录
                this.Login(false);
                break;

            case "logout":    //注销
                Logout();
                break;

            case "userbalance":
                this.GetUserBalance();
                break;

            case "autoregist":    //自助注册
                AutoRegist();
                break;

            case "news":    //获取平台消息
                this.GetNews();
                break;

            case "alertnews":
                this.GetAlertNews();
                break;

            case "getuserwhy":    //获取用户问候语
                GetUserWhy();
                break;

            case "settings":    //获取配置信息
                GetSettings();
                break;

            case "hotlottery":     //热门彩种
                GetHotLottery();
                break;

            case "banner":      //获取首页Banner列表
                GetBanners();
                break;

            case "nowtime":
                this.Synchronization();
                break;

            case "vdtailuserpwd":    //修改密码  根据账号和资金密码验证
                int uid = -1;
                if (GetVdtailuserpwd(ref uid))
                {
                    AppGlobal.RenderResult(ApiCode.Success);
                }
                break;

            case "updatepwd":
                UpdateUserPwd();    //修改密码
                break;

            case "verification":    //验证域名
                Verification();
                break;

            case "getdns":    //获取所有有效的域名
                GetDns();
                break;

            case "topnews":
                break;
            }
        }
        private void GetSettings()
        {
            var source = Ytg.Service.Logic.SysSettingHelper.GetAllSysSetting();

            AppGlobal.RenderResult <List <SysSetting> >(ApiCode.Success, source);
        }
        /// <summary>
        /// 获取热门彩种
        /// </summary>
        public void GetHotLottery()
        {
            var source = this.mHotLotteryService.GetHotLottery();

            AppGlobal.RenderResult <IList <HotLottery> >(ApiCode.Success, source);
        }
        public void GetNews()
        {
            var source = this.mNewsService.GetAll().Where(item => item.IsDelete == false).OrderByDescending(item => item.OccDate).ToList();

            AppGlobal.RenderResult <List <SysNews> >(ApiCode.Success, source);
        }
        /// <summary>
        /// 获取弹出新闻内容
        /// </summary>
        public void GetAlertNews()
        {
            var source = this.mNewsService.GetAll().Where(item => item.IsDelete == false && item.IsShow == 1).FirstOrDefault();

            AppGlobal.RenderResult <SysNews>(ApiCode.Success, source);
        }
        //玩家登陆
        private void Login(bool isfig = true)
        {
            var isLock = this.mLockIpInfoService.IsLockIp(Utils.GetIp());

            if (isLock)
            {
                //获取跳转地址
                AppGlobal.RenderResult(ApiCode.DisabledIp, this.GetRefDns());
                return;
            }

            //登陆名
            string loginCode = Request.Params["M_LOGINCODE"];
            //登陆密码
            string pwd = Request.Params["M_LOGINPWD"];
            //验证码
            string code = Request.Params["M_LOGINVIDACODE"];

            if (string.IsNullOrEmpty(loginCode) || string.IsNullOrEmpty(pwd))
            {
                AppGlobal.RenderResult(ApiCode.ParamEmpty);
                return;
            }
            if (string.IsNullOrEmpty(code) && isfig)
            {
                AppGlobal.RenderResult(ApiCode.ParamEmpty);
                return;
            }


            var item = this.mSysUserService.Get(loginCode, pwd);

            if (null == item)
            {
                AppGlobal.RenderResult(ApiCode.ValidationFails);
                return;
            }
            if (item.IsDelete)
            {
                AppGlobal.RenderResult(ApiCode.DisabledCode, this.GetRefDns());
                return;
            }


            string       sessionid = Guid.NewGuid().ToString();
            CookUserInfo info      = new CookUserInfo();

            info.Id         = item.Id;
            info.Code       = item.Code;
            info.NikeName   = item.NikeName;
            info.Sex        = sessionid;
            info.Head       = item.Head;
            info.Rebate     = item.Rebate;
            info.UserType   = item.UserType;
            info.IsRecharge = item.IsRecharge;
            info.PlayType   = item.PlayType;
            info.ProxyLevel = item.ProxyLevel;

            FormsPrincipal <CookUserInfo> .SignIn(loginCode, info, FormsAuthentication.Timeout.Minutes);

            //Ytg.ServerWeb.BootStrapper.SessionManager.AddOrUpdateSession(item.Id,new YtgSession()
            //{
            //    UserId = item.Id,
            //    SessionId = sessionid,
            //    OccDate = DateTime.Now,
            //    Code = item.Code
            //});


            string loginIpAddress = Ytg.Comm.Utils.GetIp();
            int    state          = this.mSysUserSessionService.UpdateInsertUserSession(new UserSession()
            {
                UserId      = item.Id,
                SessionId   = sessionid,
                LoginIp     = loginIpAddress,
                LoginClient = Ytg.Comm.Utils.GetLoginClientType(),
            });
            string loginCityName = "";//Utils.GetCityByIp(item.LastLoginIp);//获取所在城市
            string useSource     = System.Web.HttpContext.Current.Request.Params["usesource"];
            //判断是否为移动设备访问
            bool isMobile = Utils.IsMobile();

            if (isMobile)
            {
                useSource = "移动设备";
            }

            /**记录日志*/
            SysLog log = new SysLog()
            {
                Descript      = loginCityName,
                Ip            = loginIpAddress,
                OccDate       = DateTime.Now,
                ReferenceCode = info.Code,
                ServerSystem  = Ytg.Comm.Utils.GetUserSystem(),
                Type          = 0,
                UserId        = info.Id,
                UseSource     = useSource
            };

            /**记录日志 end*/

            //修改用户登录时间
            item.LastLoginTime = DateTime.Now;
            item.LastLoginIp   = loginIpAddress;
            item.IsLogin       = true;
            item.IsLineLogin   = true;
            item.LastCityName  = log.Descript;
            item.ServerSystem  = log.ServerSystem;
            item.UseSource     = log.UseSource;
            item.LoginCount++;//登录次数增加
            this.mSysUserService.Save();
            //单点登录
            // DanDianLogin(info.Id.ToString());

            //输出结果
            AppGlobal.RenderResult <CookUserInfo>(ApiCode.Success, info);
            //添加登录日志
            Ytg.Service.Logic.LogHelper.AddLog(log);
        }
        /// <summary>
        /// 自动注册
        /// </summary>
        private void AutoRegist()
        {
            //验证当前IP是否锁定
            var isLock = this.mLockIpInfoService.IsLockIp(Utils.GetIp());

            if (isLock)
            {
                //获取跳转地址
                AppGlobal.RenderResult(ApiCode.DisabledIp, this.GetRefDns());
                return;
            }
            //登陆名
            string account = Request.Params["Code"];

            account = account.Replace(" ", "");
            if (account.Length < 6)
            {
                AppGlobal.RenderResult(ApiCode.ParamEmpty);
                return;
            }

            string nickName = Request.Params["NickName"];
            //验证码
            string vcode = Request.Params["VdaCode"];
            int    mloginUserId;
            bool   isreg = int.TryParse(this.Request.Params["params"], out mloginUserId);

            if (!isreg)
            {
                AppGlobal.RenderResult(ApiCode.Fail);
                return;
            }
            var isCode = System.Web.HttpContext.Current.Session["ValidateCode"] == null || System.Web.HttpContext.Current.Session["ValidateCode"].ToString().ToLower() != vcode.ToLower();

            if (isCode || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(vcode))
            {
                AppGlobal.RenderResult(ApiCode.ParamEmpty);
                return;
            }
            string qq = Request.Params["qq"];

            if (string.IsNullOrEmpty(qq))
            {
                qq = "";
            }
            string phone = Request.Params["phone"];

            if (string.IsNullOrEmpty(phone))
            {
                phone = "";
            }

            var parentItem = this.mSysUserService.Get(mloginUserId);

            if (null == parentItem || parentItem.UserType == UserType.General || parentItem.UserType == UserType.Manager)
            {
                AppGlobal.RenderResult(ApiCode.Fail);//非法请求,无法继续
                return;
            }

            //验证账号是否存在
            var item = this.mSysUserService.Get(account);

            if (null != item)
            {
                AppGlobal.RenderResult(ApiCode.ValidationFails);//非法请求,无法继续
                return;
            }
            string psw = Request.Params["lgpwd"];

            if (string.IsNullOrEmpty(psw))
            {
                psw = DefaultPwd;
            }
            //注册
            var outuser = new SysUser()
            {
                Code       = account,
                ParentId   = parentItem.Id,
                Sex        = string.IsNullOrEmpty(parentItem.Sex)?"0":"1",
                NikeName   = nickName,
                Password   = psw,
                PlayType   = parentItem.PlayType,
                Rebate     = (parentItem.Rebate + parentItem.AutoRegistRebate),
                UserType   = UserType.General,
                ProxyLevel = parentItem.ProxyLevel + 1,
                Qq         = qq,
                MoTel      = phone,
                Head       = parentItem.Head
            };

            if (outuser.Rebate < 0)
            {
                outuser.Rebate = parentItem.Rebate;
            }
            this.mSysUserService.Create(outuser);
            this.mSysUserService.Save();
            UserComm.InintNewUserBalance(outuser, this.mSysSettingService, this.mSysUserBalanceService, this.mSysUserBalanceDetailService, this.mSysUserService);//初始化新用户金额
            //初始化配额
            this.mSysQuotaService.InintUserQuota(outuser.Id, outuser.ParentId, Math.Round(Ytg.Comm.Utils.MaxRemo - outuser.Rebate, 1));
            //初始化资金密码
            InintUserBalancePassword(outuser.Id, Request.Params["zjpwd"]);
            AppGlobal.RenderResult(ApiCode.Success);//非法请求,无法继续
        }
        /// <summary>
        /// 注销登陆
        /// </summary>
        private void Logout()
        {
            FormsPrincipal <CookUserInfo> .SignOut();

            AppGlobal.RenderResult(ApiCode.Success);
        }
Ejemplo n.º 13
0
        public static void CheckLARSDownload(Object stateInfo)
        {
            Boolean automatedTaskStarted = false;

            try
            {
                if (String.IsNullOrEmpty(Constants.ConfigSettings.LARSImportTime))
                {
                    // Log Warning about LARSImportTime not being set
                    AppGlobal.Log.WriteError(AppGlobal.Language.GetText("Automation_LARSImport_LARSImportTimeNotConfigured", "Error Importing LARS File.  LARSImportTime Not Configured", false, languageId));
                    return;
                }

                LARSFolder = Constants.ConfigSettings.LARSUploadVirtualDirectoryName;
                if (LARSFolder.EndsWith(@"\"))
                {
                    LARSFolder = LARSFolder.Substring(0, LARSFolder.Length - 1);
                }

                // Check if config setting is valid
                if (String.IsNullOrEmpty(LARSFolder) || !Directory.Exists(LARSFolder))
                {
                    AppGlobal.Log.WriteError(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_LARSFolderNotConfigured", "Error Importing LARS File.  LARSFolderNotConfigured Not Configured Correctly: {0}", false, languageId), LARSFolder));
                    return;
                }

                if (String.IsNullOrEmpty(Constants.ConfigSettings.LARSImportUserId))
                {
                    // Log Warning about LARSImportUserId not being set
                    AppGlobal.Log.WriteError(AppGlobal.Language.GetText("Automation_LARSImport_UserIdNotConfigured", "Error Importing LARS File.  LARSImportUserId Not Configured", false, languageId));
                    return;
                }

                AspNetUser aspNetUser = new ProviderPortalEntities().AspNetUsers.Find(Constants.ConfigSettings["LARSImportUserId"].ToString());
                if (aspNetUser == null)
                {
                    // Log Error
                    AppGlobal.Log.WriteError(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_UserIdNotFound", "Error Importing LARS File.  Cannot find user Id {0}", false, languageId), Constants.ConfigSettings["LARSImportUserId"]));
                    return;
                }

                if (DateTime.Now.ToString("HH:mm") == Constants.ConfigSettings.LARSImportTime)
                {
                    // Ensure that another server hasn't picked this up
                    if (!CanRunAutomatedTask(AutomatedTaskName.LARSImport))
                    {
                        AppGlobal.Log.WriteLog(AppGlobal.Language.GetText("Automation_LARSImport_Running", "Automated LARS import running on a different server", false, languageId));
                        return;
                    }

                    automatedTaskStarted = true;

                    DateTime date       = DateTime.Today;
                    DateTime lastImport = DateTime.MinValue.Date;

                    MetadataUpload mtu = new ProviderPortalEntities().MetadataUploads.Where(x => x.MetadataUploadTypeId == (Int32)Constants.MetadataUploadType.LearningAim).OrderByDescending(x => x.CreatedDateTimeUtc).FirstOrDefault();
                    if (mtu != null)
                    {
                        lastImport = mtu.CreatedDateTimeUtc.Date;
                    }

                    Boolean fileFound = false;
                    String  fileName  = String.Empty;
                    while (date > lastImport)
                    {
                        fileName = Constants.ConfigSettings.LARSUrlAndFileName.Replace("{date}", date.ToString("yyyyMMdd")).Replace("{year}", GetLastYear());
                        if (DoesFileExistAtUrl(fileName))
                        {
                            fileFound = true;
                            break;
                        }
                        fileName = Constants.ConfigSettings.LARSUrlAndFileName.Replace("{date}", date.ToString("yyyyMMdd")).Replace("{year}", GetThisYear());
                        if (DoesFileExistAtUrl(fileName))
                        {
                            fileFound = true;
                            break;
                        }

                        date = date.AddDays(-1);
                    }

                    if (fileFound)
                    {
                        AppGlobal.Log.WriteLog(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_FileFound", "Found LARS File {0}.  Importing...", false, languageId), fileName));

                        // Download the file
                        using (WebClient webClient = new WebClient())
                        {
                            LARSFilename = LARSFolder + @"\" + GetFileName(fileName);
                            webClient.DownloadFileCompleted += webClient_LARSDownloadFileCompleted;
                            webClient.DownloadFileAsync(new Uri(fileName), LARSFilename);
                        }
                    }
                    else
                    {
                        CompleteAutomatedTask(AutomatedTaskName.LARSImport);

                        AppGlobal.Log.WriteLog(AppGlobal.Language.GetText("Automation_LARSImport_NoFileFound", "No Updated LARS File Found", false, languageId));
                        AppGlobal.Log.WriteLog(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_NoOfDaysSinceLastImport", "{0} day(s) since last LARS import.", false, languageId), (DateTime.Now - lastImport).Days));

                        // Check if we need to send an email
                        Int32 daysBeforeSendingEmail = Constants.ConfigSettings.LARSDaysSinceLastImportBeforeSendingEmail;
                        if (daysBeforeSendingEmail > 0)
                        {
                            TimeSpan ts = TimeSpan.FromDays(daysBeforeSendingEmail);
                            if (DateTime.Today - lastImport >= ts)
                            {
                                // Send email once per week
                                if ((DateTime.Today - lastImport).Subtract(ts).Days % 7 == 0)
                                {
                                    AppGlobal.Log.WriteLog(AppGlobal.Language.GetText("Automation_LARSImport_SendingWarningEmail", "LARS Importer: Sending warning email.", false, languageId));

                                    if (String.IsNullOrWhiteSpace(Constants.ConfigSettings.LARSLongTimeSinceImportEmailAddress))
                                    {
                                        AppGlobal.Log.WriteLog(AppGlobal.Language.GetText("Automation_LARSImport_LARSLongTimeSinceImportEmailAddressNotConfigured", "LARSLongTimeSinceImportEmailAddress Not Configured", false, languageId));
                                    }
                                    else if (!AppGlobal.IsValidEmail(Constants.ConfigSettings.LARSLongTimeSinceImportEmailAddress))
                                    {
                                        AppGlobal.Log.WriteError(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_LARSLongTimeSinceImportEmailAddressInvalid", "LARSLongTimeSinceImportEmailAddress is Invalid: {0}", false, languageId), Constants.ConfigSettings.LARSLongTimeSinceImportEmailAddress));
                                    }
                                    else
                                    {
                                        // Send email(s)
                                        foreach (String address in Constants.ConfigSettings.LARSLongTimeSinceImportEmailAddress.Split(';'))
                                        {
                                            //AppGlobal.EmailQueue.AddToSendQueue(
                                            //    TemplatedEmail.EmailMessage(
                                            //        new MailAddress(address),
                                            //        null,
                                            //        new MailAddress(Constants.ConfigSettings.AutomatedFromEmailAddress, Constants.ConfigSettings.AutomatedFromEmailName),
                                            //        Constants.EmailTemplates.LARSFileNotImportSinceXDaysAgo,
                                            //        new List<EmailParameter>
                                            //        {
                                            //            new EmailParameter("%LASTIMPORT%", lastImport.ToString("dd MMM yyyy")),
                                            //            new EmailParameter("%NUMBEROFDAYSSINCELASTIMPORT%", (DateTime.Today - lastImport).Days.ToString("N0")),
                                            //            new EmailParameter("%CONFIGUREDNUMBEROFDAYS%", daysBeforeSendingEmail.ToString("N0"))
                                            //        },
                                            //        AppGlobal.Language.GetText("TemplatedEmail_EmailOverride_FormatString", "<p>This email was originally sent to {0}:<p>{1}", false, languageId)));

                                            var emailMessage = TemplatedEmail.EmailMessage(
                                                new MailAddress(address),
                                                null,
                                                new MailAddress(Constants.ConfigSettings.AutomatedFromEmailAddress, Constants.ConfigSettings.AutomatedFromEmailName),
                                                Constants.EmailTemplates.LARSFileNotImportSinceXDaysAgo,
                                                new List <EmailParameter>
                                            {
                                                new EmailParameter("%LASTIMPORT%", lastImport.ToString("dd MMM yyyy")),
                                                new EmailParameter("%NUMBEROFDAYSSINCELASTIMPORT%", (DateTime.Today - lastImport).Days.ToString("N0")),
                                                new EmailParameter("%CONFIGUREDNUMBEROFDAYS%", daysBeforeSendingEmail.ToString("N0"))
                                            },
                                                AppGlobal.Language.GetText("TemplatedEmail_EmailOverride_FormatString", "<p>This email was originally sent to {0}:<p>{1}", false, languageId));

                                            var response = SfaSendGridClient.SendGridEmailMessage(emailMessage, null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (automatedTaskStarted)
                {
                    CompleteAutomatedTask(AutomatedTaskName.LARSImport);
                }
                AppGlobal.Log.WriteError(String.Format(AppGlobal.Language.GetText("Automation_LARSImport_GenericError", "Automated LARS Importer Failed With Error: {0}", false, languageId), ex.Message));
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Retrieves a list of all ProductCodes that are currently known (i.e., available).
 /// </summary>
 public static List <string> GetAllProductCodeNames()
 {
     return(AppGlobal.GetFileNamesWithoutExtension(AppGlobal.AppDataDirectory, string.Format("*.{0}", Product.ProdXMLExtension)));
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Retrieves a list of all VersionCodes that this Product has.
 /// </summary>
 /// <returns>List of VersionCodes for the Version.</returns>
 public List <string> GetAllVersionCodes()
 {
     return(AppGlobal.GetFileNamesWithoutExtension(VersionsDirPath, string.Format("*.{0}", Version.VerXMLExtension)));
 }
Ejemplo n.º 16
0
        public JsonResult OnPost()
        {
            login_db           _context = new login_db(AppGlobal.get_db_option());
            AppResponseMessage arm      = new AppResponseMessage();

            try {
                using (var transaction = _context.Database.BeginTransaction()) {
                    if (Request.Query["f"] == "register_handler")
                    {
                        string full_name         = Request.Form["full_name"];
                        string email             = Request.Form["email"];
                        string password          = Request.Form["password"];
                        int    full_name_existed = _context.m_user.Where(e => e.full_name == full_name).Count();
                        int    email_existed     = _context.m_user.Where(e => e.email == email).Count();
                        int    count_existed     = full_name_existed + email_existed;
                        if (count_existed > 0)
                        {
                            arm.fail();
                            arm.message = "Data Already Exist!!";
                        }
                        else
                        {
                            m_user m_user_data = new m_user {
                                full_name = full_name,
                                email     = email,
                                password  = password
                            };
                            _context.m_user.Add(m_user_data);
                            _context.SaveChanges();

                            t_login_history login_history = new t_login_history {
                                m_user_id  = m_user_data.m_user_id,
                                login_time = DateTime.Now
                            };

                            _context.t_login_history.Add(login_history);
                            _context.SaveChanges();

                            //jika user valid & aktif
                            var claims = new[] {
                                new Claim(ClaimTypes.Email, email),

                                new Claim("m_user_id", m_user_data.m_user_id.ToString()),
                                new Claim("full_name", m_user_data.full_name),
                                new Claim("history_id", login_history.t_login_history_id.ToString()),
                            };
                            ClaimsIdentity  identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                            AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal);

                            arm.success();
                            arm.message = "Success";
                        }
                    }
                    transaction.Commit();
                    _context.SaveChanges();
                }
            } catch (Exception ex) {
                arm.fail();
                arm.message = ex.Message;
            }
            return(new JsonResult(arm)); //return ARM dg method JsonResult untuk auto serialize ke format JSON
        }