Exemple #1
0
        /// <summary>
        /// Find a file which, on a development machine, lives in [solution]/DistFiles/[subPath],
        /// and when installed, lives in
        /// [applicationFolder]/[subPath1]/[subPathN]
        /// </summary>
        /// <example>GetFileDistributedWithApplication("info", "releaseNotes.htm");</example>
        public static string GetDirectoryDistributedWithApplication(bool optional, params string[] partsOfTheSubPath)
        {
            var path = FileLocator.DirectoryOfApplicationOrSolution;

            foreach (var part in partsOfTheSubPath)
            {
                path = System.IO.Path.Combine(path, part);
            }
            if (Directory.Exists(path))
            {
                return(path);
            }

            foreach (var directoryHoldingFiles in new[] { "", "DistFiles", "common" /*for wesay*/, "src" /*for Bloom*/ })
            {
                path = Path.Combine(FileLocator.DirectoryOfApplicationOrSolution, directoryHoldingFiles);
                foreach (var part in partsOfTheSubPath)
                {
                    path = System.IO.Path.Combine(path, part);
                }
                if (Directory.Exists(path))
                {
                    return(path);
                }
            }

            if (optional && !Directory.Exists(path))
            {
                return(null);
            }

            RequireThat.Directory(path).Exists();
            return(path);
        }
Exemple #2
0
        //TODO: get rid of this, or somehow combine it with the other Clone() options out there
        /// <returns>path to clone, or empty if it failed</returns>
        private static string MakeCloneFromLocalToLocal(string sourcePath, string targetDirectory, bool cloningFromUsb, IProgress progress)
        {
            RequireThat.Directory(sourcePath).Exists();
            //Handled by GetUniqueFolderPath call now down in CloneLocal call. RequireThat.Directory(targetDirectory).DoesNotExist();
            RequireThat.Directory(targetDirectory).Parent().Exists();

            HgRepository local = new HgRepository(sourcePath, progress);

            if (!local.RemoveOldLocks())
            {
                progress.WriteError("Chorus could not create the clone at this time.  Try again after restarting the computer.");
                return(string.Empty);
            }

            using (new ConsoleProgress("Trying to Create repository clone at {0}", targetDirectory))
            {
                // Make a backward compatibile clone if cloning to USB (http://mercurial.selenic.com/wiki/UpgradingMercurial)
                targetDirectory = local.CloneLocalWithoutUpdate(targetDirectory, cloningFromUsb ? null : "--config format.dotencode=false --pull");
                File.WriteAllText(Path.Combine(targetDirectory, "~~Folder has an invisible repository.txt"), "In this folder, there is a (possibly hidden) folder named '.hg' that contains the actual data of this Chorus repository. Depending on your Operating System settings, that leading '.' might make the folder invisible to you. But Chorus clients (WeSay, FLEx, OneStory, etc.) can see it and can use this folder to perform Send/Receive operations.");

                if (cloningFromUsb)
                {
                    var clone = new HgRepository(targetDirectory, progress);
                    clone.Update();
                }
                return(targetDirectory);
            }
        }
