コード例 #1
0
ファイル: MyAjaxHelper.cs プロジェクト: jesusblessf6/Maike
 public static ActionResult RedirectAjax(AjaxStatusCode status, string msg, object data, string backurl)
 {
     var ajax = new AjaxMsgModel
     {
         Status = status,
         Msg = msg,
         Data = data,
         BackUrl = backurl
     };
     var res = new JsonResult { Data = ajax, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
     return res;
 }
コード例 #2
0
        public ActionResult UserList()
        {
            AjaxMsgModel ajaxMsg = new AjaxMsgModel()
            {
                Statu = "error", Msg = "登录失败!"
            };
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize  = Request["rows"] == null ? 20 : int.Parse(Request["rows"]);
            int total     = 0;
            var rows      = _userviewBLL.LoadPageEntities(pageIndex, pageSize, out total, u => u.IsDel == false, true, u => u.ID);

            //var result = new { total = total, rows = data };
            return(Json(new GridDataHelper <User_Role_DeptView>(rows, total), JsonRequestBehavior.AllowGet));
        }
コード例 #3
0
        public ActionResult DeptList()
        {
            AjaxMsgModel ajaxMsg = new AjaxMsgModel()
            {
                Statu = "err", Msg = "加载失败!"
            };
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize  = Request["rows"] == null ? 20 : int.Parse(Request["rows"]);
            int total     = 0;
            var rows      = _deptBLL.LoadPageEntities(pageIndex, pageSize, out total, u => u.Id > 0, true, u => u.Id);

            //var result = new { total = total, rows = data };
            return(Json(new GridDataHelper <Department>(rows, total), JsonRequestBehavior.AllowGet));
        }
コード例 #4
0
        public ActionResult UserLoginOut()
        {
            AjaxMsgModel ajaxM = new AjaxMsgModel()
            {
                Statu = "err", Msg = "退出录败!"
            };

            //清空cookie
            //CookiesHelper.AddCookie("cookieId", DateTime.Now.AddDays(-1));
            Session.Clear();
            ajaxM.Statu   = "ok";
            ajaxM.Msg     = "退出成功!";
            ajaxM.BackUrl = "/Login/Login";
            return(Json(ajaxM));
        }
コード例 #5
0
        public ActionResult Add()
        {
            AjaxMsgModel ajaxMsg = new AjaxMsgModel()
            {
                Statu = "error", Msg = "新增失败!"
            };
            User sessionUser = Session["ainfo"] as User;

            User   userModel   = new User();
            string accountName = Request["AccountName"];
            string nickName    = Request["RealName"];
            string mobile      = Request["MobilePhone"];
            string email       = Request["Email"];
            string isable      = Request["IsAble"];
            string id          = Request["hideId"];

            userModel.AccountName = accountName;
            userModel.RealName    = nickName;
            userModel.MobilePhone = mobile;
            userModel.Email       = email;
            userModel.IsAble      = isable == "1" ? true : false;
            userModel.IfChangePwd = false;
            userModel.CreateTime  = DateTime.Now;
            userModel.CreateBy    = sessionUser.AccountName;

            userModel.IsDel = false;
            bool flag = false;

            if (id != "" && id != "0")
            {
                userModel.ID         = int.Parse(id);
                userModel.UpdateBy   = sessionUser.AccountName;
                userModel.UpdateTime = DateTime.Now;
                flag = _userBLL.UpdateEntity(userModel);
            }
            else
            {
                flag = _userBLL.AddEntity(userModel) > 0;
            }
            if (flag)
            {
                ajaxMsg.Statu = "ok";
                ajaxMsg.Msg   = "提交成功!";
            }
            //var json = Newtonsoft.Json.JsonConvert.SerializeObject(ajaxMsg);
            return(Json(ajaxMsg, JsonRequestBehavior.AllowGet));
        }
コード例 #6
0
ファイル: UploadFile.cs プロジェクト: wpmyj/six
        public AjaxMsgModel ToUpLoadDoc(HttpFileCollectionBase files, AjaxMsgModel amm, string pathstr, string upfilename)
        {
            //得到上传的文件
            HttpPostedFileBase upfile = null;

            foreach (string file in files)
            {
                HttpPostedFileBase uploadFile = files[file] as HttpPostedFileBase;
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    upfile = uploadFile;
                }
            }
            string fileAble = Path.GetExtension(upfile.FileName).ToLower();//文件后缀

            if (upfile == null || (fileAble != ".doc" && fileAble != ".docx" && fileAble != ".xls" && fileAble != ".xlsx"))
            {
                return(amm);
            }
            //获取文件大小
            long contentLength = upfile.ContentLength;

            //文件不能大于10M
            if (contentLength > 1024 * 102400)
            {
                amm.Msg = "上传文件不能大于100M";
                return(amm);
            }
            //要保存的文件路径
            //HttpRuntime.AppDomainAppPath 网站在服务器磁盘上的物理路径
            //任何于Request/HttpContext.Current等相关的方法, 都只能在有请求上下文或者页面时使用. 即在无请求上下文时,HttpContext.Current为null. 而HttpRuntime.AppDomainAppPath方法一直可用.
            string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Content", pathstr);

            FileHelper.CreateDirectory(path);
            //string path = Path.Combine(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath), "Content", "UpLoadImg");
            //要保存的文件名称
            string fileName = string.Format("{0}{1}", upfilename, fileAble);

            //保存文件到指定的目录
            upfile.SaveAs(Path.Combine(path, fileName));

            //返回path
            amm      = DocToSwf(amm, path, fileName);
            amm.Data = upfile.FileName;
            return(amm);
        }
