Replace() public method

public Replace ( String destinationFileName, String destinationBackupFileName ) : FileInfo
destinationFileName String
destinationBackupFileName String
return FileInfo
Beispiel #1
0
        /// <summary>
        /// 编译器器开始变以前处理逻辑
        /// </summary>
        public override void BeginCompile()
        {
            ScreenPermissionData = new Dictionary <int, int>();
            var targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;

            OutputPath = Path.Combine(targetDirectory.Replace("\\Wilmar.PlatformService\\bin\\Extension", "").Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Terminate\Projects", this.Project.Identity);
            OutputPath = HttpUtility.UrlDecode(OutputPath);
            if (!Directory.Exists(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);
            }
            Permission = GlobalServices.SecurityService.CreatePermissionContext(this);

            //屏幕权限操作
            var screenItems = ProjectItems.Where(a => a.Value.DocumentType == GlobalIds.DocumentType.Screen).ToList();

            foreach (var item in screenItems)
            {
                var screen = GetDocumentBody(item.Value) as ScreenDefinition;
                if (screen != null && screen.PermissionConfigure.EnableAuth)
                {
                    var doc = item.Value as ProjectDocument;
                    int screenPermissionId = this.Permission.Write(doc.Id, DojoCompile.PermissionScreen, doc.Id.ToString(), doc.Title + "的屏幕权限", doc.Title);
                    this.ScreenPermissionData.Add(doc.Id, screenPermissionId);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// 生成项目配置文件
        /// </summary>
        /// <param name="ionicCompile"></param>
        private void BuildProjectConfig(IonicCompile ionicCompile)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw);
                jsonWriter.Formatting = Formatting.Indented;

                var frontConfig = ionicCompile.Project.Configures.OfType <FrontEndConfigure>().FirstOrDefault();
                //创建配置对象
                jsonWriter.WriteStartObject();
                #region
                jsonWriter.WritePropertyName("projectid");
                jsonWriter.WriteValue(ionicCompile.ProjectId);
                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue(ionicCompile.Project.Identity);
                jsonWriter.WritePropertyName("title");
                jsonWriter.WriteValue(ionicCompile.Project.Root.Title);
                jsonWriter.WritePropertyName("desc");
                jsonWriter.WriteValue(ionicCompile.Project.Description);
                jsonWriter.WritePropertyName("api_endpoint");
                jsonWriter.WriteValue(frontConfig.ServerUrl + "odata" + "/" + ionicCompile.Project.Identity);
                #endregion
                jsonWriter.WriteEndObject();

                //获取JSON串
                string output = sw.ToString();
                jsonWriter.Close();
                sw.Close();

                var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
                string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\config", ionicCompile.Project.Identity);
                outputPath = HttpUtility.UrlDecode(outputPath);
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                var file = Path.Combine(outputPath, ionicCompile.Project.Identity + ".config.ts");
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                string content = string.Format("export const {0}_CONFIG=", ionicCompile.Project.Identity.ToUpper()) + output;
                File.WriteAllText(file, content, System.Text.UTF8Encoding.UTF8);

                var devFile = Path.Combine(outputPath, ionicCompile.Project.Identity + ".config.dev.ts");
                if (File.Exists(devFile))
                {
                    File.Delete(devFile);
                }
                string devContent = string.Format("export const {0}_CONFIG=", ionicCompile.Project.Identity.ToUpper()) + output;
                File.WriteAllText(devFile, devContent, System.Text.UTF8Encoding.UTF8);
            }
        }
Beispiel #3
0
        private string GenerateDestFileName(JToken title)
        {
            string destFile = title.ToString();
            var index1 = destFile.IndexOf('(');
            var index2 = destFile.IndexOf(')', index1);

            destFile = destFile.Substring(index1 + 1, index2 - index1-1);

            return destFile.Replace(" ", string.Empty) + ".json";
        }
Beispiel #4
0
        /// <summary>
        /// 生成平台配置文件
        /// </summary>
        /// <param name="ionicCompile"></param>
        private void BuildPlatformConfig(IonicCompile ionicCompile)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw);
                jsonWriter.Formatting = Formatting.Indented;

                var frontConfig = ionicCompile.Project.Configures.OfType <FrontEndConfigure>().FirstOrDefault();
                //创建配置对象
                jsonWriter.WriteStartObject();
                #region
                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue("kds3.0 Mobile");
                jsonWriter.WritePropertyName("title");
                jsonWriter.WriteValue("kds3.0 移动端");
                jsonWriter.WritePropertyName("version");
                jsonWriter.WriteValue("1.0.0");
                jsonWriter.WritePropertyName("desc");
                jsonWriter.WriteValue("kds3.0 移动端平台系统");
                jsonWriter.WritePropertyName("logo");
                jsonWriter.WriteValue("kds3.0 logo");

                jsonWriter.WritePropertyName("startup_page");
                jsonWriter.WriteValue(ionicCompile.Project.Identity);
                jsonWriter.WritePropertyName("login_page");
                jsonWriter.WriteValue("Login");

                jsonWriter.WritePropertyName("auth_endpoint");
                jsonWriter.WriteValue(frontConfig.ServerUrl);
                #endregion
                jsonWriter.WriteEndObject();

                //获取JSON串
                string output = sw.ToString();
                jsonWriter.Close();
                sw.Close();

                var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
                string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\config", "platform");
                outputPath = HttpUtility.UrlDecode(outputPath);
                var file = Path.Combine(outputPath, "platform.config.ts");
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                string content = string.Format("export const PLATFORM_CONFIG=") + output;
                File.WriteAllText(file, content, System.Text.UTF8Encoding.UTF8);
            }
        }