Exemple #3
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Use this for creating new or existing elements
        /// </summary>
        /// <param name="parentElementFolder">E.g. "c:/MyProject/Sessions"</param>
        /// <param name="id">e.g. "ETR007"</param>
        /// <param name="idChangedNotificationReceiver"></param>
        /// <param name="componentFileFactory"></param>
        /// <param name="xmlFileSerializer">used to load/save</param>
        /// <param name="fileType"></param>
        /// <param name="prjElementComponentFileFactory"></param>
        /// <param name="componentRoles"></param>
        /// ------------------------------------------------------------------------------------
        protected ProjectElement(string parentElementFolder, string id,
                                 Action <ProjectElement, string, string> idChangedNotificationReceiver, FileType fileType,
                                 Func <ProjectElement, string, ComponentFile> componentFileFactory,
                                 XmlFileSerializer xmlFileSerializer,
                                 ProjectElementComponentFile.Factory prjElementComponentFileFactory,
                                 IEnumerable <ComponentRole> componentRoles)
        {
            _componentFileFactory = componentFileFactory;
            ComponentRoles        = componentRoles;
            RequireThat.Directory(parentElementFolder).Exists();

            StageCompletedControlValues = (ComponentRoles == null ?
                                           new Dictionary <string, StageCompleteType>() :
                                           ComponentRoles.ToDictionary(r => r.Id, r => StageCompleteType.Auto));

            ParentFolderPath = parentElementFolder;
            _id = id ?? GetNewDefaultElementName();
            IdChangedNotificationReceiver = idChangedNotificationReceiver;

            MetaDataFile = prjElementComponentFileFactory(this, fileType, xmlFileSerializer, RootElementName);

            if (File.Exists(SettingsFilePath))
            {
                Load();
            }
            else
            {
                Directory.CreateDirectory(FolderPath);
                Save();
            }
        }
 public static AnnotationRepository FromFile(string primaryRefParameter, string path, IProgress progress)
 {
     try
     {
         if (!File.Exists(path))
         {
             RequireThat.Directory(Path.GetDirectoryName(path)).Exists();
             File.WriteAllText(path, string.Format("<notes version='{0}'/>", kCurrentVersion.ToString()));
         }
         var doc = XDocument.Load(path);
         ThrowIfVersionTooHigh(doc, path);
         var result = new AnnotationRepository(primaryRefParameter, doc, path, progress);
         // Set up a watcher so that if something else...typically FLEx...modifies our file, we update our display.
         // This is useful in its own right for keeping things consistent, but more importantly, if we don't do
         // this and then the user does something in FlexBridge that changes the file, we could overwrite the
         // changes made elsewhere (LT-20074).
         result.UpateAnnotationFileWriteTime();
         result._watcher = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
         result._watcher.NotifyFilter        = NotifyFilters.LastWrite;
         result._watcher.Changed            += result.UnderlyingFileChanged;
         result._watcher.EnableRaisingEvents = true;
         return(result);
     }
     catch (XmlException error)
     {
         throw new AnnotationFormatException(string.Empty, error);
     }
 }
 public Configurator(string folderInWhichToReadAndSaveLibrarySettings)
 {
     _folderInWhichToReadAndSaveLibrarySettings = folderInWhichToReadAndSaveLibrarySettings;
     PathToLibraryJson = _folderInWhichToReadAndSaveLibrarySettings.CombineForPath("configuration.txt");
     RequireThat.Directory(folderInWhichToReadAndSaveLibrarySettings).Exists();
     LocalData = string.Empty;
 }
Exemple #6
0
        //TODO: get rid of this, or somehow combine it with the other Clone() options out there
        /// <returns>path to clone, or empty if it failed</returns>
        public static string MakeCloneFromLocalToLocal(string sourcePath, string targetDirectory, bool alsoDoCheckout, IProgress progress)
        {
            RequireThat.Directory(sourcePath).Exists();
            //Handled by GetUniqueFolderPath call now down in CloneLocal call. RequireThat.Directory(targetDirectory).DoesNotExist();
            RequireThat.Directory(targetDirectory).Parent().Exists();

            HgRepository local = new HgRepository(sourcePath, progress);

            if (!local.RemoveOldLocks())
            {
                progress.WriteError("Chorus could not create the clone at this time.  Try again after restarting the computer.");
                return(string.Empty);
            }

            using (new ConsoleProgress("Trying to Create repository clone at {0}", targetDirectory))
            {
                targetDirectory = local.CloneLocalWithoutUpdate(targetDirectory);
                File.WriteAllText(Path.Combine(targetDirectory, "~~Folder has an invisible repository.txt"), "In this folder, there is a (possibly hidden) folder named '.hg' that contains the actual data of this Chorus repository. Depending on your Operating System settings, that leading '.' might make the folder invisible to you. But Chorus clients (WeSay, FLEx, OneStory, etc.) can see it and can use this folder to perform Send/Receive operations.");

                if (alsoDoCheckout)
                {
                    // string userIdForCLone = string.Empty; /* don't assume it's this user... a repo on a usb key probably shouldn't have a user default */
                    var clone = new HgRepository(targetDirectory, progress);
                    clone.Update();
                }
                return(targetDirectory);
            }
        }
Exemple #7
0
        public delegate Configurator Factory(string folderInWhichToReadAndSaveCollectionSettings);        //autofac uses this

        public Configurator(string folderInWhichToReadAndSaveCollectionSettings, NavigationIsolator isolator)
        {
            _folderInWhichToReadAndSaveCollectionSettings = folderInWhichToReadAndSaveCollectionSettings;
            _isolator            = isolator;
            PathToCollectionJson = _folderInWhichToReadAndSaveCollectionSettings.CombineForPath("configuration.txt");
            RequireThat.Directory(folderInWhichToReadAndSaveCollectionSettings).Exists();
            LocalData = string.Empty;
        }