コード例 #7
0
        public ActionResult Add()
        {
            AjaxMsgModel ajaxMsg = new AjaxMsgModel()
            {
                Statu = "error", Msg = "新增失败!"
            };
            User   sessionUser = Session["ainfo"] as User;
            Menu   menuModel   = new Menu();
            string menuName    = Request["MenuName"];
            string linkurl     = Request["LinkAddress"];
            string Code        = Request["Code"];
            string icon        = Request["Icon"];
            string sort        = Request["Sort"];
            string ParentId    = Request["ParentId"];
            string id          = Request["hideId"];

            menuModel.Name        = menuName;
            menuModel.Code        = Code;
            menuModel.Icon        = icon;
            menuModel.ParentId    = string.IsNullOrEmpty(ParentId) == true?0:int.Parse(ParentId);
            menuModel.Sort        = int.Parse(sort);
            menuModel.LinkAddress = linkurl;
            menuModel.CreateTime  = DateTime.Now;
            menuModel.CreateBy    = sessionUser.AccountName;

            bool flag = false;

            if (id != "" && id != "0")
            {
                menuModel.Id         = int.Parse(id);
                menuModel.UpdateBy   = sessionUser.AccountName;
                menuModel.UpdateTime = DateTime.Now;
                flag = _menuBLL.UpdateEntity(menuModel);
            }
            else
            {
                flag = _menuBLL.AddEntity(menuModel) > 0;
            }
            if (flag)
            {
                ajaxMsg.Statu = "ok";
                ajaxMsg.Msg   = "提交成功!";
            }
            //var json = Newtonsoft.Json.JsonConvert.SerializeObject(ajaxMsg);
            return(Json(ajaxMsg, JsonRequestBehavior.AllowGet));
        }
コード例 #8
0
ファイル: HomeController.cs プロジェクト: wpmyj/six
        public JsonResult LoginIn(string id)
        {
            string ip = Request.ServerVariables["REMOTE_ADDR"].ToString();

            if (Request.Form["username"] == null || Request.Form["password"] == null || Request.Form["checkcode"] == null)
            {
                return(PackagingAjaxmsg(AjaxStatu.err, string.Format(Message.ParGetFail, "登录名|密码|验证码")));
            }
            string username  = Request["username"].ToString();
            string password  = Request["password"].ToString();
            string checkcode = Request["checkcode"].ToString();

            AjaxMsgModel amm = Model_SYS_USER.LoginIn(username, password, checkcode, id);

            Model_SYS_USER.GenerateValidateCode();    //北京后台刷新验证码
            return(PackagingAjaxmsg(amm));
        }
コード例 #9
0
ファイル: BaseController.cs プロジェクト: wpmyj/six
        /// <summary>
        /// 把ajax返回值封装成json格式返回
        /// </summary>
        /// <param name="statu">Ajax 状态</param>
        /// <param name="msg">Ajax 信息</param>
        /// <param name="data">Ajax 数据</param>
        /// <param name="backurl">调用后的链接</param>
        /// <returns>json格式的Ajax数据</returns>
        public JsonResult PackagingAjaxmsg(AjaxStatu statu, string msg
                                           , object data = null, string backurl = "")
        {
            AjaxMsgModel amm = new AjaxMsgModel
            {
                BackUrl = backurl,
                Data    = data,
                Msg     = msg,
                Statu   = statu
            };

            JsonResult ajaxRes = new JsonResult();

            ajaxRes.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            ajaxRes.Data = amm;
            return(ajaxRes);
        }
