Exemple #1
0
        /*----< test moving file to category folder >------------------*/

        public bool testAddFile(FileName srcFile, DirName category)
        {
            TestUtilities.vbtitle("testing addFile");
            FileName dstFile     = srcFile;
            FileSpec srcFileSpec = storage.stagingFilePath(srcFile);

            srcFileSpec = Path.GetFullPath(srcFileSpec);

            bool test;

            if (!File.Exists(srcFileSpec))
            {
                test = TestUtilities.handleInvoke(
                    () => {
                    var tempFile = File.Create(srcFileSpec);
                    tempFile.Close();
                    return(true);
                }
                    );
            }

            TestUtilities.putLine(string.Format("adding file \"{0}\" to category \"{1}\"", srcFile, category));

            test = TestUtilities.handleInvoke(
                () => { return(storage.addFile(category, srcFile)); }
                );

            TestUtilities.checkResult(test, "Storage.testAddFile");
            return(test);
        }
Exemple #2
0
        internal static void ContainsFile(AnnoRDA.Folder folder, FileSpec fileSpec)
        {
            if (fileSpec == null)
            {
                throw new ArgumentNullException("fileSpec");
            }

            IEnumerable <string> folderPath;
            string fileName = fileSpec.Path.SplitOffLast(out folderPath);

            AnnoRDA.Folder subFolder = folderPath.Any() ? ContainsFolder(folder, folderPath, Enumerable.Empty <string>()) : folder;
            if (subFolder == null)
            {
                throw new Xunit.Sdk.AssertActualExpectedException(
                          String.Join(PathSeparator, folderPath),
                          folder,
                          "Assert.ContainsFile() Failure",
                          "Folder not found",
                          "In value"
                          );
            }
            else
            {
                AnnoRDA.File file = subFolder.Files.FirstOrDefault((f) => f.Name == fileName);
                FileMatches(fileSpec, file, folder);
            }
        }
Exemple #3
0
        public void RevertFile()
        {
            if (System.IO.File.Exists(editFilePath))
            {
                connected = con.Connect(null);
                if (connected)
                {
                    try
                    {
                        FileSpec rivertFile    = new FileSpec(new LocalPath(editFilePath));
                        Options  rivertOptions = new Options();
                        p4.Connection.Client.RevertFiles(rivertOptions, new FileSpec[] { rivertFile });

                        EnableFileEdit();

                        Console.WriteLine("The file is reverted!");
                    }
                    catch (P4Exception e)
                    {
                        MessageBox.Show("リバートに失敗しました。");
                        Console.WriteLine("Couldn't revert file!\n {0} : {1}", e.ErrorCode, e.Message);
                    }
                }
                else
                {
                    MessageBox.Show("ワークスペースに正しく接続できているか確認してください。");
                }
            }
            else
            {
                MessageBox.Show("指定ファイルが存在しません。");
            }
        }
Exemple #4
0
        public void SubmitOptionsNoneTest()
        {
            bool unicode = false;

            string uri       = "localhost:6666";
            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";


            for (int i = 0; i < 1; i++) // run once for ascii, once for unicode
            {
                Process p4d    = Utilities.DeployP4TestServer(TestDir, 6, unicode);
                Server  server = new Server(new ServerAddress(uri));
                try
                {
                    Repository rep = new Repository(server);

                    using (Connection con = rep.Connection)
                    {
                        con.UserName    = user;
                        con.Client      = new Client();
                        con.Client.Name = ws_client;
                        Assert.AreEqual(con.Status, ConnectionStatus.Disconnected);

                        Assert.AreEqual(con.Server.State, ServerState.Unknown);

                        Assert.IsTrue(con.Connect(null));

                        Assert.AreEqual(con.Server.State, ServerState.Online);

                        Assert.AreEqual(con.Status, ConnectionStatus.Connected);

                        Assert.AreEqual("admin", con.Client.OwnerName);
                        Utilities.SetClientRoot(rep, TestDir, unicode, ws_client);

                        Changelist change = new Changelist(5, true);
                        change.initialize(con);

                        SubmitCmdOptions submitOptions = new SubmitCmdOptions(Perforce.P4.SubmitFilesCmdFlags.None, 5, null, null, null);
                        SubmitResults    sr            = change.Submit(submitOptions);

                        FileSpec             fs       = FileSpec.DepotSpec("//depot/MyCode/NewFile.txt");
                        Options              ops      = new Options();
                        IList <FileMetaData> actual   = rep.GetFileMetaData(ops, fs);
                        FileAction           expected = FileAction.None;
                        Assert.AreEqual(expected, actual[0].Action);

                        Assert.IsNotNull(sr);
                        Assert.AreEqual(1, sr.Files.Count);
                    }
                }
                finally
                {
                    Utilities.RemoveTestServer(p4d, TestDir);
                }
                unicode = !unicode;
            }
        }
Exemple #5
0
        public bool testComponent()
        {
            TestUtilities.title("Testing FileNameEditor", '=');
            TestUtilities.putLine();

            TestUtilities.title("Testing extension edits");
            FileName fileName  = "SomeFile.cs.2";
            FileName test1Name = addXmlExt(fileName);
            bool     t1        = test1Name.Contains(".xml");

            showResult(t1, test1Name, "addXmlExt");

            FileName test2Name = removeXmlExt(test1Name);
            bool     t2        = test2Name == fileName;

            showResult(t2, test2Name, "removeXmlExt");

            FileName test3Name = removeXmlExt(test2Name);
            bool     t3        = test3Name == fileName;

            showResult(t3, test3Name, "removeXmlExt");
            TestUtilities.putLine();

            TestUtilities.title("Testing path construction");
            DirName stagingdir  = "Fawcett";
            FullDir stagingpath = stagingPath(stagingdir);
            bool    t4          = (stagingpath.Contains("C:/") || stagingpath.Contains("../")) && stagingpath.Contains(stagingdir);

            showResult(t4, stagingpath, "stagingPath");

            DirName category    = "SomeCategory";
            FullDir storagepath = storagePath(category);
            bool    t5          = (storagepath.Contains("C:/") || storagepath.Contains("../")) && storagepath.Contains(category);

            showResult(t5, storagepath, "storagePath");

            FileName someFileName = "someFileName";
            FileSpec filespec     = fileSpec(storagepath, someFileName);
            bool     t6           = filespec.Contains("/someFileName");

            showResult(t6, filespec, "fileSpec");

            FileRef fileref = storageFolderRef(filespec);
            bool    t7      = fileref.IndexOf('/') == fileref.LastIndexOf('/');

            showResult(t7, fileref, "storageFolderRef");

            DirName cat = extractCategory(fileref);
            bool    t8  = cat == category;

            showResult(t8, cat, "extractCategory");

            FileName file = extractFileName(fileref);
            bool     t9   = file == someFileName;

            showResult(t8, file, "extractFileName");

            return(t1 && t2 && t3 && t4 && t5 && t6 && t7 && t8 && t9);
        }
Exemple #6
0
        public void FileTest()
        {
            FileAnnotation target   = new FileAnnotation(new FileSpec(new DepotPath("//depot/annotate.txt"), null), "this is the line");
            FileSpec       expected = new FileSpec(new DepotPath("//depot/annotate.txt"), null, null, null);
            FileSpec       actual   = target.File;

            Assert.AreEqual(expected, actual);
        }
Exemple #7
0
 internal static void ContainsFile(AnnoRDA.FileSystem fileSystem, FileSpec fileSpec)
 {
     if (fileSystem == null)
     {
         throw new ArgumentNullException("fileSystem");
     }
     ContainsFile(fileSystem.Root, fileSpec);
 }
 internal static string GetItemName(PendingChange pendingChange, bool useServerPath)
 {
     if (useServerPath || string.IsNullOrEmpty(pendingChange.LocalItem))
     {
         return(VersionControlPath.GetFileName(pendingChange.ServerItem));
     }
     return(FileSpec.GetFileName(pendingChange.LocalItem));
 }
 public ImageFileSpec(FileSpec fileSpec, FileSpecFormat fileSpecFormat, uint pixelLength, string containerName)
 {
     FileSpec            = fileSpec;
     FileSpecFormat      = fileSpecFormat;
     PixelLength         = pixelLength;
     InterpolationFilter = InterpolationFilter.Robidoux;
     ContainerName       = containerName;
 }