Exemple #8
0
        /// ------------------------------------------------------------------------------------
        public ElementRepository(string projectDirectory, string elementGroupName,
                                 FileType type, ElementFactory elementFactory)
        {
            ElementFileType = type;
            _elementFactory = elementFactory;
            RequireThat.Directory(projectDirectory).Exists();

            _rootFolder = Path.Combine(projectDirectory, elementGroupName);

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

            RefreshItemList();
        }
        ///<summary>
        /// Show settings for an existing project. The project doesn't need to have any
        /// previous chorus activity (e.g. no .hg folder is needed).
        ///</summary>
        public virtual void InitFromProjectPath(string path)
        {
            RequireThat.Directory(path).Exists();

            var repo = HgRepository.CreateOrUseExisting(path, new NullProgress());

            _pathToRepo = repo.PathToRepo;

            var address = repo.GetDefaultNetworkAddress <HttpRepositoryPath>();

            if (address != null)
            {
                InitFromUri(address.URI);
            }

            //otherwise, just leave everything in the default state
        }
		public static AnnotationRepository FromFile(string primaryRefParameter, string path, IProgress progress)
		{
			try
			{
				if(!File.Exists(path))
				{
					RequireThat.Directory(Path.GetDirectoryName(path)).Exists();
					File.WriteAllText(path, string.Format("<notes version='{0}'/>", kCurrentVersion.ToString()));
				}
				var doc = XDocument.Load(path);
				ThrowIfVersionTooHigh(doc, path);
				return new AnnotationRepository(primaryRefParameter, doc, path, progress);
			}
			catch (XmlException error)
			{
				throw new AnnotationFormatException(string.Empty, error);
			}
		}
        public static bool Create(string pathToNewDirectory, string pathToSourceLift)
        {
            try
            {
                Logger.WriteEvent(@"Starting Project creation from " + pathToSourceLift);

                if (!ReportIfLocked(pathToSourceLift))
                {
                    return(false);
                }

                RequireThat.Directory(pathToNewDirectory).DoesNotExist();

                Directory.CreateDirectory(pathToNewDirectory);

                CopyOverLiftFile(pathToSourceLift, pathToNewDirectory);

                CopyOverRangeFileIfExists(pathToSourceLift, pathToNewDirectory);

                CopyOverLdmlFiles(pathToSourceLift, BasilProject.GetPathToLdmlWritingSystemsFolder(pathToNewDirectory));

                File.Create(Path.Combine(pathToNewDirectory, ".newlycreatedfromFLEx")).Dispose();

                //The config file is created on project open when all of the orphaned writing systems have been identified.

                Logger.WriteEvent(@"Finished Importing");
                return(true);
            }
            catch (Exception e)
            {
                Palaso.Reporting.ErrorReport.NotifyUserOfProblem(e, "WeSay was unable to finish importing that LIFT file.  If you cannot fix the problem yourself, please zip and send the exported folder to issues (at) wesay (dot) org");
                try
                {
                    Logger.WriteEvent(@"Removing would-be target directory");
                    Directory.Delete(pathToNewDirectory, true);
                }
                catch (Exception)
                {
                    //swallow
                }
                return(false);
            }
        }