Beispiel #5
0
        public override void BeginCompile()
        {
            var targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;

            OutputPath = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\projects", this.Project.Identity, "pages");
            OutputPath = HttpUtility.UrlDecode(OutputPath);
            if (!Directory.Exists(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);
            }
        }
        public ModFile[] getContents()
        {
            string[] modStringFiles = Directory.GetFiles(this.folderPath);
            ModFile[] modFiles = new ModFile[modStringFiles.Length];

            for (int i = 0; i < modStringFiles.Length; i++)
            {
                string modFileName = new FileInfo(modStringFiles[i]).Name.ToLower();
                string modFolderName = new DirectoryInfo(this.folderPath).Name.ToLower();
                modFiles[i] = new ModFile(modFolderName, modFileName.Replace(modFolderName, string.Empty));
            }
            return modFiles;
        }
Beispiel #7
0
 private static void SetupDefaultPackage()
 {
     string FileContent = new FileInfo("..\\..\\..\\BatmanPackages\\Batman.MVC.Default.nuspec").Read();
     string CurrentVersion = Regex.Match(FileContent, "<version>(?<VersionNumber>.*)</version>").Groups["VersionNumber"].Value;
     foreach (Match TempMatch in Regex.Matches(FileContent, @"<dependency id=""(?<Dependency>[^""]*)"" version=""(?<VersionNumber>[^""]*)"" />"))
     {
         if (TempMatch.Value.Contains("Batman"))
         {
             FileContent = FileContent.Replace(TempMatch.Value, "<dependency id=\"" + TempMatch.Groups["Dependency"] + "\" version=\"[" + CurrentVersion + "]\" />");
         }
     }
     new FileInfo("..\\..\\..\\BatmanPackages\\Batman.MVC.Default.nuspec").Save(FileContent);
 }
Beispiel #8
0
        public AgDocumentView()
        {
            InitializeComponent();

            string dir = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName;
            ContentArea.Source = new Uri(string.Format("file://{0}/AgHost/AgHost.html", dir.Replace("\\", "/")));

            KaxamlInfo.Frame = null;

            string schemafile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(App.StartupPath + "\\"), Kaxaml.Properties.Settings.Default.AgSchema);
            XmlCompletionDataProvider.LoadSchema(schemafile);

            Parse();
        }
