public void File_Spaces_Are_Removed()
        {
            var originalValue = "THIS IS UPPER CASE";
            var testValue     = FileSystemTools.SanitizeFileName(originalValue, true, true);

            Assert.That(testValue.Contains(" ") == false);
        }
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        string pathToPlayerData         = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), Path.GetFileNameWithoutExtension(pathToBuiltProject) + "_Data");
        string pathToPlayerDataMiddleVR = Path.Combine(pathToPlayerData, "MiddleVR");

        // Copy web assets
        string webAssetsPathSource = Path.Combine(Path.Combine(Application.dataPath, "MiddleVR"), "WebAssets");

        if (Directory.Exists(webAssetsPathSource))
        {
            // The player executable file and the data folder share the same base name
            string webAssetsPathDestination = Path.Combine(pathToPlayerDataMiddleVR, "WebAssets");
            FileSystemTools.DirectoryCopy(webAssetsPathSource, webAssetsPathDestination, true, true);
        }

        // Copy web assets in hidden directory
        string dotWebAssetsPathSource = Path.Combine(Path.Combine(Application.dataPath, "MiddleVR"), ".WebAssets");

        if (Directory.Exists(dotWebAssetsPathSource))
        {
            // The player executable file and the data folder share the same base name
            string dotWebAssetsPathDestination = Path.Combine(pathToPlayerDataMiddleVR, ".WebAssets");
            FileSystemTools.DirectoryCopy(dotWebAssetsPathSource, dotWebAssetsPathDestination, true, true);
        }

        // Sign Application
        MVRTools.SignApplication(pathToBuiltProject);
    }
        public void Path_Spaces_Are_Not_Removed()
        {
            var originalValue = "THIS IS UPPER CASE";
            var testValue     = FileSystemTools.SanitizeDirectoryName(originalValue, false, true);

            Assert.That(testValue.Contains(" "));
        }
Esempio n. 4
0
        private string MakeFileName()
        {
            string fileName = string.Format(CultureInfo.InvariantCulture, "{0} {1:yyyy-MM-dd-HH-mm-ss}-{2}.{3}", SessionFileNamePrefix(Publisher.SessionSummary.Product, Publisher.SessionSummary.Application),
                                            Publisher.SessionSummary.StartDateTime.UtcDateTime, m_CurrentSessionFile, LogExtension);

            return(FileSystemTools.SanitizeFileName(fileName));
        }
        public void Path_Is_Lower_Case()
        {
            var originalValue = "THIS IS UPPER CASE";
            var testValue     = FileSystemTools.SanitizeDirectoryName(originalValue, false, true);

            Assert.That(originalValue.ToLowerInvariant(), Is.EqualTo(testValue));
        }
