Exemplo n.º 1
0
        /// <summary>
        /// 通过多标签页数据将数据写入响应流
        /// </summary>
        /// <param name="multiSheet">多标签页数据</param>
        /// <param name="Response">响应流</param>
        public static void ExportToMutilSheet(ExportMultiSheet multiSheet, HttpResponse Response)
        {
            ExportToMutilSheet(multiSheet, Response.Body);

            Response.Headers.Add("Content-Disposition", string.Format("attachment;filename={0}", Path.GetFileName(multiSheet.FileName)));
            Response.ContentType = MimeHelper.GetMineType(multiSheet.FileName);

            Response.Body.Flush();
            Response.Clear();
        }
Exemplo n.º 2
0
        public ApiResult <ExcelDownloadInfo> Export([FromBody] ExcelInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }
            ApiResult <ExcelDownloadInfo> result = new ApiResult <ExcelDownloadInfo>();

            result.Result = new ExcelDownloadInfo();
            string fileExt = info.GetFileExt();

            if (string.IsNullOrEmpty(info.FileName))
            {
                info.FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + fileExt;
            }
            else
            {
                if (!info.FileName.EndsWith(fileExt))
                {
                    info.FileName = info.FileName + fileExt;
                }
            }
            //mimeType
            string mineType = MimeHelper.GetMineType(info.FileName);

            if (!info.IsExportSelectData)
            {
                //设置最大导出条数
                info.Condition          = info.Condition == null ? new QueryCondition() : info.Condition;
                info.Condition.PageSize = SystemConfig.MaxExport;
                if (string.IsNullOrEmpty(info.Api))
                {
                    throw new ArgumentNullException(nameof(info.Api));
                }
                if (!info.Api.StartsWith(Request.Scheme))
                {
                    info.Api = $"{Request.Scheme}://{Request.Host}{info.Api}";
                }
            }
            string[] arrPath = GetTempFilePath(UrlScheme, info.FileName);
            using (MemoryStream ms = info.ExportExeclStream(token))
            {
                using (FileStream fs = new FileStream(arrPath[0], FileMode.CreateNew))
                {
                    ms.WriteTo(fs);
                }
            }
            result.Result.Name = info.FileName;
            result.Result.Url  = arrPath[1];
            return(result);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> DownLoadTemplate(ExcelImportType type, string FunctionCode = "")
        {
            if (AllImports == null)
            {
                throw new ArgumentNullException("系统不存在Excel批量导入业务处理模块");
            }
            var handler = AllImports.FirstOrDefault(e => e.Type == type);

            if (handler == null)
            {
                throw new Exception("未找到“" + type.ToString() + "”相应处理模块");
            }

            string path = ExcelImporMapper.GetTemplatePath(type);

            if (System.IO.File.Exists(path))
            {
                try
                {
                    MemoryStream ms = new MemoryStream();
                    if (handler.DowloadNeedUserInfo)
                    {
                        await handler.GetExportTemplate(path, ms, CurrentUserInfo);
                    }
                    else
                    {
                        await handler.GetExportTemplate(path, ms);
                    }
                    ms.Position = 0;
                    return(File(ms, MimeHelper.GetMineType(path), Path.GetFileName(path)));
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                throw new Exception("未找到“" + type.ToString() + "”对应模版文件");
            }
        }
Exemplo n.º 4
0
        public ExcelModule() : base("Excel")
        {
            //任务列表
            Post["/GridExport"] = r =>
            {
                string excelParam = Request.Form["excelParam"];
                if (string.IsNullOrEmpty(excelParam))
                {
                    return("");
                }

                ExcelInfo info = JsonConvert.DeserializeObject <ExcelInfo>(excelParam);
                if (string.IsNullOrEmpty(info.FileName))
                {
                    info.FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls";
                }
                else
                {
                    if (!info.FileName.EndsWith(".xls"))
                    {
                        info.FileName = info.FileName + ".xls";
                    }
                }
                MemoryStream ms     = info.ExportExeclStream();
                byte[]       msbyte = ms.GetBuffer();
                ms.Dispose();
                ms = null;

                return(new Response()
                {
                    Contents = stream => { stream.Write(msbyte, 0, msbyte.Length); },
                    ContentType = "application/msexcel",
                    StatusCode = HttpStatusCode.OK,
                    Headers = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(info.FileName)) },
                        { "Content-Length", msbyte.Length.ToString() }
                    }
                });
            };


            /// <summary>
            /// 导出Excel模版
            /// </summary>
            /// <param name="type">业务类型</param>
            /// <param name="FunctionCode">对应功能模块Code</param>
            /// <returns></returns>
            Get["/DownLoadTemplate"] = r =>
            {
                if (AllImports == null)
                {
                    AllImports = MefConfig.ResolveMany <ExcelImport>();
                }
                string          strType = Request.Query["type"];
                ExcelImportType type    = EnumHelper.StringToEnum <ExcelImportType>(strType);
                var             handler = AllImports.FirstOrDefault(e => e.Type == type);
                if (handler == null)
                {
                    throw new Exception("未找到“" + type.ToString() + "”相应处理模块");
                }

                string path = ExcelImporMapper.GetTemplatePath(type);
                if (File.Exists(path))
                {
                    try
                    {
                        string FileName = Path.GetFileName(path);

                        return(new Response()
                        {
                            Contents = stream => { handler.GetExportTemplate(path, stream); },
                            ContentType = MimeHelper.GetMineType(path),
                            StatusCode = HttpStatusCode.OK,
                            Headers = new Dictionary <string, string> {
                                { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    throw new Exception("未找到“" + type.ToString() + "”对应模版文件");
                }
            };

            /// <summary>
            /// 导出Excel模版
            /// </summary>
            /// <returns></returns>
            Post["/ImportTemplate"] = r =>
            {
                ImportResult result = new ImportResult();
                try
                {
                    if (AllImports == null)
                    {
                        AllImports = MefConfig.ResolveMany <ExcelImport>();
                    }
                    string ywType = Request.Query["type"];
                    if (string.IsNullOrEmpty(ywType))
                    {
                        throw new ArgumentNullException("ywType");
                    }
                    //业务类型
                    ExcelImportType type = EnumHelper.StringToEnum <ExcelImportType>(ywType);

                    //文件
                    HttpFile file = Request.Files.First();

                    var handler = AllImports.FirstOrDefault(e => e.Type == type);
                    if (handler == null)
                    {
                        throw new Exception("未找到“" + type.ToString() + "”相应处理模块");
                    }

                    result = handler.ImportTemplate(file.Value, file.Name, null);
                    if (result.IsSuccess)
                    {
                        //是否获取详细数据,决定后台是否返回 result.ExtraInfo
                        string ReturnDetailData = Request.Query["ReturnDetailData"];
                        if (string.IsNullOrEmpty(ReturnDetailData) || ReturnDetailData != "1")
                        {
                            result.ExtraInfo = null;
                        }
                    }
                    else
                    {
                        //设置错误模版http路径
                        result.Message = Request.Url.SiteBase + result.Message;
                    }
                }
                catch (Exception ex)
                {
                    result.IsSuccess = false;
                    result.Message   = ex.Message;
                    LogHelper.WriteLog("Excel导入异常", ex);
                }
                return(Response.AsJson(result));
            };
        }
Exemplo n.º 5
0
        public ToolModule() : base("Tool")
        {
            //数据库表
            Get["/TableList"] = r =>
            {
                ViewBag.TableList = JsonConvert.SerializeObject(TableListService.GetAllTable());
                return(View["TableList"]);
            };

            //CronExpress表达式生成器FGZDZDZDZDZDZDZ
            Get["/CronExpress"] = r =>
            {
                return(View["CronExpress"]);
            };

            //命令行执行工具
            Get["/CommandLine"] = r =>
            {
                return(View["CommandLine"]);
            };

            //系统日志
            Get["/SysLog"] = r =>
            {
                return(View["SysLog"]);
            };

            //异常信息
            Get["/ExceptionLog"] = r =>
            {
                return(View["ExceptionLog", LogHelper.GetExceptionMsg()]);
            };
            #region "接口"

            //生成实体代码
            Post["/QuickCode"] = r =>
            {
                string strTableList = Request.Form["TableList"];
                if (string.IsNullOrEmpty(strTableList))
                {
                    return(null);
                }
                string FileName = string.Format("EntityCode-{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));
                var    res      = new Response()
                {
                    Contents    = stream => { EntityCodeHelper.QuickCode(TableListService.GetTableInfo(strTableList.Split(',')), stream); },
                    ContentType = MimeHelper.GetMineType(FileName),
                    StatusCode  = HttpStatusCode.OK,
                    Headers     = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                    }
                };
                return(res);
            };

            //计算表达式最近五次运行时间
            Get["/CalcRunTime"] = r =>
            {
                string CronExpressionString = Request.Query["CronExpression"];
                if (string.IsNullOrEmpty(CronExpressionString))
                {
                    return("[]");
                }
                else
                {
                    JsonSerializerSettings setting = new JsonSerializerSettings();
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return(JsonConvert.SerializeObject(QuartzHelper.GetTaskeFireTime(CronExpressionString, 5), setting));
                }
            };

            //获取命令行返回结果
            Post["/Cmd"] = r =>
            {
                string strCmd = Request.Form["cmd"];
                return(CommandHelp.ExcuteCommad(strCmd));
            };

            //删除异常消息
            Get["/DeleteException"] = r =>
            {
                string type  = Request.Query["Type"];
                string Index = Request.Query["Index"];
                if ("Delete".Equals(type, StringComparison.CurrentCultureIgnoreCase))
                {
                    long key;
                    if (long.TryParse(Index, out key))
                    {
                        LogHelper.RemoveExceptionMsg(key);
                    }
                }
                else if ("Clear".Equals(type, StringComparison.CurrentCultureIgnoreCase))
                {
                    LogHelper.ClearExceptionMsg();
                }
                return(string.Empty);
            };
            #endregion
        }
Exemplo n.º 6
0
        public LogModule() : base("Log")
        {
            //下载日志
            Get["/Download"] = r =>
            {
                string FileName = string.Format("log-{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));

                return(new Response()
                {
                    Contents = stream => { LogCmdHelper.DowloadLog(FileName, stream); },
                    ContentType = MimeHelper.GetMineType(FileName),
                    StatusCode = HttpStatusCode.OK,
                    Headers = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                    }
                });
            };

            //查看单个日志文件详情
            Get["/LogDetail"] = r =>
            {
                string filePath = Request.Query["name"];
                if (string.IsNullOrEmpty(filePath))
                {
                    return(Response.AsText("文件路径为空", "text/plain;charset=UTF-8"));
                }
                else
                {
                    if (File.Exists(filePath))
                    {
                        string filename    = Path.GetFileName(filePath);
                        string newFileName = Guid.NewGuid().ToString("N") + filename;
                        string newFilePath = filePath.Substring(0, filePath.LastIndexOf("\\") + 1) + newFileName;
                        try
                        {
                            File.Copy(filePath, newFilePath, true);
                            string text = string.Empty;
                            using (StreamReader sr = new StreamReader(newFilePath, Encoding.Default))
                            {
                                text = sr.ReadToEnd();
                            }
                            File.Delete(newFilePath);
                            return(Response.AsText(text, "text/plain;charset=UTF-8"));
                        }
                        catch (Exception ex)
                        {
                            return(Response.AsText(ex.ToString(), "text/plain;charset=UTF-8"));
                        }
                        finally
                        {
                            if (File.Exists(newFilePath))
                            {
                                File.Delete(newFilePath);
                            }
                        }
                    }
                    else
                    {
                        return(Response.AsText("文件不存在", "text/plain;charset=UTF-8"));
                    }
                }
            };

            //下载单个日志文件
            Get["/SingleDownload"] = r =>
            {
                string filePath = Request.Query["name"];
                if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                {
                    return(Response.AsText("文件不存在", "text/plain;charset=UTF-8"));
                }
                string FileName = Path.GetFileName(filePath);

                return(new Response()
                {
                    Contents = stream =>
                    {
                        byte[] m_buffer = new byte[BUFFER_SIZE];
                        int count = 0;
                        using (FileStream fs = File.OpenRead(filePath))
                        {
                            do
                            {
                                count = fs.Read(m_buffer, 0, BUFFER_SIZE);
                                stream.Write(m_buffer, 0, count);
                            } while (count == BUFFER_SIZE);
                        }
                    },
                    ContentType = MimeHelper.GetMineType(FileName),
                    StatusCode = HttpStatusCode.OK,
                    Headers = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                    }
                });
            };

            //下载指定日志文件
            Post["/DownloadSomeLog"] = r =>
            {
                string FileName    = string.Format("log-{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));
                string strFileList = Request.Form["FileList"];
                if (string.IsNullOrEmpty(strFileList))
                {
                    return("");
                }
                List <string> list = strFileList.Split('|').ToList();

                return(new Response()
                {
                    Contents = stream => { LogCmdHelper.DowloadLog(FileName, list, stream); },
                    ContentType = MimeHelper.GetMineType(FileName),
                    StatusCode = HttpStatusCode.OK,
                    Headers = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                    }
                });
            };

            #region "前端接口"

            //日志列表查询接口
            Post["/PostQuery"] = r =>
            {
                QueryCondition condition = this.Bind <QueryCondition>();

                //进行过滤
                string searchPattern = "*";
                if (condition.FilterList != null && condition.FilterList.Count > 0)
                {
                    var LogTypeFilter = condition.FilterList.FirstOrDefault(e => e.FieldName.Equals("LogType", StringComparison.CurrentCultureIgnoreCase));
                    if (LogTypeFilter != null && !string.IsNullOrEmpty(LogTypeFilter.FieldValue))
                    {
                        if (LogTypeFilter.FieldValue == "0")
                        {
                            searchPattern = "log-*";
                        }
                        else if (LogTypeFilter.FieldValue == "1")
                        {
                            searchPattern = "error-*";
                        }
                    }
                }

                var files = Directory.GetFiles(FileHelper.GetAbsolutePath("Logs"), searchPattern, SearchOption.AllDirectories);

                ApiResult <List <dynamic> > result = new ApiResult <List <dynamic> >();
                List <dynamic> list = new List <dynamic>();
                FileInfo       fi   = null;
                foreach (var item in files)
                {
                    fi = new FileInfo(item);
                    var file = new
                    {
                        FileName  = Path.GetFileName(item),
                        FileSize  = Math.Round(fi.Length / (1024 * 1.0), 2),
                        CreatedOn = fi.CreationTime,
                        FilePath  = item,
                        Link      = string.Format("http://127.0.0.1:{0}/{1}", SystemConfig.WebPort, item.Substring(AppDomain.CurrentDomain.BaseDirectory.Length).Replace("\\", "/"))
                    };
                    list.Add(file);
                }
                //条件过滤
                if (condition.FilterList != null && condition.FilterList.Count > 0)
                {
                    foreach (var filter in condition.FilterList)
                    {
                        if (!string.IsNullOrEmpty(filter.FieldValue))
                        {
                            switch (filter.FieldName)
                            {
                            case "FileName":
                                list = list.Where(e => e.FileName.Contains(filter.FieldValue)).ToList();
                                break;

                            case "FileSizeStart":
                                list = list.Where(e => e.FileSize >= Convert.ToDouble(filter.FieldValue)).ToList();
                                break;

                            case "FileSizeEnd":
                                list = list.Where(e => e.FileSize <= Convert.ToDouble(filter.FieldValue)).ToList();
                                break;

                            case "CreatedOnStart":
                                list = list.Where(e => e.CreatedOn >= Convert.ToDateTime(filter.FieldValue)).ToList();
                                break;

                            case "CreatedOnEnd":
                                list = list.Where(e => e.CreatedOn <= Convert.ToDateTime(filter.FieldValue)).ToList();
                                break;
                            }
                        }
                    }
                }
                //排序
                if (string.IsNullOrEmpty(condition.SortField))
                {
                    condition.SortField = "CreatedOn";
                    condition.SortOrder = "desc";
                }
                if (condition.SortOrder.Equals("desc", StringComparison.OrdinalIgnoreCase))
                {
                    switch (condition.SortField)
                    {
                    case "FileName":
                        list = list.OrderByDescending(e => e.FileName).ToList();
                        break;

                    case "FileSize":
                        list = list.OrderByDescending(e => e.FileSize).ToList();
                        break;

                    case "CreatedOn":
                        list = list.OrderByDescending(e => e.CreatedOn).ToList();
                        break;
                    }
                }
                else
                {
                    switch (condition.SortField)
                    {
                    case "FileName":
                        list = list.OrderBy(e => e.FileName).ToList();
                        break;

                    case "FileSize":
                        list = list.OrderBy(e => e.FileSize).ToList();
                        break;

                    case "CreatedOn":
                        list = list.OrderBy(e => e.CreatedOn).ToList();
                        break;
                    }
                }
                //分页查询
                list = list.Skip(condition.PageIndex * condition.PageSize).Take(condition.PageSize).ToList();

                result.Result     = list;
                result.TotalCount = Convert.ToInt32(list.Count);
                result.TotalPage  = result.CalculateTotalPage(condition.PageSize, result.TotalCount.Value, condition.IsPagination);
                return(Response.AsJson(result));
            };

            #endregion
        }