Exemple #1
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 #2
0
        public void WhenContainsNull_ThrowsException()
        {
            var enumerable = new [] { new object(), null, new object() };

            Assert.Throws <ArgumentException>(
                () => RequireThat.DoesNotContainNull(enumerable, "name"));
        }
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();
            }
        }
Exemple #4
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);
        }
 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 #7
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 #8
0
        /// <summary>
        /// Creates a specification that demands that at least one of the
        /// <paramref name="left"/> and <paramref name="right"/> specifications are satisfied.
        /// </summary>
        /// <param name="left">
        /// The left hand side of the operation.
        /// </param>
        /// <param name="right">
        /// The right hand side of the operation
        /// </param>
        /// <typeparam name="T">
        /// The type of entity this specification checks.
        /// </typeparam>
        /// <returns>
        /// An <see cref="ISpecification{T}"/> representing the logical OR operation of the
        /// specifications <paramref name="left"/> and <paramref name="right"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="left"/> or <paramref name="right"/> is null.
        /// </exception>
        public static ISpecification <T> Or <T>(this ISpecification <T> left, ISpecification <T> right)
        {
            RequireThat.NotNull(left, "left");
            RequireThat.NotNull(right, "right");

            return(new OrSpecification <T>(left, right));
        }
Exemple #9
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 #10
0
        private static void DoWarmup()
        {
            var foo = Guid.NewGuid().ToString() + Environment.TickCount.ToString();

            stopwatch.Start();
            while (stopwatch.ElapsedMilliseconds < 2000)
            {
                Require.That(foo, "foo").IsNotNullOrEmpty();
                Require.That(() => foo).IsNotNullOrEmpty();
                RequireThat.NotNullOrEmpty(foo, "foo");
            }

            stopwatch.Stop();
        }
Exemple #11
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 #15
0
        public void CanExpressRequirements()
        {
            var crmConnectionString = ConfigurationManager.ConnectionStrings["CrmOrganisationServiceConnectionString"].ConnectionString;

            var requirements = RequireThat.CrmOrganisation(crmConnectionString)
                               .HasSolution("SilverbearMembershipSolution")
                               .MinimumVersion("3.3.0.58")
                               .Gather();

            var result = requirements.Check();

            if (!result)
            {
                var unsatisfiedRequirements = requirements.GetUnsatisfiedRequirements();
                foreach (var requirement in unsatisfiedRequirements)
                {
                    Console.WriteLine(requirement.Message);
                }
            }
        }
Exemple #16
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;
        }
Exemple #17
0
        private static long[] RunSimpleTests()
        {
            Console.WriteLine("Running {0} iterations of {1} simple requirements each.", numberOfIterations, callsPerIteration);
            var results = new long[numberOfIterations];

            for (int i = 0; i < numberOfIterations; i++)
            {
                var foo = Guid.NewGuid().ToString() + Environment.TickCount.ToString();
                stopwatch.Reset();
                stopwatch.Start();
                for (int callCount = 0; callCount < callsPerIteration; callCount++)
                {
                    RequireThat.NotNullOrEmpty(foo, "foo");
                }

                stopwatch.Stop();
                results[i] = stopwatch.ElapsedTicks;
            }

            return(results);
        }
Exemple #18
0
 public void WhenNull_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(
         () => RequireThat.NotNullOrEmpty(null as string, "name"));
 }