Esempio n. 6
0
        /// <summary>
        /// Open a new output file.
        /// </summary>
        /// <remarks>Any existing file will be closed.</remarks>
        private void OpenFile()
        {
            //clear the existing file pointer to make sure if we fail, it's gone.
            //we also rely on this to distinguish adding a new file to an existing stream.
            CloseFile(false);

            //increment our session file counter since we're going to open a new file
            m_CurrentSessionFile++;

            //Calculate our candidate file name (with path) based on what we know.
            string fileNamePath = Path.Combine(m_RepositoryFolder, MakeFileName());

            //now double check that the candidate path is unique
            fileNamePath = FileSystemTools.MakeFileNamePathUnique(fileNamePath);

            //we now have a unique file name, create the file.
            FileSystemTools.EnsurePathExists(fileNamePath);
            m_CurrentFile = new FileStream(fileNamePath, FileMode.CreateNew, FileAccess.Write);

            //and open a serializer on it
            m_CurrentSerializer = new GLFWriter(m_CurrentFile, Publisher.SessionSummary, m_CurrentSessionFile, DateTimeOffset.Now);

            //write out every header packet to the stream
            ICachedMessengerPacket[] headerPackets = Publisher.HeaderPackets;
            if (headerPackets != null)
            {
                foreach (ICachedMessengerPacket packet in headerPackets)
                {
                    m_CurrentSerializer.Write(packet);
                }
            }

            //and set a time for us to do our next index update.
            m_FileExpiration = DateTime.Now.AddSeconds(m_MaxLogDurationSeconds);
        }
        protected override PackageSendEventArgs OnSend(ProgressMonitorStack progressMonitors)
        {
            int             fileSizeBytes = 0;
            AsyncTaskResult result;
            string          statusMessage;
            Exception       taskException = null;

            try
            {
                //all we do is save the file out to our target path.
                Package.Save(progressMonitors, FileNamePath); // Uh-oh, we have to save it again!

                result        = AsyncTaskResult.Success;
                fileSizeBytes = (int)FileSystemTools.GetFileSize(FileNamePath);
                statusMessage = string.Format(CultureInfo.CurrentCulture, "Package written to file {0}",
                                              Path.GetFileNameWithoutExtension(FileNamePath));
            }
            catch (Exception ex)
            {
                result        = AsyncTaskResult.Error;
                statusMessage =
                    "Unable to save the package to disk.\r\n\r\nIt's possible that you don't have sufficient access to the directory to write the file or the media is read-only.";
                taskException = ex;
            }

            return(new PackageSendEventArgs(fileSizeBytes, result, statusMessage, taskException));
        }
        /// <summary>
        /// Create a repository publish engine for the specified local repository to the remote server.
        /// </summary>
        /// <param name="productName">Required. The product to restrict sending to.</param>
        /// <param name="applicationName">Optional.  The application to restrict sending to.</param>
        /// <param name="directory">Optional.  The base directory of the repository, overriding the system default.</param>
        /// <param name="serverConfiguration">The server to publish to.</param>
        public RepositoryPublishEngine(string productName, string applicationName, string directory,
                                       ServerConfiguration serverConfiguration)
        {
            if (serverConfiguration == null)
            {
                throw new ArgumentNullException(nameof(serverConfiguration));
            }

            if (string.IsNullOrWhiteSpace(productName))
            {
                throw new ArgumentNullException(nameof(productName));
            }

            m_ProductName                = productName;
            m_ApplicationName            = applicationName;
            m_Configuration              = serverConfiguration;
            m_SessionPublishThreadFailed = true;  //otherwise we won't start it when we need to.

            //find the repository path we're using.  We use the same logic that the FileMessenger users.
            m_RepositoryFolder = LocalRepository.CalculateRepositoryPath(productName, directory);

            //create the correct lock name for our scope.
            m_MultiprocessLockName = BaseMultiprocessLockName + "~" + productName +
                                     (string.IsNullOrEmpty(applicationName) ? string.Empty : "~" + applicationName);

            //we have to make sure the multiprocess lock doesn't have any unsafe characters.
            m_MultiprocessLockName = FileSystemTools.SanitizeFileName(m_MultiprocessLockName);

            BackgroundStartupDelay = 0;
        }
Esempio n. 9
0
        public void GetNextAvailableFilename()
        {
            var          tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            const string fixedFileName = "file.txt";
            var          firstFilePath = Path.Combine(tempDirectory, fixedFileName);

            //No directory
            Assert.AreEqual(FileSystemTools.GetNextAvailableFilename(firstFilePath), null);

            Directory.CreateDirectory(tempDirectory);

            //No file
            Assert.AreEqual(FileSystemTools.GetNextAvailableFilename(firstFilePath), firstFilePath);

            //First file
            WriteRandomTextToFile(firstFilePath);
            var filePath = Path.Combine(tempDirectory, "file2.txt");

            Assert.AreEqual(FileSystemTools.GetNextAvailableFilename(firstFilePath), filePath);

            //Second file
            WriteRandomTextToFile(filePath);
            filePath = Path.Combine(tempDirectory, "file3.txt");
            Assert.AreEqual(FileSystemTools.GetNextAvailableFilename(firstFilePath), filePath);

            //Clean up
            var di = new DirectoryInfo(tempDirectory);

            foreach (var file in di.GetFiles())
            {
                file.Delete();
            }

            Directory.Delete(tempDirectory);
        }
Esempio n. 10
0
        /// <summary>
        /// Shared logic for creating all streams
        /// </summary>
        public static StreamWriter CreateStream(string fileNamePath)
        {
            FileSystemTools.EnsurePathExists(fileNamePath);

            // Create the stream
            Log.Write(LogMessageSeverity.Verbose, LogCategory, "Creating file to export session data", fileNamePath);
            return(new StreamWriter(File.Create(fileNamePath)));
        }