コード例 #10
0
ファイル: UploadFile.cs プロジェクト: wpmyj/six
        public AjaxMsgModel DocToSwf(AjaxMsgModel amm, string filePath, string fileName)
        {
            string swfFile     = "error";
            string swfToolPath = HttpRuntime.AppDomainAppPath + "\\Content\\Rule\\swftools\\pdf2swf.exe";
            string hzName      = Path.GetExtension(fileName);

            string docFilePath = filePath + "\\" + fileName;
            string pdfFilePath = filePath.Replace("\\Doc", "\\Pdf");
            string pdfFileName = fileName.Replace(hzName, ".pdf");
            string swfFilePath = filePath.Replace("\\Doc", "\\Swf") + "\\";

            FileHelper.CreateDirectory(pdfFilePath);
            FileHelper.CreateDirectory(swfFilePath);

            if (FileHelper.IsExistFile(docFilePath))
            {
                if (hzName == ".doc" || hzName == ".docx")
                {
                    if (FileHelper.DocToPdf(docFilePath, pdfFilePath + "\\" + pdfFileName))
                    {
                        swfFile = FileHelper.PdfToSwf(swfToolPath, pdfFilePath, pdfFileName, swfFilePath);
                    }
                }
                if (hzName == ".xls" || hzName == ".xlsx")
                {
                    if (FileHelper.XlsToPdf(docFilePath, pdfFilePath + "\\" + pdfFileName, 4))
                    {
                        swfFile = FileHelper.PdfToSwf(swfToolPath, pdfFilePath, pdfFileName, swfFilePath);
                    }
                }
            }

            if (swfFile != "error")
            {
                amm.Statu = AjaxStatu.ok;
                amm.Msg   = "上传成功";
            }
            else
            {
                amm.Statu = AjaxStatu.err;
                amm.Msg   = "上传失败";
            }
            return(amm);
        }
コード例 #11
0
ファイル: UploadFile.cs プロジェクト: wpmyj/six
        public AjaxMsgModel ToUpLoad(HttpFileCollectionBase files, AjaxMsgModel amm, int width, int height, string pathstr = "UpLoadImg")
        {
            //得到上传的文件
            HttpPostedFileBase upfile = null;

            foreach (string file in files)
            {
                HttpPostedFileBase uploadFile = files[file] as HttpPostedFileBase;
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    upfile = uploadFile;
                }
            }
            string fileAble = Path.GetExtension(upfile.FileName).ToLower();//文件后缀

            if (upfile == null || (fileAble != ".jpg" && fileAble != ".jpeg" && fileAble != ".png" && fileAble != "bmp"))
            {
                return(amm);
            }
            //获取文件大小
            long contentLength = upfile.ContentLength;

            //文件不能大于10M
            if (contentLength > 1024 * 10240)
            {
                amm.Msg = "上传文件不能大于10M";
                return(amm);
            }
            //要保存的文件路径
            //HttpRuntime.AppDomainAppPath 网站在服务器磁盘上的物理路径
            //任何于Request/HttpContext.Current等相关的方法, 都只能在有请求上下文或者页面时使用. 即在无请求上下文时,HttpContext.Current为null. 而HttpRuntime.AppDomainAppPath方法一直可用.
            string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Content", pathstr);
            //string path = Path.Combine(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath), "Content", "UpLoadImg");
            //要保存的文件名称
            string fileName = string.Format("{0}_{1}{2}", "Y", DateTime.Now.ToString("yyyyMMddHHmmssffff"), Path.GetExtension(upfile.FileName));

            //保存文件到指定的目录
            upfile.SaveAs(Path.Combine(path, fileName));

            //返回path
            amm      = GetSmallImg(amm, path, fileName, width, height);
            amm.Data = "/Content/" + pathstr + "/" + fileName;
            return(amm);
        }
コード例 #12
0
        public ActionResult Add()
        {
            AjaxMsgModel ajaxMsg = new AjaxMsgModel()
            {
                Statu = "error", Msg = "新增失败!"
            };
            User   sessionUser = Session["ainfo"] as User;
            Role   roleModel   = new Role();
            string RoleName    = Request["RoleName"];
            string Description = Request["Description"];
            string isable      = Request["IsAble"];
            string id          = Request["hideId"];

            roleModel.RoleName    = RoleName;
            roleModel.Description = Description;

            roleModel.IsAble     = isable == "1" ? true : false;
            roleModel.CreateTime = DateTime.Now;
            roleModel.CreateBy   = sessionUser.AccountName;

            bool flag = false;

            if (id != "" && id != "0")
            {
                roleModel.Id         = int.Parse(id);
                roleModel.UpdateBy   = sessionUser.AccountName;
                roleModel.UpdateTime = DateTime.Now;
                flag = _roleBLL.UpdateEntity(roleModel);
            }
            else
            {
                flag = _roleBLL.AddEntity(roleModel) > 0;
            }
            if (flag)
            {
                ajaxMsg.Statu = "ok";
                ajaxMsg.Msg   = "提交成功!";
            }
            //var json = Newtonsoft.Json.JsonConvert.SerializeObject(ajaxMsg);
            return(Json(ajaxMsg, JsonRequestBehavior.AllowGet));
        }