Exemple #10
0
 protected bool GetFileSpecifications()
 {
     using (Operation engineOp = L.Begin("Scanning directory for file specification"))
     {
         if (Directory.Exists(BaseDirectory))
         {
             BaseDirectoryInfo = new DirectoryInfo(BaseDirectory);
             BaseDirectory     = BaseDirectoryInfo.FullName;
         }
         else
         {
             L.Error("The base directory {0} could not be found.", BaseDirectory);
             return(false);
         }
         CompilerArguments = PhpCommandLineParser.Default.Parse(FileSpec.ToArray(), BaseDirectory, RuntimeEnvironment.GetRuntimeDirectory(),
                                                                Environment.ExpandEnvironmentVariables(@"%windir%\Microsoft.NET\assembly\GAC_MSIL"));
         FileCount = CompilerArguments.SourceFiles.Count();
         if (FileCount == 0)
         {
             L.Error("No PHP source files match specification {files} in directory {dir}.", FileSpec, BaseDirectory);
             return(false);
         }
         else
         {
             Files          = CompilerArguments.SourceFiles.ToArray();
             FilesPathIndex = Files.Select((v, i) => new { v, i }).ToDictionary((f) => f.v.Path, (f) => f.i);
         }
         if (TargetFileSpec != null && TargetFileSpec.Count() > 0)
         {
             CommandLineArguments targetFilesArgs = PhpCommandLineParser.Default.Parse(TargetFileSpec.ToArray(), BaseDirectory, RuntimeEnvironment.GetRuntimeDirectory(),
                                                                                       Environment.ExpandEnvironmentVariables(@"%windir%\Microsoft.NET\assembly\GAC_MSIL"));
             TargetFilePaths = new HashSet <string>(targetFilesArgs.SourceFiles.Select(f => f.Path));
             if (TargetFilePaths.Count() == 0)
             {
                 L.Error("No PHP source files match target specification {files} in directory {dir}.", TargetFileSpec, Compiler.Arguments.BaseDirectory);
                 return(false);
             }
             else
             {
                 List <int> targetFileIndex = new List <int>(TargetFilePaths.Count);
                 for (int i = 0; i < FileCount; i++)
                 {
                     if (TargetFilePaths.Contains(Files[i].Path))
                     {
                         targetFileIndex.Add(i);
                     }
                 }
                 TargetFileIndex = targetFileIndex.ToArray();
             }
         }
         else
         {
             TargetFileIndex = Enumerable.Range(0, FileCount).ToArray();
         }
         engineOp.Complete();
         return(true);
     }
 }
Exemple #11
0
 protected GotoNonLocal(
     Document context,
     PdfName actionType,
     FileSpec fileSpec,
     T destination
     ) : base(context, actionType, destination)
 {
     FileSpec = fileSpec;
 }
        public void SubmitShelvedFromChangelist()
        {
            bool unicode = false;

            string uri       = "localhost:6666";
            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";

            for (int i = 0; i < 2; i++) // run once for ascii, once for unicode
            {
                Process p4d    = Utilities.DeployP4TestServer(TestDir, 13, unicode);
                Server  server = new Server(new ServerAddress(uri));
                try
                {
                    Repository rep = new Repository(server);

                    using (Connection con = rep.Connection)
                    {
                        con.UserName    = user;
                        con.Client      = new Client();
                        con.Client.Name = ws_client;

                        bool connected = con.Connect(null);
                        Assert.IsTrue(connected);
                        Assert.AreEqual(con.Status, ConnectionStatus.Connected);
                        Utilities.SetClientRoot(rep, TestDir, unicode, ws_client);

                        Changelist change = new Changelist(5, true);
                        change.initialize(con);

                        // shelve the files in changelist 5
                        con.Client.ShelveFiles(new ShelveFilesCmdOptions(ShelveFilesCmdFlags.None,
                                                                         null, change.Id));

                        // revert the checked out file that was shelved
                        FileSpec file = new FileSpec(new DepotPath("//..."), null, null, null);
                        con.Client.RevertFiles(new RevertCmdOptions(RevertFilesCmdFlags.None, change.Id),
                                               file);

                        // submit the shelved file
                        SubmitCmdOptions submitOptions = new
                                                         SubmitCmdOptions(Perforce.P4.SubmitFilesCmdFlags.SubmitShelved,
                                                                          5, null, null, null);
                        change.Submit(submitOptions);

                        P4CommandResult last = rep.Connection.LastResults;
                        Assert.IsTrue(last.Success);
                    }
                }
                finally
                {
                    Utilities.RemoveTestServer(p4d, TestDir);
                }
                unicode = !unicode;
            }
        }