Exemple #12
0
        public SendReceiveSettings(string repositoryLocation)
        {
            InitializeComponent();

            RequireThat.Directory(repositoryLocation).Exists();
            var repository = HgRepository.CreateOrUseExisting(repositoryLocation, new NullProgress());

            _model = new SettingsModel(repository);
            userNameTextBox.Text = _model.GetUserName(new NullProgress());

            _internetModel = new ServerSettingsModel();
            _internetModel.InitFromProjectPath(repositoryLocation);
            _serverSettingsControl.Model = _internetModel;

            _internetButtonEnabledCheckBox.CheckedChanged += internetCheckChanged;
            _internetButtonEnabledCheckBox.Checked         = Properties.Settings.Default.InternetEnabled;
            _serverSettingsControl.Enabled = _internetButtonEnabledCheckBox.Checked;

            _showChorusHubInSendReceive.Checked = Properties.Settings.Default.ShowChorusHubInSendReceive;
        }
        /// <summary>
        /// Do whatever is needed to do more than just show a title and thumbnail
        /// </summary>
        private void ExpensiveInitialization()
        {
            Debug.WriteLine(string.Format("ExpensiveInitialization({0})", _folderPath));
            _dom = new HtmlDom();
            //the fileLocator we get doesn't know anything about this particular book.
            _fileLocator.AddPath(_folderPath);
            RequireThat.Directory(_folderPath).Exists();
            if (!File.Exists(PathToExistingHtml))
            {
                var files = new List <string>(Directory.GetFiles(_folderPath));
                var b     = new StringBuilder();
                b.AppendLine("Could not determine which html file in the folder to use.");
                if (files.Count == 0)
                {
                    b.AppendLine("***There are no files.");
                }
                else
                {
                    b.AppendLine("Files in this book are:");
                    foreach (var f in files)
                    {
                        b.AppendLine("  " + f);
                    }
                }
                throw new ApplicationException(b.ToString());
            }
            else
            {
                var xmlDomFromHtmlFile = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToExistingHtml, false);
                _dom = new HtmlDom(xmlDomFromHtmlFile);                 //with throw if there are errors

                //Validating here was taking a 1/3 of the startup time
                // eventually, we need to restructure so that this whole Storage isn't created until actually needed, then maybe this can come back
                //ErrorMessages = ValidateBook(PathToExistingHtml);
                // REVIEW: we did in fact change things so that storage isn't used until we've shown all the thumbnails we can (then we go back and update in background)...
                // so maybe it would be ok to reinstate the above?

                //For now, we really need to do this check, at least. This will get picked up by the Book later (feeling kludgy!)
                //I assume the following will never trigger (I also note that the dom isn't even loaded):


                if (!string.IsNullOrEmpty(ErrorMessages))
                {
                    //hack so we can package this for palaso reporting
//                    var ex = new XmlSyntaxException(ErrorMessages);
//                    Palaso.Reporting.ErrorReport.NotifyUserOfProblem(ex, "Bloom did an integrity check of the book named '{0}', and found something wrong. This doesn't mean your work is lost, but it does mean that there is a bug in the system or templates somewhere, and the developers need to find and fix the problem (and your book).  Please click the 'Details' button and send this report to the developers.", Path.GetFileName(PathToExistingHtml));
                    _dom.RawDom.LoadXml(
                        "<html><body>There is a problem with the html structure of this book which will require expert help.</body></html>");
                    Logger.WriteEvent(
                        "{0}: There is a problem with the html structure of this book which will require expert help: {1}",
                        PathToExistingHtml, ErrorMessages);
                }
                //The following is a patch pushed out on the 25th build after 1.0 was released in order to give us a bit of backwards version protection (I should have done this originally and in a less kludgy fashion than I'm forced to do now)
                else
                {
                    var incompatibleVersionMessage = GetMessageIfVersionIsIncompatibleWithThisBloom(Dom);
                    if (!string.IsNullOrWhiteSpace(incompatibleVersionMessage))
                    {
                        _dom.RawDom.LoadXml(
                            "<html><body style='background-color: white'><p/><p/><p/>" + WebUtility.HtmlEncode(incompatibleVersionMessage) + "</body></html>");
                        Logger.WriteEvent(PathToExistingHtml + " " + incompatibleVersionMessage);
                    }
                    else
                    {
                        Logger.WriteEvent("BookStorage Loading Dom from {0}", PathToExistingHtml);
                    }
                }

                //TODO: this would be better just to add to those temporary copies of it. As it is, we have to remove it for the webkit printing
                //SetBaseForRelativePaths(Dom, folderPath); //needed because the file itself may be off in the temp directory

                //UpdateStyleSheetLinkPaths(fileLocator);

                Dom.UpdatePageDivs();

                UpdateSupportFiles();
            }
        }