コード例 #13
0
ファイル: WebApiLoginHandler.cs プロジェクト: wpmyj/six
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            int matchHeaderCount = request.Headers.Count((item) =>
            {
                if ("keyword".Equals(item.Key))
                {
                    foreach (var str in item.Value)
                    {
                        if ("SxSh".Equals(str))
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            });

            if (matchHeaderCount > 0)
            {
                return(base.SendAsync(request, cancellationToken));
            }
            else
            {
                if (!Model_SYS_USER.IsLogin())
                {
                    AjaxMsgModel amm = new AjaxMsgModel
                    {
                        BackUrl = "/Home/Login?msg=noLogin",
                        Data    = null,
                        Msg     = Message.NotLogin,
                        Statu   = AjaxStatu.nologin
                    };
                    var response = request.CreateResponse(System.Net.HttpStatusCode.OK, amm);
                    //var response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
                    var task = new TaskCompletionSource <HttpResponseMessage>();
                    task.SetResult(response);
                    return(task.Task);
                }
                return(base.SendAsync(request, cancellationToken));
            }
        }
コード例 #14
0
        public JsonResult EditPass()
        {
            if (Request.Form["txtoldpass"] == null || Request.Form["txtnewpass"] == null || Request.Form["txtrepass"] == null)
            {
                return(PackagingAjaxmsg(AjaxStatu.err, string.Format(Message.ParGetFail, "密码")));
            }
            string txtoldpass = Request["txtoldpass"].ToString();
            string txtnewpass = Request["txtnewpass"].ToString();
            string txtrepass  = Request["txtrepass"].ToString();

            if (txtnewpass != txtrepass)
            {
                return(PackagingAjaxmsg(AjaxStatu.err, string.Format(Message.MisMatch, "新密码")));
            }
            SYS_USER user = new SYS_USER
            {
                USER_NAME = oc.CurrentUser.USER_NAME,
                PASSWORD  = txtnewpass
            };
            AjaxMsgModel amm = Model_SYS_USER.EditUserPwd(user, txtoldpass);

            return(PackagingAjaxmsg(amm));
        }
コード例 #15
0
        /// <summary>
        /// 根据数据层的操作  来返回不同的json数据
        /// </summary>
        /// <param name="result">数据库返回的数据 受影响行数或者被插入数据的id</param>
        /// <param name="modelCount">待处理的数据条数</param>
        /// <param name="msg">弹框显示信息</param>
        /// <param name="opraterType">0 insert 1 update 2 delete 3 后台模型校验不通过 ,4 登录超时</param>
        /// <param name="data">后台josn 数据返回</param>
        ///  <param name="backUrl">前台处理完成后跳转页面</param>
        /// <returns></returns>
        public static JsonResult CreatJavaScriptResult(int result, int modelCount, string msg, int opraterType, string data, string backUrl)
        {
            AjaxMsgModel ajax = new AjaxMsgModel()
            {
                Statu   = CommonHelp.EnumHelper.Results.失败.ToString(),
                Msg     = "系统错误",
                Data    = data,
                BackUrl = backUrl
            };

            if (opraterType == 0)
            {
                if (result > modelCount)
                {
                    ajax = new AjaxMsgModel()
                    {
                        Statu   = CommonHelp.EnumHelper.Results.成功.ToString(),
                        Msg     = msg,
                        Data    = data,
                        BackUrl = backUrl
                    };
                }
            }
            else if (opraterType == 3)
            {
                ajax = new AjaxMsgModel()
                {
                    Statu   = "noValid",
                    Msg     = msg,
                    Data    = data,
                    BackUrl = backUrl
                };
            }
            else if (opraterType == 4)
            {
                ajax = new AjaxMsgModel()
                {
                    Statu   = "nologin",
                    Msg     = msg,
                    Data    = data,
                    BackUrl = backUrl
                };
            }
            else
            {
                if (result == modelCount)
                {
                    ajax = new AjaxMsgModel()
                    {
                        Statu   = CommonHelp.EnumHelper.Results.成功.ToString(),
                        Msg     = msg,
                        Data    = data,
                        BackUrl = backUrl
                    };
                }
            }
            JsonResult res = new JsonResult();

            res.Data = ajax;
            // res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return(res);
        }
コード例 #16
0
        /// <summary>
        /// 工作薄
        /// </summary>
        //public HSSFWorkbook WorkBook { get; set; }
        ///// <summary>
        ///// 表
        ///// </summary>
        //public ISheet Sheet { get; set; }
        ///// <summary>
        ///// 路径
        ///// </summary>
        //public string ExcelPath { get; set; }
        //public ExcelHelper(string filePath)
        //{
        //    //把xls文件中的数据写入wk中
        //    using (FileStream fs = File.OpenRead(filePath))
        //    {
        //        WorkBook = new HSSFWorkbook(fs);
        //        Sheet = WorkBook.GetSheetAt(0);
        //        ExcelPath = filePath;
        //    }
        //}
        //public ExcelHelper(string path, string fileName)
        //{
        //    //把xls文件中的数据写入wk中
        //    using (FileStream fs = File.OpenRead(path + "/" + fileName + ".xls"))
        //    {
        //        WorkBook = new HSSFWorkbook(fs);
        //        Sheet = WorkBook.GetSheetAt(0);
        //        ExcelPath = path + "/" + fileName + ".xls";
        //    }
        //}
        //public ExcelHelper(string path, string fileName, string sheetName)
        //{
        //    using (FileStream fs = File.OpenRead(path + "/" + fileName + ".xls"))
        //    {
        //        WorkBook = new HSSFWorkbook(fs);
        //        Sheet = WorkBook.GetSheet(sheetName);
        //        ExcelPath = path + "/" + fileName + ".xls";
        //    }
        //}
        #endregion

        /// <summary>
        /// excel读取返回DataTable,开始列必须是第一列
        /// </summary>
        /// <param name="files">上传的文件</param>
        /// <param name="sheetIndex">要读取的工作表索引</param>
        /// <param name="rowIndex">开始行数</param>
        /// <param name="isHead">开始行是否是DataTable的列名</param>
        /// <returns></returns>
        public AjaxMsgModel ToDataTable(HttpFileCollection files, int sheetIndex, int rowIndex, AjaxMsgModel amm)
        {
            //得到上传的文件
            HttpPostedFile upfile = null;

            foreach (string file in files)
            {
                HttpPostedFile uploadFile = files[file] as HttpPostedFile;
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    upfile = uploadFile;
                }
            }
            string fileAble = Path.GetExtension(upfile.FileName);//文件后缀

            if (upfile == null || (fileAble != ".xls" && fileAble != ".xlsx"))
            {
                return(amm);
            }
            //要保存的文件路径
            //HttpRuntime.AppDomainAppPath 网站在服务器磁盘上的物理路径
            //任何于Request/HttpContext.Current等相关的方法, 都只能在有请求上下文或者页面时使用. 即在无请求上下文时,HttpContext.Current为null. 而HttpRuntime.AppDomainAppPath方法一直可用.
            string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Content", "UpLoadExcel");
            //string path = Path.Combine(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath), "Content", "UpLoadExcel");
            //要保存的文件名称
            string fileName = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(upfile.FileName), DateTime.Now.ToString("yyyyMMddHHmmss"), Path.GetExtension(upfile.FileName));

            //保存文件到指定的目录
            upfile.SaveAs(Path.Combine(path, fileName));

            //excel读取返回DataTable
            amm = ToDataTable(path + "\\" + fileName, sheetIndex, rowIndex, amm);

            return(amm);
        }