Esempio n. 11
0
 public void Path_Tabs_Are_Removed()
 {
     {
         var originalValue = "THIS\tIS\tUPPER\tCASE";
         var testValue     = FileSystemTools.SanitizeDirectoryName(originalValue, false, true);
         Assert.That(testValue.Contains("\t") == false);
     }
 }
Esempio n. 12
0
 public void FixtureInit()
 {
     if (Directory.Exists(ScreenshotsFolder))
     {
         FileSystemTools.DeleteDirectory(ScreenshotsFolder);
     }
     Directory.CreateDirectory(ScreenshotsFolder);
 }
            public void AcceptsNull()
            {
                // ReSharper disable StringLiteralTypo
                var result   = FileSystemTools.SanitizeFileName(null);
                var expected = string.Empty;

                // ReSharper restore StringLiteralTypo
                Assert.AreEqual(expected, result);
            }
Esempio n. 14
0
        /// <summary>
        /// Save the package to the specified file name and path, overwriting any existing data
        /// </summary>
        /// <param name="progressMonitors"></param>
        /// <param name="fileNamePath"></param>
        public void Save(ProgressMonitorStack progressMonitors, string fileNamePath)
        {
            if (string.IsNullOrEmpty(fileNamePath))
            {
                throw new ArgumentNullException(nameof(fileNamePath), "Unable to save the current package because no path has been set to save to.");
            }

            //normalize the destination
            fileNamePath = Path.GetFullPath(fileNamePath);

            //make sure the path exists so we can save into it.
            FileSystemTools.EnsurePathExists(fileNamePath);

            lock (m_Lock)
            {
                int steps          = 2;
                int completedSteps = 0;
                using (ProgressMonitor ourMonitor = progressMonitors.NewMonitor(this, "Saving Package", steps))
                {
                    //Do the save (if this fails, we failed)
                    ourMonitor.Update("Saving Package File to Disk", completedSteps++);

                    m_Archive.Dispose(); // ...So we need to dispose and reopen the archive.

                    //check to see if we're saving to the same file we *are*...
                    if (fileNamePath.Equals(m_FileNamePath, StringComparison.OrdinalIgnoreCase) == false)
                    {
                        File.Copy(m_FileNamePath, fileNamePath, true);
                        try
                        {
                            File.Delete(m_FileNamePath);
                        }
                        catch (Exception ex)
                        {
                            if (!Log.SilentMode)
                            {
                                Log.Write(LogMessageSeverity.Error, LogWriteMode.Queued, ex, LogCategory,
                                          "Unable to Delete Package Temporary File due to " + ex.GetType(),
                                          "Unable to delete the temporary working file '{0}'. This means we'll use more disk space than we should but otherwise should not impact the application.",
                                          m_FileNamePath);
                            }
                        }

                        m_FileNamePath = fileNamePath;
                    }

                    ourMonitor.Update("Confirming package contents", completedSteps++);

                    //Since we were successful at saving, this is our new path and we are no longer dirty.
                    m_FileNamePath = fileNamePath;
                    m_Archive      = ZipFile.Open(m_FileNamePath, ZipArchiveMode.Update); // Now we should again be able to read any entry.
                    LoadIndex();
                    IsDirty = false;
                }
            }
        }
Esempio n. 15
0
        public RsViewProfileManager() : base()
        {
            FileInfo lBinInfo = new FileInfo(System.Windows.Forms.Application.ExecutablePath);

            this.ApplicationPath = FileSystemTools.toPath(lBinInfo.Directory.FullName);

            this.WinUserProfilePath = FileSystemTools.toPath(System.Environment.GetEnvironmentVariable("APPDATA"));
            this.RsViewProfilePath  = FileSystemTools.toPath(WinUserProfilePath + SETTINGSDIR);
            FileSystemTools.forcePath(this.RsViewProfilePath);
        }
