Exemple #1
0
 void ReportProgressScript(string filepath)
 {
     _reporter.Content.Action         = RunnerAction.ScriptRunning;
     _reporter.Content.ScriptFilepath = filepath;
     _reporter.Content.ScriptFilename = PathExtension.Filename(filepath);
     _reporter.Report();
 }
Exemple #2
0
        public List <TaskCommand> Generate(Dictionary <string, JToken> sectionData)
        {
            JToken ioSection =
                sectionData[ConfigSectionBase.IOConfigSectionId];

            string inputPath  = PathExtension.GetFullPathOrEmpty(ioSection["input"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string outputPath = PathExtension.GetFullPathOrEmpty(ioSection["output"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();

            #region 自定义参数

            JToken customArgsSection =
                sectionData["Ruminoid.Toolbox.Plugins.Common.ConfigSections.CustomArgsConfigSection"];

            string customArgs    = customArgsSection["args"]?.ToObject <string>();
            bool   useCustomArgs = customArgsSection["use_custom_args"]?.ToObject <bool>() ?? false;

            #endregion

            return(new()
            {
                new(
                    "ffmpeg",
                    $"-y -i {inputPath} -c:v libx264 -vsync cfr {(useCustomArgs ? customArgs : DefaultArgs)} -af aresample=async=1000 -c:a aac {outputPath}",
                    "ffmpeg")
            });
        }
        public void GetMatchPath_WhenExists_1()
        {
            var popFolderPath   = PathExtension.Normalize(fixturesFolder + @"/music/pop/");
            var houseFolderPath = PathExtension.Normalize(fixturesFolder + @"/music/house/");
            var mainFolderPath  = PathExtension.Normalize(fixturesFolder + @"/music/deep/");
            var specFolderPath  = PathExtension.Normalize(fixturesFolder + @"/music/spec/");

            var collection = new HashTagFolderCollection
            {
                { popFolderPath, "#pop" },
                { houseFolderPath, "#house" },
                { houseFolderPath, "#house #pop" },
                { mainFolderPath, "#deep" },
                { mainFolderPath, "#deep #house" },
                { mainFolderPath, "#deep #house #pop" },
                { mainFolderPath, "#newdisco" },
                { specFolderPath, "#spec" },
                { specFolderPath, "#trap" },
                { specFolderPath, "#rnb" },
                { specFolderPath, "#pop #spec" },
                { specFolderPath, "#house #spec" },
                { specFolderPath, "#house #spec #pop" },
            };

            Assert.AreEqual(houseFolderPath, collection.GetMatchPath(HashTagModel.Parser.All("#pop #house #entrophy")));
            Assert.AreEqual(popFolderPath, collection.GetMatchPath(HashTagModel.Parser.All("#entrophy #pop")));
            Assert.AreEqual(houseFolderPath, collection.GetMatchPath(HashTagModel.Parser.All("#house #entrophy")));
            Assert.AreEqual(specFolderPath, collection.GetMatchPath(HashTagModel.Parser.All("#spec #entrophy")));
            Assert.AreEqual(specFolderPath,
                            collection.GetMatchPath(HashTagModel.Parser.All("#spec #pop #house #entrophy")));
            Assert.AreEqual(specFolderPath,
                            collection.GetMatchPath(HashTagModel.Parser.All("#spec #pop #house #deep #entrophy")));
            Assert.AreEqual(mainFolderPath,
                            collection.GetMatchPath(HashTagModel.Parser.All("#pop #house #deep #entrophy")));
        }
Exemple #4
0
        public List <TaskCommand> Generate(Dictionary <string, JToken> sectionData)
        {
            JToken muxSection =
                sectionData["Ruminoid.Toolbox.Plugins.Common.ConfigSections.MuxConfigSection"];

            string videoPath  = PathExtension.GetFullPathOrEmpty(muxSection["video"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string audioPath  = PathExtension.GetFullPathOrEmpty(muxSection["audio"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string outputPath = PathExtension.GetFullPathOrEmpty(muxSection["output"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();

            #region 自定义参数

            JToken customArgsSection =
                sectionData["Ruminoid.Toolbox.Plugins.Common.ConfigSections.CustomArgsConfigSection"];

            string customArgs    = customArgsSection["args"]?.ToObject <string>();
            bool   useCustomArgs = customArgsSection["use_custom_args"]?.ToObject <bool>() ?? false;

            #endregion

            return(new List <TaskCommand>
            {
                new(
                    "ffmpeg",
                    $"-y -i {videoPath} -i {audioPath} -filter_complex \"[0:a][1:a]amerge=inputs=2[a]\" -map 0:v -map \"[a]\" -c:v copy -ac 2 {(useCustomArgs ? customArgs : DefaultArgs)} {outputPath}",
                    "ffmpeg")
            });
Exemple #5
0
        /// <summary>
        /// 对上传的试题题库进行分析
        /// </summary>
        /// <param name="examFiles"></param>
        /// <returns></returns>
        public static object AnalysisExamQuestion(ExamFiles examFiles)
        {
            //var absolutePath = HttpContext.Current.Server.MapPath(examFiles.FilePath);
            // @FrancisTan 20170208
            var absolutePath = PathExtension.MapPath(examFiles.FilePath);

            try
            {
                using (var fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read))
                {
                    var workBook = new HSSFWorkbook(fileStream);
                    var qaList   = AnalysisQuestions(workBook);

                    if (qaList.Count == 0)
                    {
                        return(ErrorModel.OperateFailed);
                    }

                    return(InsertQuestionsToDb(examFiles, qaList));
                }
            }
            catch (Exception ex)
            {
                ExceptionLogBll.ExceptionPersistence("ExamController.cs", "ExamController", ex);

                return(ErrorModel.OperateFailed);
            }
        }
Exemple #6
0
        public JsonResult Upload()
        {
            // 获取文件流
            var file = Request.Files[0];

            if (file == null)
            {
                return(Json(ErrorModel.InputError));
            }

            // 获取文件hash值
            var hash = file.InputStream.GetMd5();

            // 生成版本号和文件名
            var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

            // 处理相对路径与绝对路径
            var relatePath   = Path.Combine(AppSettings.ApkFiles, fileName).Replace("\\", "/");
            var absolutePath = PathExtension.MapPath(relatePath);
            var dir          = absolutePath.Replace(fileName, "");

            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(dir);
            }

            // 存储到本地
            file.SaveAs(absolutePath);

            return(Json(new
            {
                path = relatePath,
                hash
            }));
        }
Exemple #7
0
        private void Init(string fileName, long fileSize, string dirPath, bool keepOriginalName)
        {
            OriginalFileName = fileName;

            var dir = dirPath.Replace("~/", "/");

            //var rootAbPath = HttpContext.Current.Server.MapPath(dir);
            // @FrancisTan 20170208
            //var rootAbPath = PathExtension.MapPath(dir);
            // @FrancisTan 2017-03-31 支持以绝对路径作为参数
            var rootAbPath = dirPath;

            if (!Regex.IsMatch(dirPath, "^[A-Za-z]:"))
            {
                // 将相对路径映射成绝对路径
                rootAbPath = PathExtension.MapPath(dir);
            }

            var dateDirName = DateTime.Now.ToString("yyyy-MM-dd");

            RootAbsolutePath = Path.Combine(rootAbPath, dateDirName);
            RootRelativeDir  = Path.Combine(dir, dateDirName);

            NewFileName = fileName;
            if (!keepOriginalName)
            {
                var guid = Guid.NewGuid();
                NewFileName = guid + FileExtension;
            }

            FileSize = fileSize;
        }
        public List <TaskCommand> Generate(Dictionary <string, JToken> sectionData)
        {
            JToken ioSection =
                sectionData[ConfigSectionBase.IOConfigSectionId];

            string inputPath    = PathExtension.GetFullPathOrEmpty(ioSection["input"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string subtitlePath = PathExtension.GetFullPathOrEmpty(ioSection["subtitle"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string outputPath   = PathExtension.GetFullPathOrEmpty(ioSection["output"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();

            #region 自定义参数

            JToken customArgsSection =
                sectionData["Ruminoid.Toolbox.Plugins.Common.ConfigSections.CustomArgsConfigSection"];

            string customArgs    = customArgsSection["args"]?.ToObject <string>();
            bool   useCustomArgs = customArgsSection["use_custom_args"]?.ToObject <bool>() ?? false;

            #endregion

            List <TaskCommand> result = new();

            result.Add((
                           "ffmpeg",
                           $"-i {inputPath} -i {subtitlePath} -y {(useCustomArgs ? customArgs : DefaultArgs)} {outputPath}",
                           "ffmpeg"));

            return(result);
        }
Exemple #9
0
 private void CheckCompilationSubfolder(string subfolderPath)
 {
     if (PathExtension.DirectoryExists(subfolderPath) == false)
     {
         throw new CompilationSubFolderException(subfolderPath);
     }
 }
Exemple #10
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request       = filterContext.HttpContext.Request;
            var stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            foreach (var key in request.QueryString.AllKeys)
            {
                stringBuilder.AppendFormat("{0}:{1}\r\n", key, request.QueryString[key]);
            }
            foreach (var key in request.Form.AllKeys)
            {
                stringBuilder.AppendFormat("{0}:{1}\r\n", key, request.Form[key]);
            }
            stringBuilder.AppendLine("===============================================\r\n");

            //var path = filterContext.HttpContext.Server.MapPath("/Log/App");
            // @FrancisTan 20170208
            var path = PathExtension.MapPath("/Log/App");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filePath = Path.Combine(path, "params.log");

            using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (var streamWriter = new StreamWriter(fileStream))
                {
                    streamWriter.Write(stringBuilder);
                }
            }
        }
        public List <TaskCommand> Generate(Dictionary <string, JToken> sectionData)
        {
            JToken ioSection =
                sectionData[ConfigSectionBase.IOConfigSectionId];
            JToken audioSection =
                sectionData["Ruminoid.Toolbox.Plugins.Audio.ConfigSections.AudioQualityConfigSection"];

            string inputPath  = PathExtension.GetFullPathOrEmpty(ioSection["input"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();
            string outputPath = PathExtension.GetFullPathOrEmpty(ioSection["output"]?.ToObject <string>() ?? string.Empty).EscapePathStringForArg();

            int audioBitrate = audioSection["bitrate"].ToObject <int>();

            #region 自定义参数

            JToken customArgsSection =
                sectionData["Ruminoid.Toolbox.Plugins.Common.ConfigSections.CustomArgsConfigSection"];

            string customArgs    = customArgsSection["args"]?.ToObject <string>();
            bool   useCustomArgs = customArgsSection["use_custom_args"]?.ToObject <bool>() ?? false;

            #endregion

            return(new List <TaskCommand>
            {
                new(
                    "qaac64",
                    $" -q 2 --ignorelength -c {audioBitrate} {(useCustomArgs ? customArgs : DefaultArgs)} {inputPath} -o {outputPath}",
                    "null")
            });
Exemple #12
0
        private static void GenerateComponent(ComponentDefinition componentDefinition)
        {
            // Paths
            var componentsPath = componentDefinition.Directory;

            if (componentsPath.EndsWith("Components"))
            {
                componentsPath = PathExtension.SystemPath(componentsPath);
            }
            else
            {
                componentsPath = PathExtension.SystemPath(Path.Combine(componentsPath, "Components"));
            }
            if (!Directory.Exists(componentsPath))
            {
                Directory.CreateDirectory(componentsPath);
            }

            var template = CodeGeneratorUtils.LoadTemplate("Component");

            var processors = ProcessorsSelector.Selectors <ICodeGeneratorComponentProcessors>();

            foreach (var processor in processors)
            {
                template = processor.Process(componentDefinition, template);
            }

            var upperedComponentName = componentDefinition.ComponentName.ToUpperFirstChar();
            var componentPath        = Path.Combine(componentsPath, $"{upperedComponentName}.cs");

            GenerateComponentFile(upperedComponentName, componentPath, template);
        }
Exemple #13
0
        private void OnGUI()
        {
            DrawSizeAnalysis();

            _serializedObject.Update();

            // Iterate through serialized properties and draw them like the Inspector (But with ports)
            SerializedProperty componentProperty = _serializedObject.FindProperty(nameof(_componentDefinition));

            // Directory
            EditorGUILayout.BeginHorizontal();
            var directoryProperty = componentProperty.FindPropertyRelative("Directory");

            GUIDrawers.DrawFieldWithLabel(directoryProperty);
            if (GUILayout.Button("\u27b1", GUILayout.Width(30)))
            {
                var dialogPath = EditorUtility.OpenFolderPanel("Code directory", "", "");
                if (!string.IsNullOrWhiteSpace(dialogPath))
                {
                    directoryProperty.stringValue = PathExtension.AssetsPath(dialogPath);
                }
            }
            EditorGUILayout.EndHorizontal();

            // Namespace
            var namespaceProperty = componentProperty.FindPropertyRelative("Namespace");

            using (new GUIEnabledScope(false))
            {
                if (!namespaceProperty.stringValue.EndsWith(".Components", StringComparison.InvariantCultureIgnoreCase))
                {
                    EditorGUILayout.TextArea("Remember, if namespace do not ends with \".Components\" system will automatically add it", EditorStyles.helpBox);
                }
            }
            EditorGUILayout.BeginHorizontal();
            GUIDrawers.DrawFieldWithLabel(namespaceProperty);
            var selectedNamespace = DrawNamespacesPopup(namespaceProperty.stringValue);

            if (!string.IsNullOrWhiteSpace(selectedNamespace))
            {
                namespaceProperty.stringValue = selectedNamespace;
            }
            EditorGUILayout.EndHorizontal();

            // Type & Name
            EditorGUILayout.BeginHorizontal();
            GUIDrawers.DrawFieldWithLabel(componentProperty.FindPropertyRelative("ComponentType"));
            GUIDrawers.DrawFieldWithLabel(componentProperty.FindPropertyRelative("ComponentName"));
            EditorGUILayout.EndHorizontal();

            // Fields
            GUIDrawers.DrawArray <object>(componentProperty.FindPropertyRelative("Fields"));

            _serializedObject.ApplyModifiedProperties();

            DrawActionButtons();
        }
        public void MakeRelativePathTest()
        {
            string root  = @"C:\Test";
            string test1 = @"C:\Test\Test1";
            string test2 = @"C:\Test\Test1\Test2";

            Assert.AreEqual("Test1", PathExtension.MakeRelativePath(root, test1));
            Assert.AreEqual(@"Test1\Test2", PathExtension.MakeRelativePath(root, test2));
        }
        public void MakeAbsolutePathTest()
        {
            string root  = @"C:\Test";
            string test1 = @"Test1";
            string test2 = @"Test1\Test2";

            Assert.AreEqual(@"C:\Test\Test1", PathExtension.MakeAbsolutePath(test1, root));
            Assert.AreEqual(@"C:\Test\Test1\Test2", PathExtension.MakeAbsolutePath(test2, root));
        }
        /// <summary>
        /// 读取货车车次表格
        /// </summary>
        /// <returns></returns>
        public static ISheet GetHuocheSheet()
        {
            var path = PathExtension.MapPath("test-huoche.xls"); // 下行

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var workBook = new HSSFWorkbook(fs);
                return(workBook.GetSheetAt(0));
            }
        }
Exemple #17
0
 //implementation of parseValue
 public override object parseValue(string Parameter)
 {
     if (PathExtension.DirectoryExists(Parameter))
     {
         return(Parameter);
     }
     else
     {
         throw new System.ArgumentException(string.Format("Directory [{0}] does not exist", Parameter));
     }
 }
Exemple #18
0
 //implementation of parseValue
 public override object parseValue(string Parameter)
 {
     if (PathExtension.IsFilenameValid(Parameter))
     {
         return(Parameter);
     }
     else
     {
         throw new System.ArgumentException(string.Format("Filename [{0}] invalid", Parameter));
     }
 }
        private static string GetToken()
        {
            var filename = PathExtension.GetHome(".token", "token");

            if (!File.Exists(filename))
            {
                return(null);
            }

            return(File.ReadAllText(filename));
        }
        private static void SaveToken(string p_token)
        {
            var filename = PathExtension.GetHome(".token", "token");
            var dir      = Path.GetDirectoryName(filename);

            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            File.WriteAllText(filename, p_token);
        }
        private string ResolveXSLPath(string xmlFilePath, string baseFolder)
        {
            // 0: 만약 XML 파일안에 xcg-xsltKey Preprocessor 가 있다면 그를 따른다.
            XmlDocument document = new XmlDocument();

            document.Load(xmlFilePath);
            XmlProcessingInstruction xcgPI =
                document.SelectSingleNode("/processing-instruction(\"xcg-xsltKey\")")
                as XmlProcessingInstruction;

            if (xcgPI != null)
            {
                return(Path.Combine(baseFolder, xcgPI.Value) + ".xslt");
            }

            // 0.1: 만약 XML 파일안에 xcg-xsltFileName Preprocessor 가 있다면 그를 따른다.
            xcgPI = document.SelectSingleNode("/processing-instruction(\"xcg-xsltFileName\")") as XmlProcessingInstruction;

            if (xcgPI != null)
            {
                string xmlFolder = Path.GetDirectoryName(xmlFilePath);
                return(Path.Combine(xmlFolder, xcgPI.Value) + ".xslt");
            }

            // 1: XML 파일에서 "xslt" 확장자만 교체해서 검색
            string xslFilePath = Path.ChangeExtension(xmlFilePath, "xslt");

            if (File.Exists(xslFilePath) == true)
            {
                return(xslFilePath);
            }

            // 2: 같은 폴더에서 파일명만 default.xslt
            string defaultXslFilePath = PathExtension.ChangeFileName(xslFilePath, DefaultXslFileName);

            if (File.Exists(defaultXslFilePath) == true)
            {
                return(defaultXslFilePath);
            }

            // 3: 상위 폴더에서 루트 드라이브까지 파일명이 XML 파일에서 xslt 확장자만 교체한 것과 일치한 것을 검색
            string found = PathExtension.SearchInParents(xslFilePath);

            if (string.IsNullOrEmpty(found) == false)
            {
                return(found);
            }

            // 4: 상위 폴더에서 루트 드라이브까지 파일명이 default.xslt 파일이 있는지 검사.
            return(PathExtension.SearchInParents(defaultXslFilePath));
        }
Exemple #22
0
        /// <summary>
        /// 将上传的文件进行格式转换处理,若文件格式符合处理条件,则在文件处理完成之后会将处理后得到的新文件地址赋值给 fileModel 的 FilePath 字段并返回
        /// </summary>
        /// <param name="fileModel"><see cref="TraficFiles"/>类的实体对象</param>
        public static TraficFiles Format(TraficFiles fileModel)
        {
            try
            {
                var fileName      = PathExtension.MapPath(fileModel.FilePath);
                var path          = Path.GetDirectoryName(fileName);
                var htmlFilesPath = Path.Combine(path, Guid.NewGuid().ToString());

                var ext = Path.GetExtension(fileName).ToLower();
                switch (ext)
                {
                case ".doc":
                case ".docx":
                    FileHelper.Word2Html(fileName, htmlFilesPath);
                    break;

                //case ".pdf":
                //    FileHelper.Pdf2Html(fileName, htmlFilesPath);
                //    break;

                default:
                    //throw new NotImplementedException();
                    return(fileModel);
                }

                // 将 __html 中的文件打包压缩成 zip 格式的文件
                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                var zipFileName = Path.Combine(path, fileNameWithoutExtension + ".zip");
                FileHelper.Zip(zipFileName, htmlFilesPath);

                // 删除 __html 目录
                Directory.Delete(htmlFilesPath, true);

                // 将 zip 文件路径处理成相对路径
                fileName = fileName.Replace("\\", "/");
                var webDir = fileName.Replace(fileModel.FilePath, "");
                fileModel.FilePath = zipFileName.Replace("\\", "/").Replace(webDir, "");
                fileModel.FilePath = fileModel.FilePath.StartsWith("/") ? fileModel.FilePath : $"/{fileModel.FilePath}";

                var n = fileModel.FileName;
                fileModel.FileExtension = ".zip";
                fileModel.FileName      = Path.GetFileNameWithoutExtension(n) + fileModel.FileExtension;
                return(fileModel);
            }
            catch (Exception ex)
            {
                ExceptionLogBll.ExceptionPersistence(nameof(FileProcesser), nameof(FileProcesser), ex);
                return(fileModel);
            }
        }
Exemple #23
0
        /// <summary>
        /// 针对新增文件搜索所有关键字
        /// </summary>
        /// <param name="fileId"></param>
        private static void SearchForNewFile(int fileId)
        {
            var fileBll = new TraficFilesBll();
            var file    = fileBll.QuerySingle(fileId);

            if (file != null && file.FileExtension.ToLower() == ".zip")
            {
                var keywordsBll  = new TraficKeywordsBll();
                var keywordsList = keywordsBll.QueryAll();
                var zipFileName  = PathExtension.MapPath(file.FilePath);

                var zipTempFileName = Path.Combine(ZipTempPath, Path.GetFileName(file.FilePath));
                if (!Directory.Exists(ZipTempPath))
                {
                    Directory.CreateDirectory(ZipTempPath);
                }

                if (File.Exists(zipFileName))
                {
                    FileHelper.ExtractZip(zipFileName, ExtractPath);
                    var html = GetHtmlStr(ExtractPath, out string htmlFileName, out Encoding encoding);
                    html = AddIdForHtmlDom(html);
                    var tasks = new List <Task>();
                    foreach (var keywords in keywordsList)
                    {
                        tasks.Add(Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                var searchResult = SearchFromHtml(keywords.Keywords, html);

                                SearchResultEnqueue(searchResult, fileId, keywords.Id);
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogBll.ExceptionPersistence(nameof(SearchHelper), nameof(SearchHelper), ex);
                            }
                        }));
                    }

                    Task.WaitAll(tasks.ToArray());
                    ClearSearchResultQueue();
                    FileHelper.Write(htmlFileName, html, encoding);
                    SearchCompleted(zipTempFileName, zipFileName, ExtractPath);
                    tasks = null;
                    GC.Collect();
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// 在本类第一次被使用时加载过滤器配置文件到内存中
        /// </summary>
        static Authority()
        {
            try
            {
                //var configPath = HttpContext.Current.Server.MapPath("/filter.config");
                // @FrancisTan 20170208
                var configPath = PathExtension.MapPath("/filter.config");

                FilterRoot = XElement.Load(configPath);
            }
            catch
            {
                throw new Exception("加载filter.config出现异常,请检查此配置文件");
            }
        }
    static void RegenerateTagsFile()
    {
        string template =
            "// This file is autogenerated!" +
            "\n" + "static public class Tags" +
            "\n" + "{" +
            "\n" + "	#generateme#"+
            "\n" + "}";
        string entryTemplate = "\tpublic const string #safename# = \"#name#\";\n";
        string outputPath    = PathExtension.Combine("_Assets", "Scripts", "Util_safe", "Generated", "Tags.cs");

        string[] tags = UnityEditorInternal.InternalEditorUtility.tags;

        GenerateCodeFile.CreateFile(template, outputPath, entryTemplate, tags);
    }
Exemple #26
0
        protected void ReadTemplate(string templateFilepath)
        {
            if (string.IsNullOrWhiteSpace(templateFilepath))
            {
                throw new ArgumentException("TemplateFilepath can not be empty");
            }

            if (PathExtension.FileExists(templateFilepath) == false)
            {
                throw new TemplateFileNotFoundException(templateFilepath);
            }

            //If there is a load error, this will throw an exception
            _content = new StringBuilder(File.ReadAllText(templateFilepath, Encoding.UTF8));
        }
Exemple #27
0
 public MusicFolder(string path, bool createNew = false)
 {
     path = PathExtension.Normalize(path);
     if (!Directory.Exists(path))
     {
         if (!createNew)
         {
             throw new DirectoryNotFoundException();
         }
         else
         {
             Directory.CreateDirectory(path);
         }
     }
     this.path = path;
 }
        public string Move(string filePath)
        {
            CreateIfNotExists();

            filePath = PathExtension.Normalize(filePath);
            var fileInfo = new FileInfo(filePath);

            Contract.Assume(fileInfo.Directory != null);
            Contract.Assume(fileInfo.Directory.Parent != null);

            var newFilePath = IOPath.Combine(Path, fileInfo.Name);

            fileInfo.MoveTo(newFilePath);

            return(newFilePath);
        }
Exemple #29
0
        /// <summary>
        /// 添加搜索关键字,此任务仅在数据库中关键字条目数少于100个时才会执行
        /// </summary>
        public static void AddSearchKeywords()
        {
            // 判断数据库中关键字个数
            var keywordsBll = new TraficKeywordsBll();
            var totalCount  = keywordsBll.GetTotalCount();

            if (totalCount < 100)
            {
                // 读取文件中的关键字列表
                var filePath = PathExtension.MapPath(AppSettings.KeywordsFilePath);
                try
                {
                    using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        using (var streamReader = new StreamReader(fileStream))
                        {
                            var text     = streamReader.ReadToEnd();
                            var keywords = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                            // @FrancisTan 2017-10-27
                            // 批量插入关键字
                            var modelList = keywords.Select(k => new TraficKeywords {
                                Keywords = k, AddTime = DateTime.Now
                            });
                            keywordsBll.BulkInsert(modelList);
                            DataUpdateLog.BulkUpdate(nameof(TraficKeywords), 0);

                            // 依次对单个文件执行关键字搜索
                            var fileBll = new TraficFilesBll();
                            var idList  = fileBll.QueryList("IsDelete=0", new string[] { "Id" }).Select(t => t.Id).ToList();
                            idList.ForEach(id =>
                            {
                                SearchHelper.AddSearchTask(1, id);
                            });
                        } // end streamreader
                    }     // end filestream
                }
                catch (Exception ex)
                {
                    ExceptionLogBll.ExceptionPersistence(nameof(TempTask), nameof(TempTask), ex);
                }
            }
            else
            {
                // Ignore
            }
        }
 /// <summary>
 /// 执行数据同步操作
 /// 通过获取在配置文件中所配置的实现了<see cref="IMigration"/>接口的类型名称,
 /// 并反射创建类型集合,最终循环执行同步操作
 /// </summary>
 public static void ExecuteDataSynchronization()
 {
     try
     {
         var tasks = GetSyncTasks();
         tasks.ForEach(task =>
         {
             task.ImportNewData();
             task.UpdateEditedData();
         });
     }
     catch (Exception ex)
     {
         var logPath = PathExtension.MapPath("service.log");
         FileHelper.Write(logPath, ex.ToString());
     }
 }