コード例 #17
0
        /// <summary>
        /// excel读取返回DataTable,开始列必须是第一列
        /// </summary>
        /// <param name="files">上传的文件</param>
        /// <param name="sheetIndex">要读取的工作表索引</param>
        /// <param name="rowIndex">开始行数</param>
        /// <param name="isHead">开始行是否是DataTable的列名</param>
        /// <returns></returns>
        ///

        /*
         * public AjaxMsgModel ToDataTable(HttpFileCollectionBase files, int sheetIndex, int rowIndex, AjaxMsgModel amm)
         * {
         *  //得到上传的文件
         *  HttpPostedFileBase upfile = null;
         *  foreach (string file in files)
         *  {
         *      HttpPostedFileBase uploadFile = files[file] as HttpPostedFileBase;
         *      if (uploadFile != null && uploadFile.ContentLength > 0)
         *      {
         *          upfile = uploadFile;
         *
         *      }
         *  }
         *  string fileAble = Path.GetExtension(upfile.FileName);//文件后缀
         *  if (upfile == null || (fileAble != ".xls" && fileAble != ".xlsx"))
         *  {
         *      return amm;
         *  }
         *  //要保存的文件路径
         *  //HttpRuntime.AppDomainAppPath 网站在服务器磁盘上的物理路径
         *  //任何于Request/HttpContext.Current等相关的方法, 都只能在有请求上下文或者页面时使用. 即在无请求上下文时,HttpContext.Current为null. 而HttpRuntime.AppDomainAppPath方法一直可用.
         *  string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Content", "UpLoadExcel");
         *  //string path = Path.Combine(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath), "Content", "UpLoadExcel");
         *  //要保存的文件名称
         *  string fileName = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(upfile.FileName), DateTime.Now.ToString("yyyyMMddHHmmss"), Path.GetExtension(upfile.FileName));
         *  //保存文件到指定的目录
         *  upfile.SaveAs(Path.Combine(path, fileName));
         *
         *  //excel读取返回DataTable
         *  amm = ToDataTable(path + "\\" + fileName, sheetIndex, rowIndex, amm);
         *
         *  return amm;
         * }
         */
        /// <summary>
        /// excel读取返回DataTable,开始列必须是第一列
        /// </summary>
        /// <param name="excelPath">excelPath路径</param>
        /// <param name="sheetIndex">要读取的工作表索引</param>
        /// <param name="rowIndex">开始行数</param>
        /// <param name="isHead">开始行是否是DataTable的列名</param>
        /// <returns></returns>
        public AjaxMsgModel ToDataTable(string excelPath, int sheetIndex, int rowIndex, AjaxMsgModel amm)
        {
            bool isHead = true;//第一行必须是表头

            try
            {
                DataTable dt = new DataTable(Path.GetFileNameWithoutExtension(excelPath) + "_Sheet" + sheetIndex);
                IWorkbook workbook;

                //workbook = new HSSFWorkbook(file);//创建对应文件
                try
                {
                    using (FileStream file = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new HSSFWorkbook(file);//创建对应文件EXCEL2003
                    }
                }
                catch (Exception ex)
                {
                    using (FileStream file = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new XSSFWorkbook(file);//创建对应文件EXCEL2007
                    }
                }
                if (File.Exists(excelPath))//读完即删除
                {
                    File.Delete(excelPath);
                }
                ISheet sheet = workbook.GetSheetAt(sheetIndex); //按索引获取工作表
                var    rows  = sheet.GetRowEnumerator();        //获取工作表中所有行HSSFSheet.GetRow(rowIndex)获取某一行
                for (int i = 0; i < rowIndex; i++)              //从第rowindex行开始读取
                {
                    rows.MoveNext();
                }
                IRow row = (IRow)rows.Current;
                try
                {
                    for (int i = 0; i < row.LastCellNum; i++)//给DataTable创建列
                    {
                        ICell  cell       = row.GetCell(i);
                        string columnName = isHead ? cell.ToString() : i.ToString();
                        if (columnName.Trim() == "")
                        {
                            //amm.Statu = AjaxStatu.err;
                            //amm.Msg = "表头名不能为空!";

                            //return amm;

                            columnName = "EXTNAME" + i.ToString();
                        }
                        try
                        {
                            dt.Columns.Add(columnName.Replace("\r", "").Replace("\n", "").Replace(" ", "").Trim(), typeof(string));   //去除标题头回车,换行的情况
                        }
                        catch (Exception)
                        {
                            dt.Columns.Add(columnName.Trim() + i.ToString(), typeof(string));
                        }
                    }
                }
                catch (Exception)
                {
                    amm.Statu = AjaxStatu.err;
                    amm.Msg   = "表头名不能为空或有重复!";

                    return(amm);
                }
                if (!isHead)//如果第一行是列名则不加入DataTable
                {
                    DataRow first = dt.NewRow();
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        first[i] = cell.ToString();
                    }
                    dt.Rows.Add(first);
                }
                while (rows.MoveNext())
                {
                    row = (IRow)rows.Current;
                    DataRow dataRow = dt.NewRow();
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        if (cell != null)
                        {
                            if (cell.CellType == CellType.Numeric)//如果是日期或数字
                            {
                                string readvalue = GetCellValue(cell);
                                if (readvalue.IndexOf("/") > -1 || readvalue.IndexOf("-") > 1)//如果是日期
                                {
                                    dataRow[i] = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss");
                                }
                                else
                                {
                                    dataRow[i] = readvalue;
                                }
                            }
                            else
                            {
                                dataRow[i] = GetCellValue(cell);
                            }
                            //dataRow[i] = cell.ToString();
                        }
                        else//如果是空白
                        {
                            dataRow[i] = "";
                        }
                        if (i == dt.Columns.Count - 1)
                        {
                            break;//如果行的列比表头多则不继续读取
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
                amm.Data  = removeEmpty(dt);
                amm.Statu = AjaxStatu.ok;
                amm.Msg   = "读取文件内容成功!";
                return(amm);
            }
            catch (Exception)
            {
                amm.Statu = AjaxStatu.err;
                amm.Msg   = "读取文件内容失败!可能原因或为文件中没内容";
                return(amm);
            }
        }
コード例 #18
0
ファイル: UploadFile.cs プロジェクト: wpmyj/six
        /// <summary>
        /// 生成缩略图 静态方法
        /// </summary>
        /// <param name="pathImageFrom"> 源图的路径(含文件名及扩展名) </param>
        /// <param name="pathImageTo"> 生成的缩略图所保存的路径(含文件名及扩展名)
        /// 注意:扩展名一定要与生成的缩略图格式相对应 </param>
        /// <param name="width"> 欲生成的缩略图 "画布" 的宽度(像素值) </param>
        /// <param name="height"> 欲生成的缩略图 "画布" 的高度(像素值) </param>
        public AjaxMsgModel GetSmallImg(AjaxMsgModel amm, string path, string fileName, int width, int height)
        {
            string pathImageFrom = path + "\\" + fileName;
            string pathImageTo   = path + "\\" + fileName.Replace("Y", "I");
            Image  imageFrom     = null;

            try
            {
                imageFrom = Image.FromFile(pathImageFrom);
            }
            catch
            {
                return(amm);
                //throw;
            }

            if (imageFrom == null)
            {
                return(amm);
            }

            // 源图宽度及高度
            int imageFromWidth  = imageFrom.Width;
            int imageFromHeight = imageFrom.Height;

            // 生成的缩略图实际宽度及高度
            int bitmapWidth  = width;
            int bitmapHeight = height;

            // 生成的缩略图在上述"画布"上的位置
            int X = 0;
            int Y = 0;

            // 根据源图及欲生成的缩略图尺寸,计算缩略图的实际尺寸及其在"画布"上的位置
            if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
            {
                bitmapHeight = imageFromHeight * width / imageFromWidth;
                Y            = (height - bitmapHeight) / 2;
            }
            else
            {
                bitmapWidth = imageFromWidth * height / imageFromHeight;
                X           = (width - bitmapWidth) / 2;
            }

            // 创建画布
            Bitmap   bmp = new Bitmap(width, height);
            Graphics g   = Graphics.FromImage(bmp);

            // 用白色清空
            g.Clear(Color.White);

            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // 指定高质量、低速度呈现。
            g.SmoothingMode = SmoothingMode.HighQuality;

            // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。
            g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);

            try
            {
                //经测试 .jpg 格式缩略图大小与质量等最优
                bmp.Save(pathImageTo, ImageFormat.Jpeg);
                amm.Statu = AjaxStatu.ok;
                amm.Msg   = "上传成功";
            }
            catch
            {
            }
            finally
            {
                //显示释放资源
                imageFrom.Dispose();
                bmp.Dispose();
                g.Dispose();
            }
            return(amm);
        }