Exemple #14
0
        /// <summary>
        /// Do whatever is needed to do more than just show a title and thumbnail
        /// </summary>
        private void ExpensiveInitialization()
        {
            Debug.WriteLine(string.Format("ExpensiveInitialization({0})", _folderPath));
            _dom = new HtmlDom();
            //the fileLocator we get doesn't know anything about this particular book.
            _fileLocator.AddPath(_folderPath);
            RequireThat.Directory(_folderPath).Exists();
            if (!File.Exists(PathToExistingHtml))
            {
                var files = new List <string>(Directory.GetFiles(_folderPath));
                var b     = new StringBuilder();
                b.AppendLine("Could not determine which html file in the folder to use.");
                if (files.Count == 0)
                {
                    b.AppendLine("***There are no files.");
                }
                else
                {
                    b.AppendLine("Files in this book are:");
                    foreach (var f in files)
                    {
                        b.AppendLine("  " + f);
                    }
                }
                throw new ApplicationException(b.ToString());
            }
            else
            {
                //Validating here was taking a 1/3 of the startup time
                // eventually, we need to restructure so that this whole Storage isn't created until actually needed, then maybe this can come back
                //			ErrorMessages = ValidateBook(PathToExistingHtml);

                if (!string.IsNullOrEmpty(ErrorMessages))
                {
                    //hack so we can package this for palaso reporting
//                    var ex = new XmlSyntaxException(ErrorMessages);
//                    Palaso.Reporting.ErrorReport.NotifyUserOfProblem(ex, "Bloom did an integrity check of the book named '{0}', and found something wrong. This doesn't mean your work is lost, but it does mean that there is a bug in the system or templates somewhere, and the developers need to find and fix the problem (and your book).  Please click the 'Details' button and send this report to the developers.", Path.GetFileName(PathToExistingHtml));
                    _dom.RawDom.LoadXml(
                        "<html><body>There is a problem with the html structure of this book which will require expert help.</body></html>");
                    Logger.WriteEvent(
                        "{0}: There is a problem with the html structure of this book which will require expert help: {1}",
                        PathToExistingHtml, ErrorMessages);
                }
                else
                {
                    Logger.WriteEvent("BookStorage Loading Dom from {0}", PathToExistingHtml);

                    var xmlDomFromHtmlFile = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToExistingHtml, false);
                    _dom = new HtmlDom(xmlDomFromHtmlFile);                     //with throw if there are errors
                }

                //todo: this would be better just to add to those temporary copies of it. As it is, we have to remove it for the webkit printing
                //SetBaseForRelativePaths(Dom, folderPath); //needed because the file itself may be off in the temp directory

                //UpdateStyleSheetLinkPaths(fileLocator);

                Dom.UpdatePageDivs();

                UpdateSupportFiles();
            }
        }
Exemple #15
0
        public void CloneAndShrinkProject(string originalProjectFolder, string destinationFolder)
        {
            FFmpegRunner.FFmpegLocation = FFmpegDownloadHelper.FullPathToFFmpegForSayMoreExe;

            RequireThat.Directory(destinationFolder).DoesNotExist();
            RequireThat.Directory(originalProjectFolder).Exists();

            Directory.CreateDirectory(destinationFolder);
            //we don't currently process anything at this level, just copy it
            foreach (var original in Directory.GetFiles(originalProjectFolder))
            {
                File.Copy(original, Path.Combine(destinationFolder, Path.GetFileName(original)));
            }

            foreach (var directory in Directory.GetDirectories(originalProjectFolder))
            {
                var currentDestSubDirectory = Path.Combine(destinationFolder, Path.GetFileName(directory));
                Directory.CreateDirectory(currentDestSubDirectory);

                //we don't currently process anything at this level, just copy it
                foreach (var original in Directory.GetFiles(directory))
                {
                    File.Copy(original, Path.Combine(currentDestSubDirectory, Path.GetFileName(original)));
                }

                foreach (var sub in Directory.GetDirectories(directory))
                {
                    var currentDestSubSubDirectory = Path.Combine(currentDestSubDirectory, Path.GetFileName(sub));
                    Directory.CreateDirectory(currentDestSubSubDirectory);
                    foreach (var original in Directory.GetFiles(sub))
                    {
                        Debug.WriteLine("File: " + original);

                        if (original.Contains("-small"))
                        {
                            continue;
                        }
                        if (original.EndsWith(".meta"))
                        {
                            continue;
                        }
                        if (original.EndsWith(".smd"))                        //artifact of old version
                        {
                            continue;
                        }

                        var    extension   = Path.GetExtension(original).ToLower();
                        string newPath     = string.Empty;
                        var    newPathRoot = Path.Combine(currentDestSubSubDirectory, Path.GetFileNameWithoutExtension(original));
                        switch (extension)
                        {
                        default:
                            File.Copy(original, Path.Combine(currentDestSubSubDirectory, Path.GetFileName(original)));
                            break;

                        case ".mov":
                        case ".avi":
                        case ".mp4":
                            newPath = ShrinkVideo(original, newPathRoot);
                            break;

                        case ".jpg":
                            newPath = ShrinkPicture(original, newPathRoot);
                            break;

                        case ".wav":
                        case ".mp3":
                            newPath = ShrinkAudio(original, newPathRoot);
                            break;

                        case ".meta":
                            break;
                        }
                        if (!string.IsNullOrEmpty(newPath) && File.Exists(newPath) && File.Exists(original + ".meta"))
                        {
                            Debug.WriteLine("copying metadata");
                            File.Move(original + ".meta", newPath + ".meta");
                        }
                        Debug.WriteLine("");
                    }
                }
            }
        }