Beispiel #9
0
        static void Main( string[] args )
        {
            var outputDirPath = System.IO.Path.Combine( Application.StartupPath, "Output" );
            if( !Directory.Exists( outputDirPath ) )
            {
                try
                {
                    Directory.CreateDirectory( outputDirPath );
                }
                catch( Exception ex )
                {
                    Console.WriteLine( ex.Message );
                    Console.ReadKey();
                    return;
                }
            }
            foreach( var fn in Directory.GetFiles( Application.StartupPath, "PacketTemplate_*.dll" ) )
            {
                var asm = Assembly.LoadFile( fn );
                var t = Helpers.GetTemplate( asm );
                var shortfn = new FileInfo( fn ).Name;
                shortfn = shortfn.Substring( 0, shortfn.LastIndexOf( '.' ) );
                var path = System.IO.Path.Combine( outputDirPath, shortfn.Replace( ".", "_" ) );
                if( !Directory.Exists( path ) )
                {
                    try
                    {
                        Directory.CreateDirectory( path );
                    }
                    catch( Exception ex )
                    {
                        Console.WriteLine( ex.Message );
                        Console.ReadKey();
                        return;
                    }
                }

                var rtv = GenCPP.Gen( t, path, shortfn.Substring( "PacketTemplate_".Length ) );
                if( rtv != "" )
                {
                    Console.WriteLine( rtv );
                    Console.ReadKey();
                    return;
                }
            }
        }
 public void RollBack(string catalog, string dir1)
 {
     Console.WriteLine("\nВведите дату и время, на которые должен быть осуществлен откат \nВарианты:\n");
     DirectoryInfo FilesTxt = new DirectoryInfo(dir1);
     foreach (var item in FilesTxt.GetFiles("*.txt", SearchOption.AllDirectories))
     {
         Console.WriteLine(" - " + item.LastWriteTime.ToString().Replace(':', '.'));
     }
     string data = Console.ReadLine();
     DirectoryInfo dir2 = Directory.CreateDirectory(@"C:\zzz\rezerv\");
     foreach (var item in FilesTxt.GetFiles("*.txt", SearchOption.AllDirectories))
     {
         if (data == item.LastWriteTime.ToString().Replace(':', '.'))
         {
             string path = dir1 + item.Name;
             FileInfo fi1 = new FileInfo(path);
             fi1.Replace(catalog + item.Name.Substring(20), dir2 + "rezerv" + item.Name);
             Console.WriteLine("Текстовый файл \"{0}\" принял вид, соответсвтующий указанному времени", item.Name);
         }
     }
 }
Beispiel #11
0
        /// <summary>
        /// 生成Module页面HTML
        /// </summary>
        /// <param name="compile"></param>
        /// <param name="doc"></param>
        private void BuildModuleHtml(CompileBase compile, ScreenDefinition screenDef, ProjectDocument doc)
        {
            if (doc.Name.ToLower() == "startuppage")
            {
                var    ionicCompile    = compile as IonicCompile;
                var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
                string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\projects", ionicCompile.Project.Identity);
                outputPath = HttpUtility.UrlDecode(outputPath);
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                //Module页面
                var fileModulePage = Path.Combine(outputPath, ionicCompile.Project.Identity + ".module.ts");
                if (File.Exists(fileModulePage))
                {
                    File.Delete(fileModulePage);
                }
                var contentModulePage = new ModuleTemplate(ionicCompile, doc).TransformText();
                File.WriteAllText(fileModulePage, contentModulePage, System.Text.UTF8Encoding.UTF8);

                //生成Mian页面TS
                var fileMainPage = Path.Combine(outputPath, ionicCompile.Project.Identity + ".ts");
                if (File.Exists(fileMainPage))
                {
                    File.Delete(fileMainPage);
                }
                var contentMainPage = new PageMainTemplate(ionicCompile, screenDef, doc).TransformText();
                File.WriteAllText(fileMainPage, contentMainPage, System.Text.UTF8Encoding.UTF8);
                //生成Mian页面CSS
                var fileMainCss = Path.Combine(outputPath, ionicCompile.Project.Identity + ".scss");
                if (File.Exists(fileMainCss))
                {
                    File.Delete(fileMainCss);
                }
                string contentMainCss = string.Empty;
                File.WriteAllText(fileMainCss, contentMainCss, System.Text.UTF8Encoding.UTF8);
            }
        }
Beispiel #12
0
        public void AddToProject(AddToProjectRequest request)
        {
            if (request.FileName == null || !request.FileName.EndsWith(".cs"))
            {
                return;
            }

            var relativeProject = _solution.ProjectContainingFile(request.FileName);

            if (relativeProject == null || relativeProject is OrphanProject)
            {
                throw new ProjectNotFoundException(string.Format("Unable to find project relative to file {0}", request.FileName));
            }

            var project = relativeProject.AsXml();

            var requestFile = new FileInfo(request.FileName).FullName;
            var projectDirectory = new FileInfo(relativeProject.FileName).Directory;

            var relativeFileName = requestFile.Replace(projectDirectory.FullName, "").Replace("/", @"\").Substring(1);

            var compilationNodes = project.Element(_msBuildNameSpace + "Project")
                                          .Elements(_msBuildNameSpace + "ItemGroup")
                                          .Elements(_msBuildNameSpace + "Compile").ToList();

            var fileAlreadyInProject = compilationNodes.Any(n => n.Attribute("Include").Value.Equals(relativeFileName, StringComparison.InvariantCultureIgnoreCase));

            if (!fileAlreadyInProject)
            {
                var compilationNodeParent = compilationNodes.First().Parent;

                var newFileElement = new XElement(_msBuildNameSpace + "Compile", new XAttribute("Include", relativeFileName));

                compilationNodeParent.Add(newFileElement);
                
                relativeProject.Save(project);
            }
        }
Beispiel #13
0
        /// <summary>
        /// 生成实体对应模型
        /// </summary>
        /// <param name="ionicCompile"></param>
        private void BuildEntityDefinition(IonicCompile ionicCompile)
        {
            var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
            string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\projects", ionicCompile.Project.Identity, "models");

            outputPath = HttpUtility.UrlDecode(outputPath);
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            //生成实体文件
            var entityItems = ionicCompile.ProjectItems.Where(a => a.Value.DocumentType == GlobalIds.DocumentType.Entity).ToList();

            foreach (var entityItem in entityItems)
            {
                ProjectDocument doc  = entityItem.Value as ProjectDocument;
                var             def  = ionicCompile.GetDocumentBody(entityItem.Value) as EntityDefinition;
                var             file = Path.Combine(outputPath, doc.Name + ".ts");
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                string content = new ModelTemplate(ionicCompile, doc, def).TransformText();
                File.WriteAllText(file, content, System.Text.UTF8Encoding.UTF8);
            }
            //生成Container文件
            var ContainerFile = Path.Combine(outputPath, ionicCompile.Project.Identity + ".container.ts");

            if (File.Exists(ContainerFile))
            {
                File.Delete(ContainerFile);
            }
            string Container = new PageContainerTemplate(ionicCompile).TransformText();

            File.WriteAllText(ContainerFile, Container, System.Text.UTF8Encoding.UTF8);
        }
Beispiel #14
0
        /// <summary>
        /// Include a file in a "sFolder" variable.
        /// </summary>
        /// <param name="file">Path of the file to include</param>
        /// <param name="currFolder">Root "sFolder" variable to include it</param>
        /// <param name="pathFolder">Empty string</param>
        /// <param name="relativePath">Path of the first folder where all files and folders are.</param>
        /// <returns></returns>
        public static sFolder Recursive_GetDirectories(string file, sFolder currFolder, string pathFolder, string relativePath)
        {
            String directoryPath = new FileInfo(file).DirectoryName;
            if (directoryPath.Replace(relativePath, "") == pathFolder)
            {
                sFile newFile = new sFile();
                newFile.name = Path.GetFileName(file);
                newFile.offset = 0x00;
                newFile.path = file;
                newFile.size = (uint)new FileInfo(file).Length;

                if (!(currFolder.files is List<sFile>))
                    currFolder.files = new List<sFile>();
                currFolder.files.Add(newFile);
                return currFolder;
            }
            else
            {
                sFolder newFolder = new sFolder(); ;
                if (currFolder.folders is List<sFolder>)
                {
                    string folderName = file.Replace(relativePath + pathFolder, "");
                    folderName = folderName.Substring(1, folderName.Substring(2).IndexOf(Path.DirectorySeparatorChar) + 1);

                    int i;
                    for (i = 0; i < currFolder.folders.Count; i++)
                    {
                        if (currFolder.folders[i].name == folderName)
                        {
                            newFolder = currFolder.folders[i];
                            break;
                        }
                    }

                    if (!(newFolder.name is String))
                        goto Create_Folder;

                    pathFolder += Path.DirectorySeparatorChar + newFolder.name;
                    newFolder = Recursive_GetDirectories(file, newFolder, pathFolder, relativePath);
                    currFolder.folders[i] = newFolder;

                    return currFolder;
                }

            Create_Folder:
                newFolder.name = file.Replace(relativePath + pathFolder, "");
                newFolder.name = newFolder.name.Substring(1, newFolder.name.Substring(2).IndexOf(Path.DirectorySeparatorChar) + 1);
                if (!(currFolder.folders is List<sFolder>))
                    currFolder.folders = new List<sFolder>();

                pathFolder += Path.DirectorySeparatorChar + newFolder.name;
                newFolder = Recursive_GetDirectories(file, newFolder, pathFolder, relativePath);
                currFolder.folders.Add(newFolder);
                return currFolder;
            }
        }
Beispiel #15
0
 private static TypeInfo GetLookupType(string testFileDir)
 {
     var fileName = new FileInfo(testFileDir).Name;
     fileName = fileName.Replace(".cs", "");
     return fileName;
 }
Beispiel #16
0
 private string GetTableNameFromFilePath(string filePath)
 {
     var fileName = new FileInfo(filePath).Name;
     return "dbo." + fileName.Replace(".txt", "");
 }
Beispiel #17
0
        public bool Save()
        {
            FileInfo tmp = new FileInfo(File.FullName + ".tmp");
            try
            {
                tmp.Delete();
                using (FileStream fs = tmp.Create())
                {
                    Serialize(fs, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                try
                {
                    tmp.Delete();
                }
                catch
                {
                }

                return false;
            }

            try
            {
                FileInfo bak = new FileInfo(File.FullName + ".bak");
                bak.Delete();
                if (File.Exists)
                {
                    tmp.Replace(File.FullName, bak.FullName);
                }
                else
                {
                    tmp.MoveTo(File.FullName);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                try
                {
                    tmp.Delete();
                }
                catch
                {
                }

                return false;
            }
        }
Beispiel #18
0
        private void RebuildTitle(int p)
        {
            string OpenedFile = (tabTabs.TabPages[p].Tag as TabInfo).File;

            tabTabs.TabPages[p].Text = (tabTabs.TabPages[p].Tag as TabInfo).TitleFileName;

            if (File.Exists(OpenedFile))
            {
                if ((File.GetAttributes(OpenedFile) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    tabTabs.TabPages[p].Text += " [RO]";

                if (Directory.Exists("Examples"))
                    if (Path.GetFullPath(OpenedFile).Substring(0, Path.GetFullPath("Examples").Length) == Path.GetFullPath("Examples"))
                    {
                        string FileName = new FileInfo(OpenedFile).Name;
                        tabTabs.TabPages[p].Text = "Example: " + FileName.Replace('_', ' ').Substring(0, FileName.Length - 4);

                    }
            }
        }
Beispiel #19
0
        private static void CompressGifs(string sourceDirectory)
        {
            string tempFilePath = Path.GetTempFileName();
            File.Delete(tempFilePath);
            using (var process = new Process())
            {
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;

                int gifsOptimized = 0;
                process.StartInfo.FileName = Path.Combine(Environment.CurrentDirectory, "gifsicle.exe");
                if (!File.Exists(process.StartInfo.FileName))
                {
                    Console.WriteLine("Missing gifsicle.exe in current directory.");
                    return;
                }
                Console.WriteLine();
                foreach (var sourceFilePath in Directory.EnumerateFiles(sourceDirectory, "*.gif", SearchOption.AllDirectories))
                {
                    string trimmedSourcePath = sourceFilePath.Replace(sourceDirectory, "");
                    ConsoleReplacePreviousLine("Optimizing " + trimmedSourcePath);
                    bool optimized = false;
                    bool optimizedOnPass;
                    do
                    {
                        optimizedOnPass = false;
                        FileInfo sourceFile = new FileInfo(sourceFilePath);
                        sourceFile.CopyTo(tempFilePath, true);
                        process.StartInfo.Arguments =
                            "-b -O3 --no-comments --no-extensions --no-names \"" + tempFilePath + "\"";
                        process.Start();
                        process.WaitForExit();
                        if (process.ExitCode != 0)
                        {
                            Console.WriteLine("gifsicle exited with code " + process.ExitCode + " for " + trimmedSourcePath);
                            Console.WriteLine();
                        }
                        else
                        {
                            FileInfo tempFile = new FileInfo(tempFilePath);
                            if (tempFile.Length < sourceFile.Length)
                            {
                                Console.WriteLine(
                                    "Optimized " + sourceFile.Length + " to " + tempFile.Length + " for " + trimmedSourcePath);
                                RetryActionWithDelay(() => tempFile.Replace(sourceFilePath, null), 3, TimeSpan.FromSeconds(0.5));
                                optimizedOnPass = true;
                                optimized = true;
                            }
                        }
                    } while (optimizedOnPass);
                    if (optimized)
                    {
                        Console.WriteLine();
                        gifsOptimized++;
                    }
                }
                if (File.Exists(tempFilePath))
                    File.Delete(tempFilePath);
                ConsoleReplacePreviousLine(gifsOptimized + " GIFs optimized.");
            }
        }
Beispiel #20
0
		public void Replace1_Source_FileNotFound ()
		{
			string path1 = TempFolder + DSC + "FIT.Replace.Source.Test";
			string path2 = TempFolder + DSC + "FIT.Replace.Dest.Test";
			DeleteFile (path2);

			try {
				try {
					File.Create (path2).Close ();
					FileInfo info = new FileInfo (path1);
					info.Replace (path2, null);
					Assert.Fail ("#1");
				} catch (FileNotFoundException ex) {
					Assert.AreEqual (typeof (FileNotFoundException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
				}
			} finally {
				DeleteFile (path2);			
			}		
		}
        public void Replace_WhereParentIsRoot_CallsApiCorrectly()
        {
            var fixture = DokanOperationsFixture.Instance;

            string path = DokanOperationsFixture.FileName.AsRootedPath(),
                destinationPath = DokanOperationsFixture.DestinationFileName.AsRootedPath(),
                destinationBackupPath = DokanOperationsFixture.DestinationBackupFileName.AsRootedPath();
#if LOGONLY
            fixture.SetupAny();
#else
            fixture.SetupCreateFile(destinationPath, ReplaceAccess | FileAccess.Reserved, ReadWriteShare, FileMode.Open, OpenReparsePointOptions);
            fixture.SetupCreateFileWithoutCleanup(destinationPath, ReplaceAccess, ReadWriteShare, FileMode.Open, OpenReparsePointOptions);
            fixture.SetupCreateFileWithoutCleanup(path, SetOwnershipAccess, WriteShare, FileMode.Open, FileOptions.None);
            fixture.SetupGetFileInformation(destinationPath, FileAttributes.Normal);
            fixture.SetupGetFileInformation(path, FileAttributes.Normal);
            fixture.SetupSetFileAttributes(path, FileAttributes.Normal);
            fixture.SetupSetFileTime(path);
            fixture.SetupGetVolumeInformation(DokanOperationsFixture.VOLUME_LABEL, DokanOperationsFixture.FILESYSTEM_NAME);
            fixture.SetupFindStreams(destinationPath, new FileInformation[0]);
            // WARNING: This is probably an error in the Dokan driver!
            fixture.SetupOpenDirectoryWithoutCleanup(string.Empty, WriteDirectoryAccess, FileShare.ReadWrite);
            fixture.SetupMoveFile(destinationPath, destinationBackupPath, true);
            fixture.SetupMoveFile(path, destinationPath, true);
#endif

            var sut = new FileInfo(DokanOperationsFixture.FileName.AsDriveBasedPath());

            sut.Replace(DokanOperationsFixture.DestinationFileName.AsDriveBasedPath(), DokanOperationsFixture.DestinationBackupFileName.AsDriveBasedPath());

#if !LOGONLY
            fixture.VerifyAll();
#endif
        }
Beispiel #22
0
        public void Replace_WhereParentIsDirectory_CallsApiCorrectly()
        {
            var fixture = DokanOperationsFixture.Instance;

            string origin = Path.Combine(DokanOperationsFixture.DirectoryName, DokanOperationsFixture.FileName),
                destination = Path.Combine(DokanOperationsFixture.DestinationDirectoryName, DokanOperationsFixture.DestinationFileName),
                destinationBackup = Path.Combine(DokanOperationsFixture.DestinationDirectoryName, DokanOperationsFixture.DestinationBackupFileName),
                path = origin.AsRootedPath(),
                destinationPath = destination.AsRootedPath(),
                destinationBackupPath = destinationBackup.AsRootedPath();
#if LOGONLY
            fixture.SetupAny();
#else
            fixture.SetupCreateFile(destinationPath, ReplaceAccess | FileAccess.Reserved, ReadWriteShare, FileMode.Open);
            fixture.SetupCreateFileWithoutCleanup(destinationPath, ReplaceAccess, ReadWriteShare, FileMode.Open);
            fixture.SetupCreateFileWithoutCleanup(path, SetOwnershipAccess, WriteShare, FileMode.Open);
            fixture.SetupGetFileInformation(destinationPath, FileAttributes.Normal);
            fixture.SetupGetFileInformation(path, FileAttributes.Normal);
            fixture.SetupSetFileAttributes(path, FileAttributes.Normal);
            fixture.SetupSetFileTime(path);
            fixture.SetupGetVolumeInformation(DokanOperationsFixture.VOLUME_LABEL, DokanOperationsFixture.FILESYSTEM_NAME);
            fixture.SetupEnumerateNamedStreams(destinationPath, string.Empty);
            fixture.SetupOpenDirectoryWithoutCleanup(DokanOperationsFixture.DestinationDirectoryName.AsRootedPath());
            fixture.SetupMoveFile(destinationPath, destinationBackupPath, true);
            fixture.SetupCleanupFile(destinationBackupPath);
            // WARNING: This is probably an error in the Dokan driver!
            fixture.SetupCloseFile(destinationBackupPath, /* This call is probably redundant. */isDirectory: true);
            fixture.SetupMoveFile(path, destinationPath, true);
            fixture.SetupCleanupFile(destinationPath);
            // WARNING: This is probably an error in the Dokan driver!
            fixture.SetupCloseFile(destinationPath, /* This call is probably redundant. */isDirectory: true);
#endif

            var sut = new FileInfo(origin.AsDriveBasedPath());

            sut.Replace(destination.AsDriveBasedPath(), destinationBackup.AsDriveBasedPath());

#if !LOGONLY
            fixture.VerifyAll();
#endif
        }
Beispiel #23
0
		public void Replace1_DestFileName_WhiteSpace ()
		{
			string path1 = TempFolder + DSC + "FIT.Replace.Source.Test";
			DeleteFile (path1);
			try {
				try {
					File.Create (path1).Close ();
					FileInfo info = new FileInfo (path1);
					info.Replace ("     ", null);
					Assert.Fail ("#1");
				} catch (ArgumentException ex) {
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
				}
			} finally {
				DeleteFile (path1);
			}
		}
    public static void UnpackDirectory(string sourcePath_, string unpackToThisDirectory_, string processedDirectory_, string errorDirectory_, string noMetaDirectory_,  bool recurse_, bool processFile_=true)
    {
      if (!Directory.Exists(sourcePath_))
        return;

      foreach(var zipPath in Directory.GetFiles(sourcePath_,"*.gz"))
      {
        var fileName = new FileInfo(zipPath).Name;
        var csvFileName = fileName.Replace(".gz", string.Empty);

        var unpackPath = string.Format(@"{0}\{1}", unpackToThisDirectory_, csvFileName);

        var buffer = new byte[2048];
        int n=1;
        Logger.Debug(string.Format("Unpacking {0}", new FileInfo(fileName).Name), typeof(FuturesIntradaySaver));

        try
        {
          if (!File.Exists(unpackPath))
          {
            using (var input = File.OpenRead(zipPath))
            {
              using (var decompressor = new GZipStream(input, CompressionMode.Decompress, true))
              {
                using (var output = File.Create(unpackPath))
                {
                  do
                  {
                    n = decompressor.Read(buffer, 0, buffer.Length);
                    if (n > 0) output.Write(buffer, 0, n);
                  }
                  while (n > 0);
                }
              }
            }
          }

          if(processFile_)
            processFile(unpackPath, processedDirectory_, errorDirectory_, noMetaDirectory_);
        }
        catch (Exception ex_)
        {
          Logger.Error( string.Format("Error processing file {0}. error: {1}{2}", fileName, ex_.Message, ex_.StackTrace),typeof(FuturesIntradaySaver));

          string errorPath = string.Format(@"{0}\{1}", errorDirectory_, csvFileName);

          if (processFile_ && File.Exists(unpackPath)) File.Move(unpackPath, errorPath);
        }
      }

      if(recurse_)
        foreach (var dir in Directory.GetDirectories(sourcePath_))
          UnpackDirectory(dir, unpackToThisDirectory_, processedDirectory_, errorDirectory_, noMetaDirectory_, recurse_,
            processFile_);
    }
Beispiel #25
0
        public void IsReady2(Dictionary<int, string>  outputFileValues, eDoctrinaOcrEd.BubblesAreaControl bac, List<eDoctrinaOcrEd.BarCodeControl> barCodeControls)
        {
            var barCodes = "";
            System.Windows.Forms.CheckBox chb = bac.CheckBoxArr[0];
            var tag = chb.Tag;
            RecognitionTools.Bubble[] currentLineBubbles = new RecognitionTools.Bubble[0];
            RecognitionTools.Bubble bubble2 = (RecognitionTools.Bubble)tag;
            int currentLine = bubble2.point.Y;
            int[] subStrSet = new int[areas[0].subLinesAmount];
            totalOutput[answersPosition - 1] = new string[0];
            subStrSet = new int[areas[bubble2.areaNumber].subLinesAmount];

            for (int k = 0; k < bac.CheckBoxArr.Length; k++)
            {
                chb = bac.CheckBoxArr[k];
                bubble2 = (RecognitionTools.Bubble)tag;
                //totalOutput[answersPosition][0] = ;
                if (bubble2.point.Y == currentLine)
                {
                    if (chb.Checked)
                    {
                        Array.Resize(ref currentLineBubbles, currentLineBubbles.Length + 1);
                        currentLineBubbles[currentLineBubbles.Length - 1] = bubble2;
                    }
                    if (k < bac.CheckBoxArr.Length - 1)
                    {
                        continue;
                    }
                }
                if (currentLineBubbles.Length == 0)
                {
                    if (subStrSet.Length > 0 && areas[bubble2.areaNumber].bubblesFormat == "multiple")
                    {
                        for (int n = 0; n < subStrSet.Length; n++)
                        {
                            subStrSet[n] = n;
                            RecognitionTools.AppendOutput(ref totalOutput, answersPosition, "~", indexAnswersPosition, indexOfFirstBubble);
                        }
                    }
                    else
                    {
                        RecognitionTools.AppendOutput(ref totalOutput, answersPosition, "", indexAnswersPosition, indexOfFirstBubble);
                    }
                }
                else
                {
                    for (int j = 0; j < currentLineBubbles.Length; j++)
                    {
                        RecognitionTools.Bubble b2 = currentLineBubbles[j];
                        KeyValuePair<RecognitionTools.Bubble, double> item1 = new KeyValuePair<RecognitionTools.Bubble, double>(b2, 0);
                        RecognitionTools.AppendOutput(ref totalOutput, answersPosition, indexAnswersPosition, item1
                                       , j, ref subStrSet, areas[item1.Key.areaNumber], bubblesPerLine[b2.areaNumber], indexOfFirstBubble);
                    }
                }
                if (k < bac.CheckBoxArr.Length - 1)
                {
                    Array.Resize(ref currentLineBubbles, 0);
                    currentLine = bubble2.point.Y;
                    RecognitionTools.AppendOutput(ref totalOutput, indexAnswersPosition, currentLine.ToString(), indexAnswersPosition, indexOfFirstBubble);
                    subStrSet = new int[areas[bubble2.areaNumber].subLinesAmount];
                    k--;
                }
            }
            try
            {
                string[] str = totalOutput[indexAnswersPosition - 1] as string[];
                int first = Convert.ToInt32(str[0]);
                if (first != indexOfFirstQuestion)
                {
                    for (int k = 0; k < str.Length; k++)
                    {
                        str[k] = (indexOfFirstQuestion + k).ToString();
                    }
                    totalOutput[indexAnswersPosition - 1] = str;
                }
            }
            catch (Exception) { }
            var direct = Defaults.ManualSuccessFolder;
            foreach (KeyValuePair<int, string> item in outputFileValues)
            {
                if (item.Key > totalOutput.Length)
                {
                    Array.Resize(ref totalOutput, item.Key);
                }
                totalOutput[item.Key - 1] = item.Value;
            }
            for (int num = 0; num < regions.regions.Length; num++)
            {
                string type = regions.regions[num].type;
                bool? active = regions.regions[num].active;
                string name = regions.regions[num].name;

                if (active == false || type == "marker" || name == "sheetIdentifier")
                {
                    continue;
                }
                regionOutputPosition = regions.regions[num].outputPosition;
                if (regionOutputPosition > 0)
                {
                    foreach (var item in barCodeControls)
                    {
                        if (item.Name == name)
                        {
                            headersValues[regionOutputPosition - 1] = item.barCodeValue;
                            totalOutput[regionOutputPosition - 1] = item.barCodeValue;
                            break;
                        }
                    }
                }
            }
            string outputFileNameFormat = "";
            if (regions != null)
            {
                outputFileNameFormat = regions.outputFileNameFormat;
            }
            for (int k = 0; k < allBarCodeNames.Length; k++)
            {
                int index = Array.IndexOf(headers, allBarCodeNames[k]);
                if (index >= 0)
                {
                    if (outputFileValues.Keys.Contains(k))
                    {
                        allBarCodeValues[k] = outputFileValues[k];
                    }
                }
                outputFileNameFormat = outputFileNameFormat.Replace
                    ("{" + allBarCodeNames[k] + "}", allBarCodeValues[k]);
            }
            var destFileName = direct + "\\" + outputFileNameFormat + ".csv";
            Utils.CreateDirectory(direct);
            destFileName = destFileName.Replace(@"\\", @"\");
            destFileName = Utils.GetNextFileName(destFileName);

            string destFileNameTiff;
            destFileNameTiff = Utils.GetNextFileName(direct + "\\" + outputFileNameFormat + ".tiff");
            //b.Save(destFileNameTiff, ImageFormat.Tiff);
            destFileNameTiff = destFileNameTiff.Replace(@"\\", @"\");
            repeat: try
            {
                File.Move(FileName, destFileNameTiff);
            }
            catch (Exception ex)
            {
                goto repeat;
            }
            var currentFileName = destFileNameTiff;
            var fi = new FileInfo(FileName);
            var fn1 = new FileInfo(FileName).Name;
            var fn2 = fn1.Replace(new FileInfo(FileName).Extension, ".audit");
            Utils.DeleteFile(Defaults.TempEdFolder + "\\" + fn2);
            StringBuilder[] sb = new StringBuilder[1];
            RecognitionTools.WriteCsv(false, destFileName, barCodesPrompt, sb, totalOutput
                 , answersPosition, indexAnswersPosition, additionalOutputData, barCodes);
        }
Beispiel #26
0
        public void TestFilePath()
        {
            var q = _fileInfo.FilePath;

            var exp = new FileInfo(_testFilePath1.FullName).FullName;

            Assert.AreEqual(exp.Replace("\\", "/"), q);
        }
Beispiel #27
0
 protected string GetTestHTMLPathLocation()
 {
     var file = new FileInfo(Path.Combine(@"..\..\", TestPage)).FullName;
     return "file:///" + file.Replace('\\', '/');
 }
Beispiel #28
0
 protected static string TestHtmlPathLocation(string testPage)
 {
     var file = new FileInfo(Path.Combine(@"..\..\", testPage)).FullName;
     return "file:///" + file.Replace('\\', '/');
 }
        public void Replace_WhereParentIsDirectory_CallsApiCorrectly()
        {
            var fixture = DokanOperationsFixture.Instance;

            string origin = Path.Combine(fixture.DirectoryName, fixture.FileName),
                destination = Path.Combine(fixture.DestinationDirectoryName, fixture.DestinationFileName),
                destinationBackup = Path.Combine(fixture.DestinationDirectoryName, fixture.DestinationBackupFileName),
                path = origin.AsRootedPath(),
                destinationPath = destination.AsRootedPath(),
                destinationBackupPath = destinationBackup.AsRootedPath();
#if LOGONLY
            fixture.SetupAny();
#else
            fixture.ExpectCreateFile(destinationPath, ReplaceAccess | FileAccess.Reserved, ReadWriteShare, FileMode.Open);
            fixture.ExpectCreateFileWithoutCleanup(destinationPath, ReplaceAccess, ReadWriteShare, FileMode.Open);
            fixture.ExpectCreateFileWithoutCleanup(path, SetOwnershipAccess, WriteShare, FileMode.Open, FileOptions.None);
            fixture.ExpectGetFileInformation(destinationPath, FileAttributes.Normal);
            fixture.ExpectGetFileInformation(path, FileAttributes.Normal);
            fixture.ExpectSetFileAttributes(path, FileAttributes.Normal);
            fixture.ExpectSetFileTime(path);
            fixture.ExpectGetVolumeInformation(DokanOperationsFixture.VOLUME_LABEL, DokanOperationsFixture.FILESYSTEM_NAME);
            fixture.ExpectFindStreams(destinationPath, new FileInformation[0]);
            fixture.PermitGetFileInformationToFail(destinationBackupPath, FileAttributes.Normal, NtStatus.ObjectPathNotFound, true);
            fixture.PermitOpenDirectory(fixture.DestinationDirectoryName.AsRootedPath(), ReadDirectoryAccess, ReadWriteShare, attributes: FileAttributes.Normal);
            fixture.ExpectOpenDirectoryWithoutCleanup(fixture.DestinationDirectoryName.AsRootedPath(), WriteDirectoryAccess, FileShare.ReadWrite);
            fixture.ExpectMoveFile(destinationPath, destinationBackupPath, true);
            fixture.PermitGetFileInformation(destinationBackupPath, FileAttributes.Normal, false);
            fixture.ExpectMoveFile(path, destinationPath, true);
#endif

            var sut = new FileInfo(origin.AsDriveBasedPath());

            sut.Replace(destination.AsDriveBasedPath(), destinationBackup.AsDriveBasedPath());

#if !LOGONLY
            fixture.Verify();
#endif
        }
Beispiel #30
0
		public void Replace1_DestFileName_IsReadOnly ()
		{
			string path1 = TempFolder + DSC + "FIT.Replace.Source.Test";
			string path2 = TempFolder + DSC + "FIT.Replace.Dest.Test";
			DeleteFile (path1);
			DeleteFile (path2);

			try {
				try {
					File.Create (path1).Close ();
					File.Create (path2).Close ();
					File.SetAttributes (path2, FileAttributes.ReadOnly);
					FileInfo info = new FileInfo (path1);
					info.Replace (path2, null);
					Assert.Fail ("#1");
				} catch (UnauthorizedAccessException ex) {
					Assert.AreEqual (typeof (UnauthorizedAccessException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
				}
			} finally {
				File.SetAttributes (path2, FileAttributes.Normal);
				DeleteFile (path1);
				DeleteFile (path2);			
			}
		}
 private string[] ordernarArchivos(string[] archivos)
 {
     int[] names = new int[archivos.Length];
     Dictionary<int, string> Name_Path = new Dictionary<int, string>();
     string fname;
     for (int i = 0; i < archivos.Length; i++)
     {
         fname = new FileInfo(archivos[i]).Name;
         names[i] = int.Parse(fname.Replace(".pdf", ""));
         Name_Path.Add(names[i], archivos[i]);
     }
     Array.Sort(names);
     for (int i = 0; i < names.Length; i++)
     {
         archivos[i] = Name_Path[names[i]];
     }
     return archivos;
 }
Beispiel #32
0
		public void Replace1_Backup_Null ()
		{
			string path1 = TempFolder + DSC + "FIT.Replace.Source.Test";
			string path2 = TempFolder + DSC + "FIT.Replace.Dest.Test";
			
			DeleteFile (path1);
			DeleteFile (path2);
			try {
				File.Create (path1).Close ();
				File.Create (path2).Close ();
				FileInfo info = new FileInfo (path1);
				Assert.IsTrue (info.Exists, "#1");
				FileInfo info2 = info.Replace (path2, null);
				Assert.IsTrue (info2.Exists, "#2");
				info = new FileInfo (path1);
				Assert.IsFalse (info.Exists, "#3");				
			} finally {
				DeleteFile (path2);
			} 
		}
        public void LoadFile()
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "Word Documents|*.doc;*.docx";
            file.FilterIndex = 1;

            file.ShowDialog();
            string str = new FileInfo(file.FileName).Name;
            str = str.Replace(" ", string.Empty);
            Repository.Path = Path.Combine("../../Data/DBDocs", str);
            string dir = new FileInfo(Repository.Path).DirectoryName;
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            File.Copy(file.FileName, Repository.Path);
            Repository.Size = new FileInfo(Repository.Path).Length / 1024;
        }
Beispiel #34
0
		public void Replace1_DestFileName_InvalidPathChars ()
		{
			string path1 = TempFolder + DSC + "FIT.Replace.Source.Test";
			string path2 = string.Empty;
			DeleteFile (path1);

			try {
				File.Create (path1).Close ();
				FileInfo info = new FileInfo (path1);
				foreach (char c in Path.InvalidPathChars)
					path2 += c;
				try {
					info.Replace (path2, null);
					Assert.Fail ("#1");
				} catch (ArgumentException ex) {
					// Illegal characters in path
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
					Assert.IsNull (ex.ParamName, "#5");
				}
			} finally {
				DeleteFile (path1);
			}
		}
Beispiel #35
0
        private void ExportArchivesForWorldspaceProject()
        {
            string[] archiveFilePaths = Directory.GetDirectories(_loadedWorldspaceProject.ProjectFilePath);
            foreach (string filePath in archiveFilePaths)
            {
                string arcPackerFileName = Path.Combine(Application.StartupPath, "ExternalTools/arcPack.exe");
                string yazCompressFileName = Path.Combine(Application.StartupPath, "ExternalTools/yaz0enc.exe");

                //We're going to archive all of the folders in the project dir, under the assumption that people
                //haven't been f*****g around with them manually. >:|
                Console.WriteLine("Invoking external tool arcPack on {0}", filePath);
                ProcessStartInfo arcPack = new ProcessStartInfo(arcPackerFileName);
                arcPack.WindowStyle = ProcessWindowStyle.Hidden;
                arcPack.Arguments = "\"" + filePath + "\"";
                Process.Start(arcPack);


                string fileName = Path.GetFileNameWithoutExtension(filePath);
                if (fileName.ToLower() == "stage")
                {
                    System.Threading.Thread.Sleep(100);
                    Console.WriteLine("Invoking external tool yaz0enc on {0}", filePath);
                    ProcessStartInfo yazCompress = new ProcessStartInfo(yazCompressFileName);
                    yazCompress.WindowStyle = ProcessWindowStyle.Hidden;
                    yazCompress.Arguments = "\"" + filePath + ".arc\"";
                    Process.Start(yazCompress);
                }
            }

            //Wait for all of the archiving processes to finish.
            Process[] archiveProcesses = Process.GetProcessesByName("arcPack");
            if (archiveProcesses.Length > 0)
            {
                Console.WriteLine("Archives still being created, waiting...");
                while (archiveProcesses.Length > 0)
                {
                    System.Threading.Thread.Sleep(100);
                    archiveProcesses = Process.GetProcessesByName("arcPack");
                }
                Console.WriteLine("arcPack processes complete.");
            }


            //We're going to delete the old Stage.arc and rename the Yaz0 compressed one for easier/less confusing inclusion.
            string stageFilePath = Path.Combine(_loadedWorldspaceProject.ProjectFilePath, "Stage.arc");
            string compressedStageFilePath = stageFilePath + ".yaz0";
            if (File.Exists(stageFilePath) && File.Exists(compressedStageFilePath))
            {
                Process[] processes = Process.GetProcessesByName("yaz0enc");
                if (processes.Length > 0)
                {
                    Console.WriteLine("Stage.arc is still being compressed, waiting...");
                    while (!processes[0].HasExited)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    Console.WriteLine("yaz0enc compression complete. Replacing Stage.arc with compressed file.");
                }

                FileInfo fInfo = new FileInfo(stageFilePath);
                fInfo.Replace(compressedStageFilePath, null);
            }

            Console.WriteLine("Project Export completed.");
        }