コード例 #19
0
        public ActionResult Login(FormCollection form)
        {
            AjaxMsgModel ajaxM = new AjaxMsgModel()
            {
                Statu = "error", Msg = "登录失败!"
            };
            Base_Log logEntity = new Base_Log();

            //1.1 获取数据
            string strName  = Request.Params["UserName"];
            string strPwd   = Request.Params["Password"];
            string vcode    = Request.Params["VCode"];
            bool   isAllway = bool.Parse(Request.Params["isAllway"]);

            logEntity.CategoryId     = 1;
            logEntity.OperateTypeId  = ((int)OperationType.Login).ToString();
            logEntity.OperateType    = EnumAttribute.GetDescription(OperationType.Login);
            logEntity.OperateAccount = strName;
            logEntity.OperateUserId  = strName;
            logEntity.Module         = "我的MVC";
            ////1.2 验证
            //if (vcode!=Session["vcode"].ToString().ToLower())
            //{
            //    ajaxM.Msg = "登录失败,验证码不正确!";
            //    return Json(ajaxM);
            //}
            // 1.3 通过操作上下文获取 用户业务接口对象 ,调用里面的登录方法!
            User usr = _userBLL.Login(strName, strPwd);

            if (usr != null)
            {
                //2.1 保存 用户数据(session or cookie)
                Session["ainfo"] = usr;

                //如果选择了复选框 则要使用cookie 保存数据
                if (isAllway)
                {
                    //2.1.2 将用户id加密成字符串
                    string strCookieValue = SecurityHelper.EncryptUserInfo(usr.ID.ToString());
                    //2.1.3 创建cookie
                    HttpCookie cookie = new HttpCookie("cookieId", strCookieValue);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    cookie.Path    = "/admin";
                    Response.Cookies.Add(cookie);
                    //记录登录cookie
                }
                //2.2 查询当前用户的权限 , 并将权限存入Session 中
                //List<tbMenu> listPers = OperateContext.GetUserPermission(usr.ID);
                //Session["tbMenu"] = listPers;
                ajaxM.Statu                 = "ok";
                ajaxM.Msg                   = "登录成功!";
                ajaxM.BackUrl               = "/Home/Index";//"/Login/LoginOK";
                logEntity.ExecuteResult     = 1;
                logEntity.ExecuteResultJson = "登录成功";
                logEntity.WriteLog();
                return(Json(ajaxM));
            }
            else
            {
                ajaxM.Msg = "登录失败,用户或密码不正确!";
                return(Json(ajaxM));
            }
        }