Esempio n. 16
0
        public int ExecuteWithRetry()
        {
            if (this.consoleArgumentsProvider.ShouldDeleteOldTestResultFiles && File.Exists(consoleArgumentsProvider.TestResultPath))
            {
                File.Delete(consoleArgumentsProvider.TestResultPath);
            }


            System.Console.Out.WriteLine("Iteration #1  - First call to MsText.exe");
            this.testProcessManager.ExecuteInitialRun(consoleArgumentsProvider);

            var masterTestRun = FileSystemTools.DeserializeTestRun(consoleArgumentsProvider.TestResultPath);

            var testsToRepeat = new List <string>();

            testsToRepeat = this.testRunProvider.GetNamesOfNotPassedTests(masterTestRun);

            if (testRunProvider.CalculateRepeatPercentage(masterTestRun) <= this.consoleArgumentsProvider.FailedTestsThreshold)
            {
                // We've already done the first iteration. This loop performs the rest
                for (int iterationNumber = 2; iterationNumber <= this.consoleArgumentsProvider.RetriesCount + 1; iterationNumber++)
                {
                    // If we made all test succeed, exit!
                    if (testsToRepeat.Count == 0)
                    {
                        break;
                    }

                    System.Console.Out.WriteLine("Iteration #{0,2} - Rerunning {1} failed tests.", iterationNumber, testsToRepeat.Count);

                    string tempTestResultsPath = FileSystemTools.GetTempTrxFile();
                    testProcessManager.ExecuteIterativeRun(testsToRepeat, tempTestResultsPath, consoleArgumentsProvider);

                    var currentIterativeTestRun = FileSystemTools.DeserializeTestRun(tempTestResultsPath);

                    // Update master results file
                    this.testRunProvider.UpdateMasterRunWithNewIteration(iterationNumber, masterTestRun, currentIterativeTestRun);

                    if (File.Exists(this.consoleArgumentsProvider.NewTestResultPath))
                    {
                        File.Delete(this.consoleArgumentsProvider.NewTestResultPath);
                    }
                    FileSystemTools.SerializeTestRun(masterTestRun, consoleArgumentsProvider.NewTestResultPath);

                    testsToRepeat = this.testRunProvider.GetNamesOfNotPassedTests(currentIterativeTestRun);
                }
            }

            FileSystemTools.SerializeTestRun(masterTestRun, consoleArgumentsProvider.NewTestResultPath);

            int returnCode = testsToRepeat.Count > 0 ? 1 : 0;

            return(returnCode);
        }
Esempio n. 17
0
    private static void CopyFolderIfExists(string iFolderName, string iSrcBasePath, string iDstBasePath)
    {
        string sourcePath = Path.Combine(iSrcBasePath, iFolderName);

        if (Directory.Exists(sourcePath))
        {
            // The player executable file and the data folder share the same base name
            string destinationPath = Path.Combine(iDstBasePath, iFolderName);
            FileSystemTools.DirectoryCopy(sourcePath, destinationPath, true, true);
        }
    }
Esempio n. 18
0
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        string renderingPlugin32Path = pathToBuiltProject.Replace(".exe", "_Data/Plugins/MiddleVR_UnityRendering.dll");
        string renderingPlugin64Path = pathToBuiltProject.Replace(".exe", "_Data/Plugins/MiddleVR_UnityRendering_x64.dll");

        switch (target)
        {
        case BuildTarget.StandaloneWindows:
        {
            Debug.Log("[ ] 32-bit build : delete " + renderingPlugin64Path);

            // Delete x64 version
            if (System.IO.File.Exists(renderingPlugin64Path))
            {
                System.IO.File.Delete(renderingPlugin64Path);
            }

            break;
        }

        case BuildTarget.StandaloneWindows64:
        {
            Debug.Log("[ ] 64-bit build : delete " + renderingPlugin32Path + " and rename " + renderingPlugin64Path);

            // Delete 32b version...
            if (System.IO.File.Exists(renderingPlugin32Path))
            {
                System.IO.File.Delete(renderingPlugin32Path);
            }

            // ...and rename x64 version
            if (System.IO.File.Exists(renderingPlugin64Path))
            {
                System.IO.File.Move(renderingPlugin64Path, renderingPlugin32Path);
            }

            break;
        }
        }

        // Copy web assets for HTML5 default GUI
        string webAssetsPathSource      = Application.dataPath + System.IO.Path.DirectorySeparatorChar + "/MiddleVR/.WebAssets";
        string webAssetsPathDestination = pathToBuiltProject.Replace(".exe", "_Data/MiddleVR/.WebAssets");

        FileSystemTools.DirectoryCopy(webAssetsPathSource, webAssetsPathDestination, true, true);

        // Sign Application
        MVRTools.SignApplication(pathToBuiltProject);
    }
        private int m_FailedAttempts;                                 //PROTECTED BY THREADLOCK

        internal RepositoryPublishEngine(Publisher publisher, AgentConfiguration configuration)
        {
            m_ProductName                = publisher.SessionSummary.Product;
            m_ApplicationName            = publisher.SessionSummary.Application;
            m_Configuration              = configuration.Server;
            m_SessionPublishThreadFailed = true;  //otherwise we won't start it when we need to.

            //find the repository path we're using.  We use the same logic that the FileMessenger users.
            m_RepositoryFolder = LocalRepository.CalculateRepositoryPath(m_ProductName, configuration.SessionFile.Folder);

            //create the correct lock name for our scope.
            m_MultiprocessLockName = BaseMultiprocessLockName + "~" + m_ProductName +
                                     (m_Configuration.SendAllApplications ? string.Empty : "~" + m_ApplicationName);

            //we have to make sure the multiprocess lock doesn't have any unsafe characters.
            m_MultiprocessLockName = FileSystemTools.SanitizeFileName(m_MultiprocessLockName);
        }