Exemple #13
0
        public void EditFile()
        {
            if (System.IO.File.Exists(editFilePath))
            {
                connected = con.Connect(null);
                if (connected)
                {
                    // Checking the file if it's in version control
                    if (ChkFileIsManaged())
                    {
                        try
                        {
                            string deaultfComment = "補助ツールによるチェックアウト";

                            // Create a new custom changelist
                            myChange             = new Changelist();
                            myChange.Description = deaultfComment;
                            myChange             = p4.CreateChangelist(myChange);

                            FileSpec editFile    = new FileSpec(new LocalPath(editFilePath));
                            Options  editOptions = new Options();
                            editOptions["-c"] = String.Format("{0}", myChange.Id);

                            try
                            {
                                // Open the file for edit
                                p4.Connection.Client.EditFiles(editOptions, new FileSpec[] { editFile });

                                EnableFileSubmit();

                                Console.WriteLine("The file is checkout!");
                            }
                            catch (P4Exception e)
                            {
                                MessageBox.Show("チェックアウトに失敗しました。\n" +
                                                "すでにチェックアウトされていないか確認してください。");
                                Console.WriteLine("Couldn't open file for edit!\n {0} : {1}", e.ErrorCode, e.Message);
                            }
                        }
                        catch (P4Exception e)
                        {
                            MessageBox.Show("チェンジリスト作成に失敗しました。\n" +
                                            "バージョン管理されているファイルか確認してください。");
                            Console.WriteLine("Couldn't make new changelist!\n {0} : {1}", e.ErrorCode, e.Message);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("ワークスペースに正しく接続できているか確認してください。");
                }
            }
            else
            {
                MessageBox.Show("指定ファイルが存在しません。");
            }
        }
        public static List <string> FileOperation(List <string> filePathList, FileAction action)
        {
            IList <FileSpec> filesEdited = null;
            Perforce         server      = new Perforce();

            if (server.Enabled == false)
            {
                return(new List <string>());
            }

            try
            {
                server.DiscoverClient(GetFilePath(filePathList[0]));
                // connect to the server
                server.Connect();

                foreach (string filePath in filePathList)
                {
                    string   fixedFilePath = GetFilePath(filePath);
                    FileSpec fileToAdd     = new FileSpec(new ClientPath(fixedFilePath));

                    if (System.IO.File.Exists(fixedFilePath) == true)
                    {
                        EditCmdOptions options = new EditCmdOptions(EditFilesCmdFlags.None, 0, null);
                        // run the command with the current connection
                        if (action == FileAction.Add)
                        {
                            filesEdited = server.Repository.Connection.Client.AddFiles(options, fileToAdd);
                        }
                        else if (action == FileAction.Edit)
                        {
                            filesEdited = server.Repository.Connection.Client.EditFiles(options, fileToAdd);
                        }
                        else if (action == FileAction.Delete)
                        {
                            filesEdited = server.Repository.Connection.Client.DeleteFiles(options, fileToAdd);
                        }
                        else if (action == FileAction.Reverted)
                        {
                            filesEdited = server.Repository.Connection.Client.RevertFiles(options, fileToAdd);
                        }
                    }
                }
            }
            finally
            {
                server.Disconnect();
            }

            List <FileSpec> fileSpecList = new List <FileSpec>();

            if (filesEdited != null)
            {
                fileSpecList = new List <FileSpec>(filesEdited);
            }
            return(fileSpecList.Select(x => x.ClientPath.ToString()).ToList());
        }
        public ImageFileSpec(FileSpec fileSpec, string containerName)
        {
            FileSpec       = fileSpec;
            ContainerName  = containerName;
            FileSpecFormat = FileSpecFormat.Undefined;

            // this will never be used for this simple constructor, it's just that a valid is needed.
            InterpolationFilter = InterpolationFilter.Robidoux;
        }
Exemple #16
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Create a PDF Package.
            try
            {
                using (PDFDoc doc = new PDFDoc())
                {
                    AddPackage(doc, input_path + "numbered.pdf", "My File 1");
                    AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
                    AddPackage(doc, input_path + "peppers.jpg", "An image");
                    AddCovePage(doc);
                    doc.Save(output_path + "package.pdf", SDFDoc.SaveOptions.e_linearized);
                    Console.WriteLine("Done.");
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Extract parts from a PDF Package.
            try
            {
                using (PDFDoc doc = new PDFDoc(output_path + "package.pdf"))
                {
                    doc.InitSecurityHandler();

                    pdftron.SDF.NameTree files = NameTree.Find(doc, "EmbeddedFiles");
                    if (files.IsValid())
                    {
                        // Traverse the list of embedded files.
                        NameTreeIterator i = files.GetIterator();
                        for (int counter = 0; i.HasNext(); i.Next(), ++counter)
                        {
                            string entry_name = i.Key().GetAsPDFText();
                            Console.WriteLine("Part: {0}", entry_name);
                            FileSpec file_spec = new FileSpec(i.Value());
                            Filter   stm       = file_spec.GetFileData();
                            if (stm != null)
                            {
                                string fname = output_path + "extract_" + counter.ToString() + ".pdf";
                                stm.WriteToFile(fname, false);
                            }
                        }
                    }
                }

                Console.WriteLine("Done.");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #17
0
        public void ToEscapedStringTest()
        {
            string    expected = "0";
            DepotPath dp       = new DepotPath(expected);
            FileSpec  target   = new FileSpec(dp);
            string    actual;

            actual = target.ToEscapedString();
            Assert.AreEqual(expected, actual);
        }
Exemple #18
0
 public void FreeUrl(FileSpec url)
 {
     if (free.pos + 1 >= free.urls.Length)
     {
         //Console.WriteLine("free cache full! de-allocating");
         url = null;
         return;
     }
     free.urls[free.pos++] = url;
 }
 public ImageFileSpec(FileSpec fileSpec, FileSpecFormat fileSpecFormat, uint pixelLength, int quality, float sharpeningAmount, InterpolationFilter interpolationFilter, string containerName)
 {
     FileSpec            = fileSpec;
     FileSpecFormat      = fileSpecFormat;
     PixelLength         = pixelLength;
     Quality             = quality;
     SharpeningAmount    = sharpeningAmount;
     InterpolationFilter = interpolationFilter;
     ContainerName       = containerName;
 }
Exemple #20
0
        public void HowTest()
        {
            FileSpec fromfile              = new FileSpec(new DepotPath("//depot/main/test"), new VersionRange(2, 4));
            FileSpec tofile                = new FileSpec(new DepotPath("//depot/rel/test"), new VersionRange(2, 4));
            FileIntegrationRecord target   = new FileIntegrationRecord(fromfile, tofile, IntegrateAction.BranchInto, 44444);
            IntegrateAction       expected = IntegrateAction.BranchInto;
            IntegrateAction       actual   = target.How;

            Assert.AreEqual(expected, actual);
        }
Exemple #21
0
 /**
  * <summary>Creates a new movie within the given document context.</summary>
  */
 public Movie(
     Document context,
     FileSpec fileSpec
     ) : base(
         context.File,
         new PdfDictionary()
         )
 {
     FileSpec = fileSpec;
 }
        public override void DeleteFile(Common.File file)
        {
            base.DeleteFile(file);

            string path = System.IO.Path.Combine(DirectoryInfo.FullName, file.Name);
            FileSpec fileSpec = new FileSpec(null, null, new LocalPath(path), null);

            storage.Connection.Client.RevertFiles(null, fileSpec);
            storage.Connection.Client.DeleteFiles(null, fileSpec);
        }
        private static async Task ProcessImageAsync(Image image, byte[] imageBytes, FileSpec fileSpec)
        {
            _log.Information($"LB.PhotoGalleries.Worker.Program.ProcessImageAsync() - Image {image.Id} for file spec {fileSpec}");

            var imageFileSpec = ImageFileSpecs.GetImageFileSpec(fileSpec);

            // we only generate images if the source image is larger than the size we're being asked to resize to, i.e. we only go down in size
            var longestSide = image.Metadata.Width > image.Metadata.Height ? image.Metadata.Width : image.Metadata.Height;

            if (longestSide <= imageFileSpec.PixelLength)
            {
                _log.Warning($"LB.PhotoGalleries.Worker.Program.ProcessImageAsync() - Image too small for this file spec: {fileSpec}: {image.Metadata.Width} x {image.Metadata.Height}");
                return;
            }

            // create the new image file
            var storageId = imageFileSpec.GetStorageId(image);

            await using (var imageFile = await GenerateImageAsync(image, imageBytes, imageFileSpec))
            {
                // upload the new image file to storage
                var containerClient = _blobServiceClient.GetBlobContainerClient(imageFileSpec.ContainerName);
                var uploadStopwatch = new Stopwatch();
                uploadStopwatch.Start();
                await containerClient.UploadBlobAsync(storageId, imageFile);

                uploadStopwatch.Stop();

                _log.Information($"LB.PhotoGalleries.Worker.Program.ProcessImageAsync() - Upload blob elapsed time: {uploadStopwatch.ElapsedMilliseconds}ms");
            }

            // update the Image object with the storage id of the newly-generated image file
            switch (fileSpec)
            {
            case FileSpec.Spec3840:
                image.Files.Spec3840Id = storageId;
                break;

            case FileSpec.Spec2560:
                image.Files.Spec2560Id = storageId;
                break;

            case FileSpec.Spec1920:
                image.Files.Spec1920Id = storageId;
                break;

            case FileSpec.Spec800:
                image.Files.Spec800Id = storageId;
                break;

            case FileSpec.SpecLowRes:
                image.Files.SpecLowResId = storageId;
                break;
            }
        }
Exemple #24
0
        public void RshConnectionTest()
        {
            bool unicode = false;

            string user      = "******";
            string pass      = string.Empty;
            string ws_client = "admin_space";

            var        p4d    = Utilities.DeployP4TestServer(TestDir, unicode, TestContext.TestName);
            Server     server = new Server(new ServerAddress("localhost:6666"));
            Repository rep    = new Repository(server);

            using (Connection con = rep.Connection)
            {
                con.UserName    = user;
                con.Client      = new Client();
                con.Client.Name = ws_client;
                bool connected = con.Connect(null);
                Assert.IsTrue(connected);
                Assert.AreEqual(con.Status, ConnectionStatus.Connected);
                uint     cmdID = 7;
                string[] args  = new string[] { "stop" };
                Assert.IsTrue(con.getP4Server().RunCommand("admin", cmdID, false, args, args.Length));
                logger.Debug("Stopped launched server");
            }

            string uri = Utilities.TestRshServerPort(TestDir, unicode);

            server = new Server(new ServerAddress(uri));
            rep    = new Repository(server);
            logger.Debug("Created new server");
            try
            {
                using (Connection con = rep.Connection)
                {
                    con.UserName    = user;
                    con.Client      = new Client();
                    con.Client.Name = ws_client;

                    logger.Debug("About to connect");
                    Assert.AreEqual(con.Status, ConnectionStatus.Disconnected);
                    Assert.IsTrue(con.Connect(null));
                    Assert.AreEqual(con.Status, ConnectionStatus.Connected);
                    logger.Debug("Connected");
                    Utilities.SetClientRoot(rep, TestDir, unicode, ws_client);

                    FileSpec fs = new FileSpec(new DepotPath("//depot/MyCode/ReadMe.txt"), null);
                    rep.Connection.Client.EditFiles(null, fs);
                    logger.Debug("File edited");
                }
            } finally
            {
                Utilities.RemoveTestServer(p4d, TestDir);
            }
        }
Exemple #25
0
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (BackgroundWorkEnded != null)
            {
                BackgroundWorkEnded(this, EventArgs.Empty);
            }

            if (e.Cancelled)
            {
                return;
            }

            TempItemSet[] itemSets = e.Result as TempItemSet[];
            if (itemSets != null)
            {
                treeView.BeginUpdate();
                TreeNodeLocalItem treeNodeServerFolder = null;
                foreach (TempItemSet itemSet in itemSets)
                {
                    if (itemSet.QueryPath != null)
                    {
                        if (treeNodeServerFolder != null && !FileSpec.IsSubItem(itemSet.QueryPath, treeNodeServerFolder.LocalItem))
                        {
                            treeNodeServerFolder = null;
                        }
                        TreeNodeLocalItem treeNodeServerFolder2;
                        if (TryFindNodeByServerItem(itemSet.QueryPath, treeNodeServerFolder, out treeNodeServerFolder2) && NodeNeedsExpansion(treeNodeServerFolder2))
                        {
                            treeNodeServerFolder2.Nodes.Clear();
                            foreach (TempItemSet.TempItem i in itemSet.Items)
                            {
                                AttachTreeNode(treeNodeServerFolder2, Path.GetFileName(i.LocalPath), i);
                            }
                            if (!treeNodeServerFolder2.IsExpanded && m_navigateToWhenLoaded == null)
                            {
                                treeNodeServerFolder2.Expand();
                            }
                            treeNodeServerFolder = treeNodeServerFolder2;
                        }
                    }
                }
                if (m_navigateToWhenLoaded != null)
                {
                    TreeNodeLocalItem treeNodeServerFolder3;
                    TryFindNodeByServerItem(m_navigateToWhenLoaded, null, out treeNodeServerFolder3);
                    if (treeNodeServerFolder3 != null)
                    {
                        treeNodeServerFolder3.EnsureVisible();
                        treeView.SelectedNode = treeNodeServerFolder3;
                    }
                    m_navigateToWhenLoaded = null;
                }
                treeView.EndUpdate();
            }
        }
Exemple #26
0
        public void ToStringTest()
        {
            string   target    = @"C:\workspace@root\test#1%2.txt";
            FileSpec LocalSpec = new FileSpec(null, null, new LocalPath(target), new NoneRevision());

            string expected = @"c:\workspace@root\test#1%2.txt#none";

            string actual = LocalSpec.ToString();

            Assert.AreEqual(expected, actual);
        }
Exemple #27
0
        public void ClientPathTest()
        {
            ClientPath  expected = new ClientPath("c:\foobarclient");
            VersionSpec version  = new VersionRange(new LabelNameVersion("my_label"), new LabelNameVersion("my_old_label"));
            FileSpec    target   = new FileSpec(expected, version);
            ClientPath  actual;

            target.ClientPath = expected;
            actual            = target.ClientPath;
            Assert.AreEqual(expected, actual);
        }
Exemple #28
0
        /*----< extract category from filespec >-----------------------*/

        public DirName extractCategory(FileSpec fileSpec)
        {
            string temp = storageFolderSpec(fileSpec);
            int    pos  = temp.IndexOf("/");

            if (pos == temp.Length || pos == -1)
            {
                return("");
            }
            return(temp.Substring(0, pos));
        }
Exemple #29
0
        public void WritesDataToXml()
        {
            // Arrange
            var fileSpec = new FileSpec("file.ext", 1);

            // Act
            var xml = TestHelper.GetXml(fileSpec.WriteXml);

            // Assert
            xml.Should().Be("<Root><SourceFileID>1</SourceFileID><SourceFileName>file.ext</SourceFileName></Root>");
        }
Exemple #30
0
        /*----< extract fileName from filespec >-----------------------*/

        public FileName extractFileName(FileSpec fileSpec)
        {
            string temp = storageFolderSpec(fileSpec);
            int    pos  = temp.IndexOf("/");

            if (pos == temp.Length || pos == -1)
            {
                return("");
            }
            return(temp.Substring(pos + 1));
        }
Exemple #31
0
        public async Task FileCount_DefaultSpec_ReturnsCountOfActiveFiles()
        {
            using var repository = CreateRepositoryHelper().GetFileRepository();
            var spec = new FileSpec();

            var result = await repository.CountAsync(spec);

            var expected = RepositoryData.Files.Count(e => e.Active);

            result.Should().Be(expected);
        }
Exemple #32
0
        public void ToStringTest2()
        {
            Type      pathType = typeof(DepotPath);        // TODO: Initialize to an appropriate value
            string    expected = "0";
            DepotPath dp       = new DepotPath(expected);
            FileSpec  target   = new FileSpec(dp);
            string    actual;

            actual = target.ToString(pathType);
            Assert.AreEqual(expected, actual);
        }
Exemple #33
0
   public FileAttachment(
 Page page,
 RectangleF box,
 FileSpec fileSpec
 )
       : base(page.Document,
   PdfName.FileAttachment,
   box,
   page)
   {
       FileSpec = fileSpec;
   }
		/// <summary>
        /// Construct a P4ChangelistSpanQuery from the changelist numbers specified as parameters; the numbers are not required to be in order
        /// </summary>
		/// <param name="InQueryChangelistStart">The start or end changelist number for the query</param>
		/// <param name="InQueryChangelistEnd">The start or end changelist number for the query, whichever wasn't specified by the first parameter</param>
		/// <param name="InDepotFilter">Path to filter the depot by</param>
		/// <param name="InUserFilter">User to filter the depot by, can be empty string</param>
        public P4ChangelistSpanQuery(int InQueryChangelistStart, int InQueryChangelistEnd, String InDepotFilter, String InUserFilter="")
			: base(InDepotFilter, InUserFilter)
		{
			// Reorder the changelists increasing
            ReOrder(ref InQueryChangelistStart, ref InQueryChangelistEnd);

            ChangelistIdVersion StartVersionId = new ChangelistIdVersion(InQueryChangelistStart);
            ChangelistIdVersion EndVersionId = new ChangelistIdVersion(InQueryChangelistEnd);

            VersionRange Versions = new VersionRange(StartVersionId, EndVersionId);

            mFileFilter = new FileSpec(new DepotPath(InDepotFilter), null, null, Versions);
        }
        /// <summary>
        /// Construct a P4ChangelistSpanQuery from the dates specified as parameters; the dates are not required to be in order
        /// </summary>
        /// <param name="InQueryDateTimeStart">The start or end date for the query</param>
        /// <param name="InQueryDateTimeEnd">The start or end date for the query, whichever wasn't specified by the first parameter</param>
        /// <param name="InDepotFilter">Path to filter the depot by</param>
        /// <param name="InUserFilter">User to filter the depot by, can be empty string</param>
        public P4ChangelistSpanQuery(DateTime InQueryDateTimeStart, DateTime InQueryDateTimeEnd, String InDepotFilter, String InUserFilter = "")
            : base(InDepotFilter, InUserFilter)
        {
            // Reorder the changelists increasing
            ReOrder(ref InQueryDateTimeStart, ref InQueryDateTimeEnd);

            DateTimeVersion StartDateTime = new DateTimeVersion(InQueryDateTimeStart);
            DateTimeVersion EndDateTime = new DateTimeVersion(InQueryDateTimeEnd);

            VersionRange Versions = new VersionRange(StartDateTime, EndDateTime);

            mFileFilter = new FileSpec(new DepotPath(InDepotFilter), null, null, Versions);
        }
Exemple #36
0
        public void op_Load_string_whenFile()
        {
            using (var temp = new TempDirectory())
            {
                var expected = temp
                    .Info
                    .ToFile("example.txt")
                    .AppendLine(string.Empty)
                    .FullName;

                var actual = new FileSpec(expected).First().FullName;

                Assert.Equal(expected, actual);
            }
        }
Exemple #37
0
        public void op_Load_string_whenFileSearch()
        {
            using (var temp = new TempDirectory())
            {
                var expected = temp
                    .Info
                    .ToFile("example.txt")
                    .AppendLine(string.Empty)
                    .FullName;

                var name = @"{0}\*.txt".FormatWith(temp.Info.FullName);

                var actual = new FileSpec(name).First().FullName;

                Assert.Equal(expected, actual);
            }
        }
 /// <summary>
 /// Check out the INT file for this lang file
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void checkoutINTFileToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (CheckConnect())
     {
         using (Connection P4Connection = P4Repository.Connection)
         {
             foreach (ListViewItem SelectedRow in FileListView.SelectedItems)
             {
                 //Set the language client file to edit
                 FileSpec[] CurrentClientFile = new FileSpec[1];
                 CurrentClientFile[0] = new FileSpec(null, new ClientPath(GetClientFile(SelectedRow)), null, null);
                 try
                 {
                     P4Connection.Client.EditFiles(CurrentClientFile, null);
                 }
                 catch (P4CommandTimeOutException Error)
                 {
                     log.Error(Error.Message);
                     //do not continue
                     return;
                 }
             }
         }
     }
 }
        /// <summary>
        /// Add the move files to the default change list
        /// </summary>
        private void AddMoveFilesToDefaultChangeList(Connection P4Connection)
        {
            foreach (var LangFileMoveDetails in LangFileToMoveProcessingList)
            {
                //Check that the Move to file does not already exist.
                if (
                    LangFileProcessingDictionary.ContainsKey(
                        ParseLangFileName(_connectionDetails.UserSavedStatePreferredLanguage).Match(LangFileMoveDetails.ToDepotFile).Groups[
                            "FileName"].Value.ToUpper()))
                {
                    log.Error(
                        String.Format(
                            "Unable to move a file, destination already exists, manual fix needed.\nFrom:{0}\nTo:{1}",
                            LangFileMoveDetails.FromDepotFile, LangFileMoveDetails.ToDepotFile));
                }
                else
                {
                    FileSpec[] CurrentClientFile = new FileSpec[1];
                    CurrentClientFile[0] = new FileSpec(null, new ClientPath(LangFileMoveDetails.FromClientFile),
                                                        null, null);

                    try
                    {
                        P4Connection.Client.EditFiles(CurrentClientFile, null);
                        P4Connection.Client.MoveFiles(CurrentClientFile[0],
                                                        new FileSpec(null,
                                                                    new ClientPath(LangFileMoveDetails.ToClientFile),
                                                                    null, null),
                                                        null);
                    }
                    catch (P4CommandTimeOutException Error)
                    {
                        log.Error(Error.Message);
                        //do not continue
                        return;
                    }
                }
            }

            LangFileToMoveProcessingList.Clear();
        }
        /// <summary>
        /// Performs the action for a translate or diff operation based on the value of FullTranslate
        /// </summary>
        /// <param name="FullTranslate">If true will translate files and checkout the language file, otherwise just performs a diff operation</param>
        void TranslateOrDiff(bool FullTranslate)
        {
            foreach (ListViewItem SelectedRow in FileListView.SelectedItems)
            {
                if (GetState(SelectedRow).Equals(FileProcessingDetails.State.New.ToString()))
                {
                    //Copy file to Lang version only if file does not already exist.
                    string LangClientFileName = "";

                    //TempFileLocation or FullTranslate location
                    if (FullTranslate)
                    {
                        LangClientFileName = GetLangFileNameFromInt(GetClientFile(SelectedRow));
                    }
                    else
                    {
                        DirectoryInfo TempOutputDirectory = new DirectoryInfo(Path.Combine(System.IO.Path.GetTempPath(), "UnrealDocTranslator"));

                        if (!TempOutputDirectory.Exists)
                        {
                            TempOutputDirectory.Create();
                        }

                        LangClientFileName = Path.Combine(TempOutputDirectory.FullName,
                                                           (new System.IO.FileInfo(GetClientFile(SelectedRow))).Name);
                    }

                    if (!(new System.IO.FileInfo(GetClientFile(SelectedRow))).Exists)
                    {
                        log.Error(String.Format("Client file {0} does not exist, unable to create language file, try to Refresh P4 and synchronize", GetClientFile(SelectedRow)));
                        break;
                    }
                    else
                    {
                        // Does the local file exist? only create file once if not full translate
                        if (!(FullTranslate && (new System.IO.FileInfo(LangClientFileName)).Exists))
                        {
                            //Add Changelist number of INT file to top of lang file as metadata
                            string FileContents = "INTSourceChangelist:" + GetChangelist(SelectedRow) +
                                                    Environment.NewLine +
                                                    System.IO.File.ReadAllText(GetClientFile(SelectedRow), Encoding.UTF8);
                            System.IO.File.WriteAllText(LangClientFileName, FileContents, Encoding.UTF8);
                        }

                        // Add to P4 as file add
                        if (FullTranslate && CheckConnect())
                        {
                            using (Connection P4Connection = P4Repository.Connection)
                            {
                                FileSpec[] CurrentClientFile = new FileSpec[1];
                                CurrentClientFile[0] = new FileSpec(null, new ClientPath(LangClientFileName), null, null);

                                try
                                {
                                    P4Connection.Client.AddFiles(CurrentClientFile, null);
                                    SelectedRow.ForeColor = Color.Red;
                                    FilesCheckedOut.Add(GetLangFileNameFromInt(GetDepotFile(SelectedRow)));
                                }
                                catch (P4CommandTimeOutException Error)
                                {
                                    //do not continue
                                    log.Error(Error.Message);
                                    return;
                                }
                            }
                        }
                        string AraxisMergeComparePath = System.IO.Path.Combine(_connectionDetails.AraxisFolderName, "Compare.exe");
                        if ((new System.IO.FileInfo(AraxisMergeComparePath)).Exists)
                        {
                            ProcessStartInfo StartInfo = new ProcessStartInfo(AraxisMergeComparePath, String.Format("\"{0}\" \"{1}\"", GetClientFile(SelectedRow), LangClientFileName));
                            StartInfo.UseShellExecute = false;
                            StartInfo.CreateNoWindow = true;
                            StartInfo.RedirectStandardOutput = true;
                            StartInfo.RedirectStandardError = true;
                            System.Diagnostics.Process.Start(StartInfo);
                        }
                        else
                        {
                            log.Error("Unable to locate Araxis Merge compare, please use Change Settings to correct");
                            break;
                        }
                    }
                }
                else if (GetState(SelectedRow).Equals(FileProcessingDetails.State.Translated.ToString()))
                {
                    string LangFileProcessingDictionaryIndex = ParseINTFileName.Match(GetDepotFile(SelectedRow)).Groups["FileName"].Value.ToUpper();

                    FileProcessingDetails LangFileDetails;

                    if (!LangFileProcessingDictionary.TryGetValue(LangFileProcessingDictionaryIndex, out LangFileDetails))
                    {
                        log.Error("Can not find Lang file details for " + GetClientFile(SelectedRow));
                        break;
                    }

                    if (FullTranslate && CheckConnect())
                    {
                        using (Connection P4Connection = P4Repository.Connection)
                        {
                            //Set the language client file to edit
                            FileSpec[] CurrentClientFile = new FileSpec[1];
                            CurrentClientFile[0] = new FileSpec(null, new ClientPath(LangFileDetails.ClientFile), null, null);
                            try
                            {
                                P4Connection.Client.EditFiles(CurrentClientFile, null);
                                SelectedRow.ForeColor = Color.Red;
                                FilesCheckedOut.Add(GetLangFileNameFromInt(GetDepotFile(SelectedRow)));
                            }
                            catch (P4CommandTimeOutException Error)
                            {
                                //do not continue
                                log.Error(Error.Message);
                                return;
                            }
                        }
                    }

                    string AraxisMergeComparePath = System.IO.Path.Combine(_connectionDetails.AraxisFolderName, "Compare.exe");
                    if ((new System.IO.FileInfo(AraxisMergeComparePath)).Exists)
                    {
                        ProcessStartInfo StartInfo = new ProcessStartInfo(AraxisMergeComparePath, String.Format("\"{0}\" \"{1}\"", GetClientFile(SelectedRow), LangFileDetails.ClientFile));
                        StartInfo.UseShellExecute = false;
                        StartInfo.CreateNoWindow = true;
                        StartInfo.RedirectStandardOutput = true;
                        StartInfo.RedirectStandardError = true;
                        System.Diagnostics.Process.Start(StartInfo);
                    }
                    else
                    {
                        log.Error("Unable to locate Araxis Merge compare, please use Change Settings to correct");
                        break;
                    }
                }
                else if (GetState(SelectedRow).Equals(FileProcessingDetails.State.Delete.ToString()))
                {
                    //Should not be able to get here
                    log.Info("Not implemented for delete");
                }
                else if (GetState(SelectedRow).Equals(FileProcessingDetails.State.MoveTo.ToString()))
                {
                    //Should not be able to get here
                    log.Info("Not implemented for move");
                }
                else if (GetState(SelectedRow).Equals(FileProcessingDetails.State.Changed.ToString()))
                {
                    string LangFileProcessingDictionaryIndex = ParseINTFileName.Match(GetDepotFile(SelectedRow)).Groups["FileName"].Value.ToUpper();

                    FileProcessingDetails LangFileDetails;

                    if (!LangFileProcessingDictionary.TryGetValue(LangFileProcessingDictionaryIndex, out LangFileDetails))
                    {
                        log.Error("Can not find Lang file details for " + GetClientFile(SelectedRow));
                        break;
                    }

                    //Create temp file for diff to old INT file
                    string tempFileContent = "INTSourceChangelist:" + GetChangelist(SelectedRow) + Environment.NewLine;

                    if (CheckConnect())
                    {
                        using (Connection P4Connection = P4Repository.Connection)
                        {
                            FileSpec[] CurrentClientFile = new FileSpec[1];
                            if (FullTranslate)
                            {
                                //Set the language client file to edit
                                CurrentClientFile[0] = new FileSpec(null, new ClientPath(LangFileDetails.ClientFile), null, null);
                                try
                                {
                                    P4Connection.Client.EditFiles(CurrentClientFile, null);
                                    SelectedRow.ForeColor = Color.Red;
                                    FilesCheckedOut.Add(GetLangFileNameFromInt(GetDepotFile(SelectedRow)));
                                }
                                catch (P4CommandTimeOutException Error)
                                {
                                    //do not continue
                                    log.Error(Error.Message);
                                    return;
                                }
                            }

                            //Get the filespec of the int file for the current changelist number
                            CurrentClientFile[0] = GetIntFileSpecForFileChangelist(GetDepotFile(SelectedRow), LangFileDetails.ChangeList, true);

                            IList<string> listString = P4Repository.GetFileContents(CurrentClientFile, null);
                            if (listString.Count > 1)
                            {
                                tempFileContent += listString[1];
                            }
                        }
                    }
                    DirectoryInfo TempOutputDirectory = new DirectoryInfo(Path.Combine(System.IO.Path.GetTempPath(), "UnrealDocTranslator"));

                    if (!TempOutputDirectory.Exists)
                    {
                        TempOutputDirectory.Create();
                    }

                    string TempFileName = Path.Combine(TempOutputDirectory.FullName,
                                                       (new System.IO.FileInfo(GetClientFile(SelectedRow))).Name);

                    System.IO.File.WriteAllText(TempFileName, tempFileContent);

                    string AraxisMergeComparePath = System.IO.Path.Combine(_connectionDetails.AraxisFolderName, "Compare.exe");
                    if ((new System.IO.FileInfo(AraxisMergeComparePath)).Exists)
                    {
                        ProcessStartInfo StartInfo = new ProcessStartInfo(AraxisMergeComparePath, String.Format("/a3 /3 \"{0}\" \"{1}\" \"{2}\"", GetClientFile(SelectedRow), LangFileDetails.ClientFile, TempFileName));
                        StartInfo.UseShellExecute = false;
                        StartInfo.CreateNoWindow = true;
                        StartInfo.RedirectStandardOutput = true;
                        StartInfo.RedirectStandardError = true;
                        System.Diagnostics.Process.Start(StartInfo);
                    }
                    else
                    {
                        log.Error("Unable to locate Araxis Merge compare, please use Change Settings to correct");
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// List control from P4
        /// </summary>
        private void RefreshP4Details()
        {
            //If any temporary files delete them
            DirectoryInfo TempOutputDirectory = new DirectoryInfo(Path.Combine(System.IO.Path.GetTempPath(), "UnrealDocTranslator"));

            if (TempOutputDirectory.Exists)
            {
                TempOutputDirectory.Delete(true);
            }

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (CheckConnect())
                {
                    using (Connection P4Connection = P4Repository.Connection)
                    {
                        FileSpec[] HeadSourceUdnFiles = new FileSpec[1];
                        HeadSourceUdnFiles[0] = new FileSpec(
                            new DepotPath(_connectionDetails.DepotPath), null, null, VersionSpec.Head);

                        FileSpec[] OpenedSourceUdnFiles = new FileSpec[1];
                        OpenedSourceUdnFiles[0] = new FileSpec(
                            new DepotPath(_connectionDetails.DepotPath), null, null, null);

                        try
                        {
                            var ListOfOpenedFileStats = P4Repository.GetOpenedFiles(OpenedSourceUdnFiles, null);

                            FilesCheckedOut.Clear();

                            //If there are any opened files
                            if (ListOfOpenedFileStats != null)
                            {
                                foreach (var FileStat in ListOfOpenedFileStats)
                                {
                                    //if any of the files are in the default changelist stop processing.
                                    if (FileStat.ChangeId == 0)
                                    {
                                        log.Error("Your default Changelist is not empty. Please Submit All or Revert before you proceed.");
                                        return;
                                    }
                                }
                            }

                            log.Info("Sync P4 to get latest changes");
                            P4Repository.Connection.Client.SyncFiles(null, HeadSourceUdnFiles);

                            log.Info("Getting file metadata from p4");
                            ListOfAllFileStats = P4Repository.GetFileMetaData(null, HeadSourceUdnFiles);

                        }
                        catch (P4Exception ErrorMessage)
                        {
                            log.Error(ErrorMessage.Message);
                            return;
                        }

                        INTFileProcessingDictionary.Clear();
                        INTMovedFileFromProcessingDictionary.Clear();
                        INTMovedFileToProcessingDictionary.Clear();
                        INTDeletedFileProcessingDictionary.Clear();

                        log.Info("Detecting status of INT files");

                        //From the list of file stats set up the INT dictionary
                        foreach (FileMetaData FileDetails in ListOfAllFileStats)
                        {
                            string PartFileName = FileDetails.DepotPath == null ? "" : ParseINTFileName.Match(FileDetails.DepotPath.ToString()).Groups["FileName"].Value.ToUpper();

                            if (!string.IsNullOrWhiteSpace(PartFileName))
                            {
                                //Does anyone else have this checked out?
                                bool IsCheckedOutByOtherUser = FileDetails.OtherUsers == null ? false : true;

                                //Depot file could be determined?
                                if (FileDetails.DepotPath == null)
                                {
                                    log.Warn("DepotPath missing for PartFileName: " + PartFileName);
                                }
                                else
                                {

                                    if (FileDetails.HeadAction == FileAction.Delete)
                                    {
                                        INTDeletedFileProcessingDictionary.Add(PartFileName,
                                                                               new FileProcessingDetails(
                                                                                   FileDetails.DepotPath.ToString(),
                                                                                   FileDetails.ClientPath == null ? "" : FileDetails.ClientPath.ToString(),
                                                                                   FileDetails.HeadChange,
                                                                                   FileProcessingDetails.State.Delete,
                                                                                   IsCheckedOutByOtherUser,
                                                                                   _connectionDetails));
                                    }
                                    else if (FileDetails.HeadAction == FileAction.MoveDelete)
                                    {
                                        INTMovedFileFromProcessingDictionary.Add(PartFileName,
                                                                                 new FileProcessingDetails(
                                                                                     FileDetails.DepotPath.ToString(),
                                                                                     FileDetails.ClientPath == null ? "" : FileDetails.ClientPath.ToString(),
                                                                                     FileDetails.HeadChange,
                                                                                     FileProcessingDetails.State.MoveFrom,
                                                                                     IsCheckedOutByOtherUser,
                                                                                     _connectionDetails));
                                    }
                                    else if (FileDetails.HeadAction == FileAction.MoveAdd)
                                    {
                                        if (FileDetails.ClientPath == null)
                                        {
                                            //log message
                                            log.Warn("ClientPath missing for DepotPath: " + FileDetails.DepotPath.ToString());
                                        }
                                        else
                                        {
                                            INTMovedFileToProcessingDictionary.Add(PartFileName,
                                                                                     new FileProcessingDetails(
                                                                                         FileDetails.DepotPath.ToString(),
                                                                                         FileDetails.ClientPath.ToString(),
                                                                                         FileDetails.HeadChange,
                                                                                         FileProcessingDetails.State.MoveTo,
                                                                                         IsCheckedOutByOtherUser,
                                                                                         _connectionDetails));
                                        }
                                    }
                                    else
                                    {
                                        if (FileDetails.ClientPath == null)
                                        {
                                            //log message
                                            log.Warn("ClientPath missing for DepotPath: " + FileDetails.DepotPath.ToString());
                                        }
                                        else
                                        {
                                            INTFileProcessingDictionary.Add(PartFileName,
                                                                            new FileProcessingDetails(
                                                                                FileDetails.DepotPath.ToString(),
                                                                                FileDetails.ClientPath.ToString(),
                                                                                FileDetails.HeadChange,
                                                                                FileProcessingDetails.State.NotDeterminedYet,
                                                                                IsCheckedOutByOtherUser,
                                                                                _connectionDetails));
                                        }
                                    }
                                }
                            }
                        }

                        CreateLanguageFileDictionary();
                    }
                }

                PerformDefaultActions();

                log.Info("Lookup the change list descriptions");

                BuildChangeListsDescriptionMapping();

                log.Info("Populating list  view");

                //Clear the FileListView
                FileListView.BeginUpdate();
                FileListView.Items.Clear();
                FileListView.EndUpdate();
                FileListView.Refresh();

                switch (ButtonToSwitchOnAfterRefresh)
                {
                    case DefaultOnButton.New:
                        NotInLangButtonOn = true;
                        UpdatedInIntButtonOn = false;
                        AlreadyTranslatedButtonOn = false;
                        break;
                    case DefaultOnButton.Changed:
                        NotInLangButtonOn = false;
                        UpdatedInIntButtonOn = true;
                        AlreadyTranslatedButtonOn = false;
                        break;
                    case DefaultOnButton.Translated:
                        NotInLangButtonOn = false;
                        UpdatedInIntButtonOn = false;
                        AlreadyTranslatedButtonOn = true;
                        break;
                    default:
                        NotInLangButtonOn = false;
                        UpdatedInIntButtonOn = false;
                        AlreadyTranslatedButtonOn = false;
                        break;
                }

                PopulateListWithNotInLang();
                PopulateListWithUpdatedInInt();
                PopulateListWithAlreadyTranslated();

                log.Info("Refresh or loading tasks completed");
            }
            catch (Exception ex)
            {
                log.Error("Error in refresh:");
                log.Error(ex.Message);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        private FileProcessingDetails GetMovedToLocation(FileProcessingDetails MovedFromFileDetails)
        {
            //Find the moved to location of moved from files, need to examine the changelist, do this in languages as it is quite slow so should only process those moves which we need to.
            var ListOfFilesInMovedFromChangeList =
                P4Repository.GetChangelist(MovedFromFileDetails.ChangeList).Files;

            //For the files that are MoveAdd
            foreach (var FileDetails in ListOfFilesInMovedFromChangeList)
            {
                if (FileDetails.Action == FileAction.MoveAdd)
                {
                    //This could be the file we are looking for.  Check the file history of this file.
                    FileSpec[] CurrentClientFile = new FileSpec[1];
                    CurrentClientFile[0] = new FileSpec(new DepotPath(FileDetails.DepotPath.ToString()), null);
                    IList<FileHistory> FileHistory = P4Repository.GetFileHistory(CurrentClientFile, null);

                    foreach (var SliceOfHistory in FileHistory)
                    {
                        if (SliceOfHistory.ChangelistId == MovedFromFileDetails.ChangeList)
                        {
                            foreach (var IntegrationSummary in SliceOfHistory.IntegrationSummaries)
                            {
                                if (IntegrationSummary.FromFile.DepotPath.ToString() == MovedFromFileDetails.DepotFile)
                                {
                                    //Does anyone else have this checked out?
                                    bool IsCheckedOutByOtherUser = FileDetails.OtherUsers == null ? false : true;

                                    //Found where it moves to initially, what if it moved again?
                                    //Would like to determine the last moved to location.
                                    if (FileHistory[0].Action == FileAction.MoveDelete)
                                    {
                                        return
                                            GetMovedToLocation(new FileProcessingDetails(
                                                                   FileDetails.DepotPath.ToString(),
                                                                   "",
                                                                   FileHistory[0].ChangelistId,
                                                                   FileProcessingDetails.State.MoveTo,
                                                                   IsCheckedOutByOtherUser,
                                                                   _connectionDetails));
                                    }
                                    else
                                    {
                                        //Need the client path of this file to be able to rename the language file on move correctly.
                                        string ClientPath = "";

                                        FileProcessingDetails ClientFileDetails;

                                        //Last task on the file could be the MoveAdd, it could also be an update, or delete, find the ClientPath
                                        if (
                                            INTMovedFileToProcessingDictionary.TryGetValue(
                                                ParseINTFileName.Match(FileDetails.DepotPath.ToString()).Groups[
                                                    "FileName"].Value.ToUpper(), out ClientFileDetails))
                                        {
                                            ClientPath = ClientFileDetails.ClientFile;
                                        }
                                        else if (
                                            INTDeletedFileProcessingDictionary.TryGetValue(
                                                ParseINTFileName.Match(FileDetails.DepotPath.ToString()).Groups[
                                                    "FileName"].Value.ToUpper(), out ClientFileDetails))
                                        {
                                            ClientPath = ClientFileDetails.ClientFile;
                                        }
                                        else if (
                                            INTFileProcessingDictionary.TryGetValue(
                                                ParseINTFileName.Match(FileDetails.DepotPath.ToString()).Groups[
                                                    "FileName"].Value.ToUpper(), out ClientFileDetails))
                                        {
                                            ClientPath = ClientFileDetails.ClientFile;
                                        }

                                        return
                                            (new FileProcessingDetails(FileDetails.DepotPath.ToString(),
                                                                       ClientPath,
                                                                       MovedFromFileDetails.ChangeList,
                                                                       FileProcessingDetails.State.MoveTo,
                                                                       IsCheckedOutByOtherUser,
                                                                       _connectionDetails));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //Should not really get here unless P4 is corrupt.
            return (new FileProcessingDetails());
        }
        /// <summary>
        /// Get the FileSpec for a depot file given a changelist
        /// </summary>
        /// <param name="depotFileName">The file name in current depot location</param>
        /// <param name="changelist">The language file's changelist to be used to find an older version of the int file</param>
        /// <param name="checkForRenameMove">Check if the file has changed names due to a move/rename</param>
        /// <returns>FileSpec which may have a different depotfilename than that passed into function if the file has been moved since changelist</returns>
        private FileSpec GetIntFileSpecForFileChangelist(string depotFileName, int changelist, bool checkForRenameMove)
        {
            if (!CheckConnect())
            {
                return null;
            }

            if (checkForRenameMove)
            {
                PathSpec HistoryPathSpec = new DepotPath(depotFileName) as PathSpec;

                FileSpec[] HistoryFiles = new FileSpec[1];
                HistoryFiles[0] = new FileSpec(HistoryPathSpec, VersionSpec.Head);

                Options Opts = new Options();
                Opts.Add("-i", "");
                IList<FileHistory> History = P4Repository.GetFileHistory(Opts, HistoryFiles);

                // walk through history until we find the first changelist older than the specified changelist
                foreach (FileHistory Item in History)
                {
                    if (Item.ChangelistId > changelist)
                    {
                        continue;
                    }

                    // use the depot filename at this revision
                    HistoryPathSpec = Item.DepotPath;
                    break;
                }

                return new FileSpec(HistoryPathSpec, new ChangelistIdVersion(changelist));
            }
            else
            {
                return new FileSpec(new DepotPath(depotFileName) as PathSpec, new ChangelistIdVersion(changelist));
            }
        }
        /// <summary>
        /// Creates LangFileProcessingDictionary based on the currently selected language
        /// </summary>
        private void CreateLanguageFileDictionary()
        {
            //From the list of file stats set up the Lang dictionary
            log.Info("Processing language files");

            if (ListOfAllFileStats != null && !string.IsNullOrWhiteSpace(_connectionDetails.UserSavedStatePreferredLanguage))
            {
                LangFileProcessingDictionary.Clear();
                foreach (FileMetaData FileDetails in ListOfAllFileStats)
                {
                    if (FileDetails.DepotPath == null)
                    {
                        log.Warn("DepotPath missing for one of the files on language CreateLanguageFileDictionary");
                    }
                    else if (FileDetails.ClientPath == null)
                    {
                        log.Warn("ClientPath missing for DepotPath: " + FileDetails.DepotPath.ToString());
                    }
                    else
                    {
                        string PartFileName = ParseLangFileName(_connectionDetails.UserSavedStatePreferredLanguage).Match(FileDetails.DepotPath.ToString()).Groups["FileName"].Value.ToUpper();

                        if (!string.IsNullOrWhiteSpace(PartFileName) && !(FileDetails.HeadAction == FileAction.Delete || FileDetails.HeadAction == FileAction.MoveDelete))
                        {
                            //check files for INTSourceChangelist:
                            int ChangelistValue = ChooseHeadChangeOrFileChangeListNumber(FileDetails.HeadChange, FileDetails.ClientPath.ToString());

                            LangFileProcessingDictionary.Add(PartFileName, new FileProcessingDetails(FileDetails.DepotPath.ToString(), FileDetails.ClientPath.ToString(), ChangelistValue, FileProcessingDetails.State.NotDeterminedYet, false, _connectionDetails));
                        }
                    }
                }
            }

            //Setup list of files for create, change and translated
            log.Info("Generating list of language files missing, needing update or already translated");
            LangFileToCreateProcessingList.Clear();
            LangFileToUpdateProcessingList.Clear();
            LangFileTranslatedProcessingList.Clear();
            foreach (var INTFile in INTFileProcessingDictionary)
            {
                if (LangFileProcessingDictionary.ContainsKey(INTFile.Key))
                {
                    FileProcessingDetails LangFile;
                    if (LangFileProcessingDictionary.TryGetValue(INTFile.Key, out LangFile))
                    {
                        // mi.wang: Special case we can now copy all those untranslated pages to localized folder but mark ChangeList as 0 to distinguish them from Needs Updated ones.
                        //          This can help fix reference errors from actual parse errors and also keep links not fall back to INT while using specified language under UDN.
                        if (LangFile.ChangeList <= 0)
                        {
                            LangFileToCreateProcessingList.Add(new FileProcessingDetails(INTFile.Value.DepotFile, INTFile.Value.ClientFile, INTFile.Value.ChangeList, FileProcessingDetails.State.New, INTFile.Value.CheckedOutByOthers, _connectionDetails));
                        }
                        else if (LangFile.ChangeList < INTFile.Value.ChangeList)
                        {
                            // Needs update
                            LangFileToUpdateProcessingList.Add(new FileProcessingDetails(INTFile.Value.DepotFile, INTFile.Value.ClientFile, INTFile.Value.ChangeList, FileProcessingDetails.State.Changed, INTFile.Value.CheckedOutByOthers, _connectionDetails));
                        }
                        else
                        {
                            // Already translated
                            LangFileTranslatedProcessingList.Add(new FileProcessingDetails(INTFile.Value.DepotFile, INTFile.Value.ClientFile, INTFile.Value.ChangeList, FileProcessingDetails.State.Translated, INTFile.Value.CheckedOutByOthers, _connectionDetails));
                        }
                    }
                }
                else
                {
                    LangFileToCreateProcessingList.Add(new FileProcessingDetails(INTFile.Value.DepotFile, INTFile.Value.ClientFile, INTFile.Value.ChangeList, FileProcessingDetails.State.New, INTFile.Value.CheckedOutByOthers, _connectionDetails));
                    string LangClientFileName =  GetLangFileNameFromInt( INTFile.Value.ClientFile );
                    if ( !(new System.IO.FileInfo(LangClientFileName)).Exists )
                    {
                        //Add Changelist number of INT file to top of lang file as metadata
                        string FileContents = "INTSourceChangelist:0" + Environment.NewLine +
                                                System.IO.File.ReadAllText(INTFile.Value.ClientFile, Encoding.UTF8);
                        System.IO.File.WriteAllText(LangClientFileName, FileContents, Encoding.UTF8);
                        if (CheckConnect())
                        {
                            using (Connection P4Connection = P4Repository.Connection)
                            {
                                FileSpec[] CurrentClientFile = new FileSpec[1];
                                CurrentClientFile[0] = new FileSpec(null, new ClientPath(LangClientFileName), null, null);

                                try
                                {
                                    P4Connection.Client.AddFiles(CurrentClientFile, null);
                                    FilesCheckedOut.Add( GetLangFileNameFromInt(INTFile.Value.DepotFile) );
                                }
                                catch (P4CommandTimeOutException Error)
                                {
                                    //do not continue
                                    log.Error(Error.Message);
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            //Setup list of files for move
            log.Info("Checking list of language files to be moved");
            LangFileToMoveProcessingList.Clear();
            foreach (var LangFile in LangFileProcessingDictionary)
            {
                FileProcessingDetails MovedFromFileDetails;
                if (INTMovedFileFromProcessingDictionary.TryGetValue(LangFile.Key, out MovedFromFileDetails))
                {

                    log.Info("Locating destination of language files that need to be moved - This is a long process");
                    var MovedToFileDetails = GetMovedToLocation(MovedFromFileDetails);

                    LangFileToMoveProcessingList.Add(new MoveFileProcessingDetails(LangFile.Value.DepotFile,
                                                                                   LangFile.Value.ClientFile,
                                                                                   GetLangFileNameFromInt(MovedToFileDetails.DepotFile),
                                                                                   GetLangFileNameFromInt(MovedToFileDetails.ClientFile),
                                                                                   MovedToFileDetails.ChangeList,
                                                                                   MovedToFileDetails.CheckedOutByOthers));
                }
            }

            //Setup list of files for delete
            log.Info("Generating list of language files needing to be deleted");
            LangFileToDeleteProcessingList.Clear();
            foreach (var LangFile in LangFileProcessingDictionary)
            {
                if (INTDeletedFileProcessingDictionary.ContainsKey(LangFile.Key))
                {
                    LangFileToDeleteProcessingList.Add(new FileProcessingDetails(LangFile.Value.DepotFile, LangFile.Value.ClientFile, LangFile.Value.ChangeList, FileProcessingDetails.State.Delete, false, _connectionDetails));
                }
            }
            //Update buttons to match counts
            UpdateButtonText();

        }
Exemple #45
0
        private static PathSpec TraceP4Location(Repository p4Repository, FileSpec originalFile, DateTime date)
        {
            var history = p4Repository.GetFileHistory(
                new Options(), originalFile);

            foreach (var historyFile in history)
            {
                if (historyFile.Date < date)
                {
                    return historyFile.DepotPath;
                }
            }

            return null;
        }
        /// <summary>
        /// Construct a P4ChangelistSpanQuery from the labels specified as parameters; the labels are not required to be in order
        /// </summary>
        /// <param name="InQueryLabelStart">The start or end date for the query</param>
        /// <param name="InQueryLabelEnd">The start or end date for the query, whichever wasn't specified by the first parameter</param>
        /// <param name="InDepotFilter">Path to filter the depot by</param>
        /// <param name="InUserFilter">User to filter the depot by, can be empty string</param>
        public P4ChangelistSpanQuery(Label InQueryLabelStart, Label InQueryLabelEnd, String InDepotFilter, String InUserFilter = "")
            : base(InDepotFilter, InUserFilter)
        {
            // Reorder the changelists increasing
            ReOrder(ref InQueryLabelStart, ref InQueryLabelEnd);

            LabelNameVersion StartLabel = new LabelNameVersion(InQueryLabelStart.Id);
            LabelNameVersion EndLabel = new LabelNameVersion(InQueryLabelEnd.Id);

            VersionRange Versions = new VersionRange(StartLabel, EndLabel);

            mFileFilter = new FileSpec(new DepotPath(InDepotFilter), null, null, Versions);
        }