コード例 #20
0
        /// <summary>
        ///  DataTable转List
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static AjaxMsgModel ConvertToList(DataTable dts, int rowIdex, AjaxMsgModel amm)
        {
            //错误集合
            List <TableToListErrorModel> errorList = new List <TableToListErrorModel>();
            // 定义集合
            List <T> ts = new List <T>();

            // 获得此模型的类型
            Type type = typeof(T);

            DataTable dt = ExcelExtHelper.ReplaceColumnsName(dts, type.Name);

            if (dt == null)
            {
                amm.Statu = AjaxStatu.err;
                amm.Msg   = "导入的文件模板不正确";
                errorList.Add(
                    new TableToListErrorModel()
                {
                    rowIndex    = rowIdex,
                    columnIndex = 0,
                    errorInfo   = "导入的文件模板不正确",
                    errorCause  = "导入的文件模板不正确"
                });
                amm.Data = errorList;// ObjToJson.GetToJson(errorList);//转为JSON
                return(amm);
            }

            //定义一个临时变量
            string tempName = string.Empty;

            //遍历DataTable中所有的数据行
            foreach (DataRow dr in dt.Rows)
            {
                rowIdex++;//计算行
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍历该对象的所有属性
                foreach (PropertyInfo pi in propertys)
                {
                    Type pt = pi.PropertyType;

                    tempName = pi.Name;//将属性名称赋值给临时变量
                    //检查DataTable是否包含此列(列名==对象的属性名)
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite)
                        {
                            continue;              //该属性不可写,直接跳出
                        }
                        //取值
                        object value = dr[tempName];
                        //判断
                        if (pt.Equals(value.GetType()))
                        {
                            //如果非空,则赋给对象的属性
                            if (value != DBNull.Value)
                            {
                                try
                                {
                                    pi.SetValue(t, value, null);
                                }
                                catch (Exception)
                                {
                                    amm.Statu = AjaxStatu.err;
                                    errorList.Add(
                                        new TableToListErrorModel()
                                    {
                                        rowIndex    = rowIdex,
                                        columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                        errorInfo   = "内容过多",
                                        errorCause  = "内容过多"
                                    });
                                }
                            }
                        }
                        else
                        {
                            string fullName = pt.FullName;

                            if (fullName.Contains("System.String"))//文本型
                            {
                                //如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                {
                                    try
                                    {
                                        pi.SetValue(t, value.ToString(), null);
                                    }
                                    catch (Exception)
                                    {
                                        amm.Statu = AjaxStatu.err;
                                        errorList.Add(
                                            new TableToListErrorModel()
                                        {
                                            rowIndex    = rowIdex,
                                            columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                            errorInfo   = "内容过多",
                                            errorCause  = "内容过多"
                                        });
                                    }
                                }
                            }
                            if (fullName.Contains("System.Int16"))//数字型
                            {
                                //如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                {
                                    try
                                    {
                                        if (!fullName.Contains("System.Nullable") || value != "")//如果是必填项或不为空时
                                        {
                                            value = Convert.ToInt16(value);
                                            pi.SetValue(t, value, null);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        amm.Statu = AjaxStatu.err;
                                        //数字转换失败
                                        errorList.Add(
                                            new TableToListErrorModel()
                                        {
                                            rowIndex    = rowIdex,
                                            columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                            errorInfo   = "数字转换失败",
                                            errorCause  = "需要数字类型"
                                        });
                                    }
                                }
                            }
                            if (fullName.Contains("System.Int32"))//数字型
                            {
                                //如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                {
                                    try
                                    {
                                        if (!fullName.Contains("System.Nullable") || value != "")//如果是必填项或不为空时
                                        {
                                            value = Convert.ToInt32(value);
                                            pi.SetValue(t, value, null);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        amm.Statu = AjaxStatu.err;
                                        //数字转换失败
                                        errorList.Add(
                                            new TableToListErrorModel()
                                        {
                                            rowIndex    = rowIdex,
                                            columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                            errorInfo   = "数字转换失败",
                                            errorCause  = "需要数字类型"
                                        });
                                    }
                                }
                            }
                            if (fullName.Contains("System.Decimal"))//数字型
                            {
                                //如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                {
                                    try
                                    {
                                        if (!fullName.Contains("System.Nullable") || value != "")//如果是必填项或不为空时
                                        {
                                            value = Convert.ToDecimal(value);
                                            pi.SetValue(t, value, null);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        amm.Statu = AjaxStatu.err;
                                        //数字转换失败
                                        errorList.Add(
                                            new TableToListErrorModel()
                                        {
                                            rowIndex    = rowIdex,
                                            columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                            errorInfo   = "数字转换失败",
                                            errorCause  = "需要数字类型"
                                        });
                                    }
                                }
                            }
                            if (fullName.Contains("System.DateTime"))//日期型
                            {
                                //如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                {
                                    try
                                    {
                                        if (!fullName.Contains("System.Nullable") || value != "")//如果是必填项或不为空时
                                        {
                                            value = Convert.ToDateTime(value.ToString());
                                            pi.SetValue(t, value, null);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        amm.Statu = AjaxStatu.err;
                                        //日期转换失败
                                        //excel日期列必须设置为日期格式才能正确转换
                                        errorList.Add(
                                            new TableToListErrorModel()
                                        {
                                            rowIndex    = rowIdex,
                                            columnIndex = dt.Columns.IndexOf(tempName) + 1,
                                            errorInfo   = "日期转换失败",
                                            errorCause  = "需要日期类型,请设置该单元格格式为日期型或算定义为yyyy-MM-dd HH:mm:ss"
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                //对象添加到泛型集合中
                ts.Add(t);
            }
            if (errorList.Count > 0)//如果有错误
            {
                amm.Statu = AjaxStatu.err;
                amm.Data  = errorList;// ObjToJson.GetToJson(errorList);//转为JSON
            }
            else
            {
                amm.Statu = AjaxStatu.ok;
                amm.Data  = ts;
            }
            return(amm);
        }