Exemple #19
0
        /// <summary>
        /// Get a json of stats about the image. It is used to populate a tooltip when you hover over an image container
        /// </summary>
        private void HandleImageInfo(ApiRequest request)
        {
            try
            {
                var fileName = request.RequiredFileNameOrPath("image");
                Guard.AgainstNull(_bookSelection.CurrentSelection, "CurrentBook");
                var plainfilename = fileName.NotEncoded;
                // The fileName might be URL encoded.  See https://silbloom.myjetbrains.com/youtrack/issue/BL-3901.
                var path = UrlPathString.GetFullyDecodedPath(_bookSelection.CurrentSelection.FolderPath, ref plainfilename);
                RequireThat.File(path).Exists();
                var     fileInfo = new FileInfo(path);
                dynamic result   = new ExpandoObject();
                result.name  = plainfilename;
                result.bytes = fileInfo.Length;

                // Using a stream this way, according to one source,
                // http://stackoverflow.com/questions/552467/how-do-i-reliably-get-an-image-dimensions-in-net-without-loading-the-image,
                // supposedly avoids loading the image into memory when we only want its dimensions
                using (var stream = RobustFile.OpenRead(path))
                    using (var img = Image.FromStream(stream, false, false))
                    {
                        result.width  = img.Width;
                        result.height = img.Height;
                        switch (img.PixelFormat)
                        {
                        case PixelFormat.Format32bppArgb:
                        case PixelFormat.Format32bppRgb:
                        case PixelFormat.Format32bppPArgb:
                            result.bitDepth = "32";
                            break;

                        case PixelFormat.Format24bppRgb:
                            result.bitDepth = "24";
                            break;

                        case PixelFormat.Format16bppArgb1555:
                        case PixelFormat.Format16bppGrayScale:
                            result.bitDepth = "16";
                            break;

                        case PixelFormat.Format8bppIndexed:
                            result.bitDepth = "8";
                            break;

                        case PixelFormat.Format1bppIndexed:
                            result.bitDepth = "1";
                            break;

                        default:
                            result.bitDepth = "unknown";
                            break;
                        }
                    }
                request.ReplyWithJson((object)result);
            }
            catch (Exception e)
            {
                Logger.WriteEvent("Error in server imageInfo/: url was " + request.LocalPath());
                Logger.WriteEvent("Error in server imageInfo/: exception is " + e.Message);
                request.Failed(e.Message);
                NonFatalProblem.Report(ModalIf.None, PassiveIf.Alpha, "Request Error", request.LocalPath(), e);
            }
        }
Exemple #20
0
 public void WhenNonNullObject_DoesNotThrowException()
 {
     RequireThat.NotNull(new object(), "name");
 }
Exemple #21
0
 public void WhenOfDerivedType_DoesNotThrow()
 {
     RequireThat.IsOfType <IEnumerable>(new List <string>(), "name");
 }
Exemple #22
0
 public void WhenNull_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(
         () => RequireThat.DoesNotContainNull(null as IEnumerable, "name"));
 }
Exemple #23
0
 public void WhenNullNullable_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(
         () => RequireThat.NotNull(null as int?, "name"));
 }
Exemple #24
0
 public void WhenEmptyEnumerable_ThrowsException()
 {
     Assert.Throws <ArgumentException>(
         () => RequireThat.NotNullOrEmpty(Enumerable.Empty <object>(), "name"));
 }
Exemple #25
0
 public void WhenNotEmptyEnumerable_DoesNotThrow()
 {
     RequireThat.NotNullOrEmpty(Enumerable.Range(1, 1), "name");
 }
Exemple #26
0
 public void WhenNullEnumerable_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(
         () => RequireThat.NotNullOrEmpty(null as IEnumerable, "name"));
 }
Exemple #27
0
 public void WhenNotEmptyString_DoesNotThrow()
 {
     RequireThat.NotNullOrEmpty("value", "name");
 }
Exemple #28
0
 public void WhenEmptyString_ThrowsException()
 {
     Assert.Throws <ArgumentException>(
         () => RequireThat.NotNullOrEmpty("", "name"));
 }
Exemple #29
0
 public void WhenNullableWithoutValue_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(
         () => RequireThat.NotNull(new Nullable <int>(), "name"));
 }
Exemple #30
0
 public void WhenNullableWithValue_DoesNotThrow()
 {
     RequireThat.NotNull(new Nullable <int>(1), "name");
 }