Esempio n. 20
0
 private void ScreenshotOnFailure()
 {
     try
     {
         var status = TestContext.CurrentContext.Result.Outcome.Status.ToString();
         if (status.Equals(TestStatus.Failed.ToString()))
         {
             var fileName = FileSystemTools.ReplaceIllegalFilenameCharacters(FullTestMethodName) + "_" + DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt") + ".png";
             var filePath = Path.Combine(ScreenshotsFolder, fileName);
             new TakeScreenShot(browser.getDriver).TakeScreenshot(filePath);
             Log.Error("{0}.{1} generated an error. {1}A Screenshot of the browser has been saved.: {2}", FullTestMethodName, Environment.NewLine, filePath);
         }
     }
     catch (Exception e)
     {
         Log.Error("Encountered error while saving screenshot {0}{1}", Environment.NewLine, e.Message);
     }
 }
Esempio n. 21
0
        /// <summary>
        /// Adds the provided session to the package
        /// </summary>
        /// <param name="sessionStream"></param>
        public void AddSession(Stream sessionStream)
        {
            using (GLFReader glfReader = new GLFReader(sessionStream)) // This will dispose the stream when it is disposed.
            {
                if (!glfReader.IsSessionStream)
                {
                    throw new GibraltarException("The data stream provided is not a valid session data stream.");
                }

                if (!Log.SilentMode)
                {
                    Log.Write(LogMessageSeverity.Verbose, LogCategory, "Stream is session file, attempting to load", null);
                }

                lock (m_Lock)
                {
                    //Add this stream to our zip archive
                    string fileName = glfReader.SessionHeader.HasFileInfo ? string.Format("{0}~{1}.{2}", glfReader.SessionHeader.Id, glfReader.SessionHeader.FileId, Log.LogExtension)
                                          : string.Format("{0}.{1}", glfReader.SessionHeader.Id, Log.LogExtension);

                    string zipFilePath = GenerateFragmentPath(glfReader.SessionHeader.FileId);

                    ZipArchiveEntry fragmentEntry;
                    if (m_Archive.Mode == ZipArchiveMode.Update)
                    {
                        fragmentEntry = m_Archive.GetEntry(zipFilePath);
                        if (fragmentEntry != null)
                        {
                            fragmentEntry.Delete(); //wipe out any existing entry
                        }
                    }

                    fragmentEntry = m_Archive.CreateEntry(FragmentsFolder + "\\" + fileName, CompressionLevel.NoCompression); //session files are already highly compressed, no reason to waste effort.

                    using (var zipStream = fragmentEntry.Open())
                    {
                        FileSystemTools.StreamContentCopy(sessionStream, zipStream, false); // Copy the stream into our package's temp directory.
                    }

                    IsDirty = true;
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Inheritors should override this method to implement custom initialize functionality.
        /// </summary>
        /// <remarks>This method will be called exactly once before any call to OnFlush or OnWrite is made.
        /// Code in this method is protected by a Thread Lock.
        /// This method is called with the Message Dispatch thread exclusively.</remarks>
        protected override void OnInitialize(IMessengerConfiguration configuration)
        {
            //do our first time initialization
            Caption     = "Standard File Messenger";
            Description = "Messenger implementation that writes messages to files through a buffer.  Supports synchronous and asynchronous messaging.";

            //try to up cast the configuration to our specific configuration type
            var fileConfiguration = (SessionFileConfiguration)configuration;

            //If the max file size is unbounded (zero or less) then we want 1GB.
            m_MaxFileSizeBytes = fileConfiguration.MaxFileSize < 1 ? 1024 : fileConfiguration.MaxFileSize;
            m_MaxFileSizeBytes = m_MaxFileSizeBytes * 1048576;                //the configured value is in MB, we use bytes for faster comparisons

            m_MaxLogDurationSeconds = fileConfiguration.MaxFileDuration * 60; //the configured value is in minutes, we use seconds for consistency

            m_RepositoryMaintenanceEnabled = fileConfiguration.EnableFilePruning;
            m_MaxLocalDiskUsage            = fileConfiguration.MaxLocalDiskUsage;
            m_MaxLocalFileAge = fileConfiguration.MaxLocalFileAge;

            //what are the very best folders for us to use?
            m_RepositoryFolder  = LocalRepository.CalculateRepositoryPath(Publisher.SessionSummary.Product, fileConfiguration.Folder);
            m_SessionLockFolder = Path.Combine(m_RepositoryFolder, SessionLockFolderName);

            //we also have to be sure the path exists now.
            FileSystemTools.EnsurePathExists(m_RepositoryFolder);
            FileSystemTools.EnsurePathExists(m_SessionLockFolder);

            //Since we update the index during a flush, and the index update is about as bad as a flush we look at both together.
            AutoFlush         = true;
            AutoFlushInterval = Math.Min(fileConfiguration.AutoFlushInterval, fileConfiguration.IndexUpdateInterval);

            //If we aren't able to initialize our log folder, throw an exception
            if (string.IsNullOrEmpty(m_RepositoryFolder))
            {
                throw new DirectoryNotFoundException("No log folder could be determined, so the file messenger can't log.");
            }

            ScheduleRepositoryMaintenance(0, 0);

            GetSessionFileLock();
        }
Esempio n. 23
0
        /// <summary>
        /// Load the specified session
        /// </summary>
        /// <returns>The loaded session.  If no session can be found with the specified Id an ArgumentOutOfRangeException will be thrown.</returns>
        public Session GetSession(Guid sessionId, Guid?fileId = null)
        {
            Session requestedSession = null;

            lock (m_Lock)
            {
                SessionFileInfo <ZipArchiveEntry> sessionFileInfo;
                if (m_Sessions.TryGetValue(sessionId, out sessionFileInfo) == false)
                {
                    throw new ArgumentOutOfRangeException(nameof(sessionId), "There is no session in the package with the provided id");
                }

                //now load up all of the session fragments.
                var loadingCollection = new SessionCollection();

                foreach (var fragment in sessionFileInfo.Fragments)
                {
                    //we need a seek-able stream - so we'll extract the fragment into a temp file and go with that.
                    if (fileId != null)
                    {
                        //we need to check the file Id to see if it's what they requested
                        using (var reader = new GLFReader(FileSystemTools.GetTempFileStreamCopy(fragment.Open())))
                        {
                            if (reader.SessionHeader.FileId != fileId.Value)
                            {
                                continue;
                            }
                        }
                    }

                    requestedSession = loadingCollection.Add(FileSystemTools.GetTempFileStreamCopy(fragment.Open()), true);
                }
            }

            if (requestedSession == null)
            {
                throw new ArgumentOutOfRangeException(nameof(fileId), "There is no session file in the package with the provided file id");
            }

            return(requestedSession);
        }
Esempio n. 24
0
        public bool ShowOpenROIDocumentDialog(string defaultDataDirectory, List <string> companiesList, string documentPath = "")
        {
            UIServices.SetBusyState();

            var editROIDocView       = new EditROIDocumentView();
            var roiDocumentViewModel = new ROIDocumentViewModel {
                DocumentPath = documentPath, DataDirectory = defaultDataDirectory
            };

            //Pre-populate new report's default name
            if (string.IsNullOrEmpty(documentPath))
            {
                roiDocumentViewModel.IsNewReport = true;
                roiDocumentViewModel.ROIDocument.DocumentName = Path.GetFileNameWithoutExtension(
                    FileSystemTools.GetNextAvailableFilename(Path.Combine(defaultDataDirectory, "ROIDocument.xml")));

                //Todo: Recall modal last new report defaults (culture, etc.)
            }

            roiDocumentViewModel.CompaniesList = companiesList;
            roiDocumentViewModel.LoadExistingImages();

            var editReportCommand = new ButtonServiceCommand("Reporting", roiDocumentViewModel.EditReportCommand, false, false, false);
            var okCommand         = new ButtonServiceCommand("OK", roiDocumentViewModel.SaveROIDocumentCommand, false, false, true);
            var cancelCommand     = new ButtonServiceCommand("Cancel", roiDocumentViewModel.CancelCommand, true, false, true);

            var result = dialogService.ShowDialogWindow($"Edit {roiDocumentViewModel.ROIDocument.DocumentName}", new[] { editReportCommand, okCommand, cancelCommand }, null, editROIDocView, roiDocumentViewModel, false);

            if (result == okCommand)
            {
                var gridSaveDirectory = Path.Combine(defaultDataDirectory, Constants.AppSettingsDirectoryName);
                if (!Directory.Exists(gridSaveDirectory))
                {
                    Directory.CreateDirectory(gridSaveDirectory);
                }
                editROIDocView.SaveDocumentGrids(gridSaveDirectory);
                return(true);
            }

            return(false);
        }
Esempio n. 25
0
        /// <summary>
        /// Add a session from the provided GLF File stream
        /// </summary>
        /// <param name="fileStream">A file stream of a GLF File to read.</param>
        /// <param name="useOriginalStream">If true, the caller no longer owns the stream and must not further use or dispose
        /// it. If false, the method will copy the contents of the stream before returning and will restore its Position,
        /// so the caller is responsible for eventually disposing it.</param>
        /// <returns>The session object that was affected.</returns>
        public Session Add(Stream fileStream, bool useOriginalStream)
        {
            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            long originalPosition = fileStream.Position;

            if (GLFReader.IsGLF(fileStream) == false) // This also throws an exception if the stream is not seekable.
            {
                fileStream.Position = originalPosition;
                throw new ArgumentException("The provided data stream is not a valid GLF session stream.", nameof(fileStream));
            }

            Stream newStream;

            if (useOriginalStream == false)
            {
                // Uh-oh, the caller wants to keep the stream themselves.  We need to punt a copy from the original stream.
                fileStream.Position = 0;                                                 // Reset its position to the start of the file to copy from the start.
                newStream           = FileSystemTools.GetTempFileStreamCopy(fileStream); // Get a delete-on-close temp file copied from it.
                newStream.Position  = originalPosition;                                  // Should it do this?

                fileStream.Position = originalPosition;                                  // And set it back where it had been.
            }
            else
            {
                // Otherwise, they're saying the file will stick around for us.  We own it now.  Or rather, the GLFReader will.
                newStream = fileStream;
            }

            GLFReader glfReader = new GLFReader(newStream);

            //now forward to our GLF Reader add which is shared with other things
            Session newSession = Add(glfReader);

            return(newSession);
        }
Esempio n. 26
0
        private void InstallFactoryReportTemplates(bool doFactoryReset = false)
        {
            var reportTemplateDirectory = Path.Combine(DataDirectory, Constants.ReportTemplateDirectoryName);

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

            if ((Directory.GetFiles(reportTemplateDirectory, "*.repx", SearchOption.TopDirectoryOnly).Length == 0) || doFactoryReset)
            {
                var factoryTemplateFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates");
                foreach (var file in Directory.GetFiles(factoryTemplateFolder, "*.repx", SearchOption.TopDirectoryOnly).ToList())
                {
                    if (doFactoryReset)
                    {
                        var targetFilePath = Path.Combine(reportTemplateDirectory, Path.GetFileName(file));
                        try
                        {
                            if (DialogService.Instance.ShowMessageQuestion(
                                    $"{Path.GetFileName(file)} already exists. Create a backup copy?", "Backup Template"))
                            {
                                var backupTargetFilePath = FileSystemTools.GetNextAvailableFilename(targetFilePath);
                                File.Move(targetFilePath, backupTargetFilePath);
                            }
                            File.Copy(file, targetFilePath, true);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    else
                    {
                        File.Copy(file, Path.Combine(reportTemplateDirectory, Path.GetFileName(file)));
                    }
                }
            }
        }
Esempio n. 27
0
        private void CloneROIDocument()
        {
            var selectedROIViewModel = SelectedRoiDocViewModelList[0];

            if (selectedROIViewModel == null)
            {
                return;
            }

            var suggestedFileNameNoExt = Path.GetFileNameWithoutExtension(FileSystemTools.GetNextAvailableFilename(Path.Combine(DataDirectory,
                                                                                                                                Path.GetFileNameWithoutExtension(selectedROIViewModel.DocumentPath) + "-copy.xml")));

            var reportName = DialogService.Instance.InputDialog("Clone Report", "", "Enter new report name:",
                                                                suggestedFileNameNoExt);

            if (string.IsNullOrEmpty(reportName))
            {
                return;
            }

            var newReportFilePath = Path.Combine(Path.GetDirectoryName(selectedROIViewModel.DocumentPath), reportName + ".xml");

            if (File.Exists(newReportFilePath))
            {
                DialogService.Instance.ShowMessageError("Error: File already exists: " + Environment.NewLine + Environment.NewLine + newReportFilePath);
            }
            else
            {
                File.Copy(SelectedRoiDocViewModelList[0].DocumentPath, newReportFilePath);
                var roiDocumentViewModel = new ROIDocumentViewModel
                {
                    DocumentPath  = newReportFilePath,
                    DataDirectory = DataDirectory,
                    ROIDocument   = { DocumentName = reportName, DateCreated = DateTime.Now, DateModified = DateTime.Now }
                };
                roiDocumentViewModel.SaveROIDocument();
                ScanFileSystemForROIDocuments();
            }
        }
Esempio n. 28
0
        /// <summary>
        /// The temporary path to put all of the transfer information for this session.
        /// </summary>
        /// <returns></returns>
        private string GenerateTemporarySessionPath()
        {
            //find the right temporary directory for us...
            //if this is a real repository, we'll use a persistent path.
            //otherwise we'll use something truly temporary and have to clean up after ourselves.
            string tempDirectory;

            if (Repository != null)
            {
                tempDirectory = Path.Combine(Repository.TempPath, SessionTempFolder);
            }
            else
            {
                tempDirectory = FileSystemTools.GetTempFileName();
                File.Delete(tempDirectory); //we just want it as a directory, not a file.
                m_DeleteTemporaryFilesOnDispose = true;
            }

            //make damn sure it exists.
            Directory.CreateDirectory(tempDirectory);

            return(tempDirectory);
        }
Esempio n. 29
0
        /// <summary>
        /// Retrieve the ids of the sessions files known locally for the specified session
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public IList <Guid> GetSessionFileIds(Guid sessionId)
        {
            lock (m_Lock)
            {
                SessionFileInfo <ZipArchiveEntry> sessionFileInfo;
                if (m_Sessions.TryGetValue(sessionId, out sessionFileInfo) == false)
                {
                    throw new ArgumentOutOfRangeException(nameof(sessionId), "There is no session in the package with the provided id");
                }

                var fileIds = new List <Guid>();
                foreach (var fragment in sessionFileInfo.Fragments)
                {
                    //this is kinda crappy - we have to make a copy of the whole fragment to get a seekable stream to read the id.
                    using (var reader = new GLFReader(FileSystemTools.GetTempFileStreamCopy(fragment.Open())))
                    {
                        fileIds.Add(reader.SessionHeader.FileId);
                    }
                }

                return(fileIds);
            }
        }
Esempio n. 30
0
 public virtual void Write(Stream sessionPacketStream)
 {
     FileSystemTools.StreamContentPump(sessionPacketStream, m_OutputStream);
 }