public string CountOccurrences()
        {
            int occurrences = 0;

            for (int i = 0; i <= (TemplateString.Length - ScanningString.Length - 1); i++)
            {
                string substringBeingTested;
                string modifiedScanningString;
                if (i == 0)
                {
                    modifiedScanningString = ScanningString + " ";
                }
                else if (i == (TemplateString.Length - ScanningString.Length - 1))
                {
                    modifiedScanningString = " " + ScanningString;
                }
                else
                {
                    modifiedScanningString = " " + ScanningString + " ";
                }

                substringBeingTested = TemplateString.Substring(i, (modifiedScanningString.Length));
                if (substringBeingTested == modifiedScanningString)
                {
                    occurrences += 1;
                }
            }
            return("Your search string occurs: " + occurrences + " times in the host string.");
        }
Exemple #2
0
 public InvalidFileLocationIssue(FileInformation file, TemplateString directoryPathTemplate, IReadOnlyList <FilenameSuggestion> suggestions, string correctFilename)
 {
     File = file;
     DirectoryPathTemplate = directoryPathTemplate;
     Suggestions           = suggestions;
     CorrectFilename       = correctFilename;
 }
Exemple #3
0
        private void RenderDockerfile(TemplateString workingFolder)
        {
            if (Directory.Exists(workingFolder))
            {
                Directory.CreateDirectory(workingFolder);
            }

            var dockerFile = Path.Combine(workingFolder, "Dockerfile");

            string contents = null;

            if (!string.IsNullOrEmpty(_config.UseFile))
            {
                contents = _config.UseFile.FromFile();
            }

            if (!string.IsNullOrWhiteSpace(_config.DockerFileString))
            {
                contents = _config.DockerFileString;
            }

            if (string.IsNullOrEmpty(contents))
            {
                contents = _config.ToString();
            }

            contents.ToFile(dockerFile);
        }
        /// <summary>
        ///   Copies file or directories (recursively) to the <paramref name="workdir" /> and returns a relative
        ///   linux compatible¨path string to be used in e.g. a Dockerfile.
        /// </summary>
        /// <param name="fileOrDirectory">The file or directory to copy to <paramref name="workdir" />.</param>
        /// <param name="workdir">The working directory to copy the file or directory to.</param>
        /// <returns>A relative path to <paramref name="workdir" /> in linux format. If fails it will return null.</returns>
        /// <remarks>
        ///   If the <paramref name="fileOrDirectory" /> is on format emb://namespace/file format it will use
        ///   <see
        ///     cref="ResourceExtensions.ToFile(System.Collections.Generic.IEnumerable{Ductus.FluentDocker.Resources.ResourceInfo},TemplateString)" />
        ///   to perform the copy. Only one file is permitted and thus the file or directory parameter is always a single file.
        /// </remarks>
        public static string Copy(this TemplateString fileOrDirectory, TemplateString workdir)
        {
            var fd = fileOrDirectory.Rendered.EscapePath();

            if (fd.StartsWith($"{EmbeddedUri.Prefix}:"))
            {
                return(new EmbeddedUri(fd).ToFile(workdir));
            }

            if (File.Exists(fd))
            {
                var file = Path.GetFileName(fd);
                File.Copy(fd, Path.Combine(workdir, file));
                return(file);
            }

            if (!Directory.Exists(fd))
            {
                return(null);
            }

            CopyTo(fd, workdir);

            // Return the relative path of workdir
            return(Path.GetFileName(Path.GetFullPath(fd).TrimEnd(Path.DirectorySeparatorChar)));
        }
        private string GenerateBuildingNameFromFormat(string nameFormat, BuildingNameGroups nameGroups)
        {
            var template = new TemplateString(nameFormat);

            var results = new HashSet <string>();

            foreach (var field in template.TemplateFields)
            {
                var nameGroup = nameGroups.NameParts[field.FieldName];

                var nameResult = _randomItemSelector.GetRandomWeightedItem(nameGroup);
                while (results.Contains(nameResult.NamePart))
                {
                    nameResult = _randomItemSelector.GetRandomWeightedItem(nameGroup);
                }
                results.Add(nameResult.NamePart);

                var regex = new Regex(Regex.Escape(field.FieldTemplate));
                nameFormat = regex.Replace(nameFormat, nameResult.NamePart, 1);
            }

            // There are template results that then reference another template.
            if (nameFormat.Contains("{"))
            {
                nameFormat = GenerateBuildingNameFromFormat(nameFormat, nameGroups);
            }

            return(nameFormat);
        }
        public static void CopyTo(this TemplateString sourceDirectory, TemplateString targetDirectory)
        {
            var sd = sourceDirectory.Rendered.EscapePath();
            var td = targetDirectory.Rendered.EscapePath();

            CopyAll(new DirectoryInfo(sd), new DirectoryInfo(td));
        }
        private void ProcessOpeningBrace()
        {
            Pos++;
            if (Pos < TemplateString.Length && TemplateString[Pos] == '{')
            {
                Pos++;
                FormatBuilder.Append("{{");
                OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
                return;
            }

            if (ClosingBraceIndex < 0)
            {
                FormatBuilder.Append("{{");
                OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
                return;
            }

            var selectorExpression = TemplateString.Substring(Pos, ClosingBraceIndex - Pos);
            var valueSelector      = CreateValueSelector(selectorExpression);

            FormatBuilder.Append("{" + ValueSelectors.Count + "}");
            ValueSelectors.Add(valueSelector);

            Pos = ClosingBraceIndex + 1;
            OpeningBraceIndex = TemplateString.IndexOf("{", Pos);
            ClosingBraceIndex = TemplateString.IndexOf("}", Pos);
        }
Exemple #8
0
        /// <summary>
        ///   Copies all files and folders to working directory.
        ///   Note that this method will mutate <see cref="AddCommand.Source" /> to
        ///   a relative path!!
        /// </summary>
        /// <param name="workingFolder">The working folder.</param>
        private void CopyToWorkDir(TemplateString workingFolder)
        {
            // Copy all files from copy arguments.
            foreach (var cp in _config.Commands.Where(x => x is CopyCommand).Cast <CopyCommand>())
            {
                if (!File.Exists(cp.From))
                {
                    continue;
                }

                var wp  = Path.Combine(workingFolder, cp.From);
                var wdp = Path.GetDirectoryName(wp);
                Directory.CreateDirectory(wdp);
                File.Copy(cp.From, wp, true /*overwrite*/);
            }

            foreach (var command in _config.Commands.Where(x => x is AddCommand).Cast <AddCommand>())
            {
                var wff = Path.Combine(workingFolder, command.Source);
                if (File.Exists(wff) || Directory.Exists(wff))
                {
                    // File or folder already at working folder - no need to copy.
                    continue;
                }

                // Replace to relative path
                command.Source = command.Source.Copy(workingFolder);
            }
        }
Exemple #9
0
 public FileBuilder Add(TemplateString source, TemplateString destination)
 {
     _config.AddRunCommands.Add(new AddCommand {
         Source = source, Destination = destination
     });
     return(this);
 }
Exemple #10
0
        internal string PrepareBuild()
        {
            TemplateString workingFolder = @"${TEMP}\fluentdockertest\${RND}";

            CopyToWorkDir(workingFolder); // Must be before RenderDockerFile!
            RenderDockerfile(workingFolder);
            return(workingFolder);
        }
Exemple #11
0
 private void btn_ChangeTemplate_Click(object sender, System.EventArgs e)
 {
     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         TemplateString.ChangeTemplateFile(openFileDialog1.FileName, _selectedTemplateType);
         SetTemplateString();
     }
 }
Exemple #12
0
 /// <summary>
 ///   Copies all files and folders to working directory.
 ///   Note that this method will mutate <see cref="AddCommand.Source" /> to
 ///   a relative path!!
 /// </summary>
 /// <param name="workingFolder">The working folder.</param>
 private void CopyToWorkDir(TemplateString workingFolder)
 {
     foreach (var command in _config.AddRunCommands.Where(x => x is AddCommand).Cast <AddCommand>())
     {
         // Replace to relative path
         command.Source = command.Source.Copy(workingFolder);
     }
 }
        public ComposeServiceBuilder Volume(TemplateString containerPath, TemplateString hostPath)
        {
            _config.Volumes.Add(new ShortServiceVolumeDefinition
            {
                Entry = $"{hostPath.Rendered.EscapePath()}:{containerPath.Rendered.EscapePath()}"
            });

            return(this);
        }
        public static string FromFile(this TemplateString fqPath, Encoding encoding = null)
        {
            if (null == encoding)
            {
                encoding = Encoding.UTF8;
            }

            return(File.ReadAllText(fqPath.Rendered.EscapePath(), encoding));
        }
Exemple #15
0
        public PhotoDirectory(IFileSystem fileSystem, string rootDirectory, PhotoDirectoryConfig config,
                              DbContextOptions <AppDbContext> dbOptions, IDirectoryMemoryManager directoryMemoryManager)
        {
            _fileSystem    = fileSystem;
            _rootDirectory = rootDirectory.ToForwardSlashes().TrimEnd('/');

            _photoFilenameTemplate = TemplateString.Parse(config.TemplatePath.ToForwardSlashes());
            _dbOptions             = dbOptions;
            MemoryManager          = directoryMemoryManager;
        }
Exemple #16
0
        public TemplateString GetFilenameTemplate(FileInformation fileInformation)
        {
            var values = FilePlaceholderFiller.GetPlaceholders(
                _photoFilenameTemplate.Fragments.OfType <PlaceholderFragment>().Select(x => x.Value), fileInformation);
            var nonNullValues = values.Where(x => x.Value != null).ToDictionary(x => x.Key, x => x.Value !);

            var path = _photoFilenameTemplate.ToString(nonNullValues).ToForwardSlashes();

            return(TemplateString.Parse(path));
        }
        public void GivenNoPlaceholders_HasNoPlaceholders_ToString()
        {
            // arrange
            var s = new TemplateString(new[] { new TextFragment("hello"), new TextFragment("world") });

            // act
            var result = s.ToString();

            // assert
            Assert.Equal("helloworld", result);
        }
        public static void ToFile(this string contents, TemplateString fqPath)
        {
            var folder = Path.GetDirectoryName(fqPath.Rendered.EscapePath());

            if (null != folder && !Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            File.WriteAllText(fqPath.Rendered.EscapePath(), contents);
        }
        private void ProcessClosingBrace()
        {
            Pos++;
            if (Pos < TemplateString.Length && TemplateString[Pos] == '}')
            {
                Pos++;
            }

            FormatBuilder.Append("}}");
            ClosingBraceIndex = TemplateString.IndexOf("}", Pos);
        }
Exemple #20
0
        public static MailTemplate BuildMailTemplate(MailTemplate template, KeyValueVariables keyValues, KeyTableVariables keyTables)
        {
            if (template == null)
            {
                throw new ArgumentException("参数不能为null!", "template");
            }
            template.Subject = TemplateString.BuildHtml(template.Subject, keyValues, keyTables);
            template.Body    = TemplateString.BuildHtml(template.Subject, keyValues, keyTables);

            return(template);
        }
        public void UnifiedSeparatorWillBeTranslatedOnWindows()
        {
            if (!FdOs.IsWindows())
            {
                return;
            }

            var path = new TemplateString(@"${TEMP}/folder/${RND}");

            Assert.IsTrue(path.ToString().IndexOf(@"\folder\", StringComparison.Ordinal) != -1);
        }
        public void UrlAtTheEndOfStringShallNotBeAlteredOnWindows()
        {
            if (!FdOs.IsWindows())
            {
                return;
            }

            var tst = new TemplateString("/foo/bar/cmd \"https://kalle.hoobe.net/hejohå.txt\"");

            Assert.IsTrue(tst.Rendered.IndexOf("\"https://kalle.hoobe.net/hejohå.txt\"", StringComparison.Ordinal) == 13);
        }
        public void UrlWithinAPowershellExpressionOnWindowsShallLeaveUrlUntouched()
        {
            if (!FdOs.IsWindows())
            {
                return;
            }

            var tst = new TemplateString("RUN Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))");

            Assert.IsTrue(tst.Rendered.IndexOf("'https://chocolatey.org/install.ps1'", StringComparison.Ordinal) == 108);
        }
        public void UrlAtTheBeginningOfStringShallNotBeAlteredOnWindows()
        {
            if (!FdOs.IsWindows())
            {
                return;
            }

            var tst = new TemplateString("\"https://kalle.hoobe.net/hejohå.txt\" ${TEMP}/folder/${RND}");

            Assert.IsTrue(tst.Rendered.IndexOf("\"https://kalle.hoobe.net/hejohå.txt\"", StringComparison.Ordinal) == 0);
        }
Exemple #25
0
        internal string PrepareBuild()
        {
            if (null == _workingFolder)
            {
                _workingFolder = @"${TEMP}/fluentdockertest/${RND}";
            }

            CopyToWorkDir(_workingFolder); // Must be before RenderDockerFile!
            RenderDockerfile(_workingFolder);
            return(_workingFolder);
        }
Exemple #26
0
        public static MailTemplate BuildMailTemplate(string templateID, KeyValueVariables keyValues, KeyTableVariables keyTables)
        {
            MailTemplate entity = GetMailTemplate(templateID);

            if (entity == null)
            {
                throw new ApplicationException("目标模板[" + templateID + "]未找到!");
            }
            entity.Subject = TemplateString.BuildHtml(entity.Subject, keyValues, keyTables);
            entity.Body    = TemplateString.BuildHtml(entity.Body, keyValues, keyTables);

            return(entity);
        }
        public void IsIsPossibleToHaveSeveralUrlsInSameStringNotAffectingWindowsPathSubstitution()
        {
            if (!FdOs.IsWindows())
            {
                return;
            }

            var tst = new TemplateString("/foo/bar/cmd \"https://kalle.hoobe.net/hejohå.txt\" \"http://kalle.hoobe.net/hejohå.txt\"");
            var res = tst.Rendered.IndexOf("\"http://kalle.hoobe.net/hejohå.txt\"", StringComparison.Ordinal);

            Assert.IsTrue(tst.Rendered.IndexOf("\"https://kalle.hoobe.net/hejohå.txt\"", StringComparison.Ordinal) == 13);
            Assert.IsTrue(tst.Rendered.IndexOf("\"http://kalle.hoobe.net/hejohå.txt\"", StringComparison.Ordinal) == 50);
        }
        public void GivenPlaceholders_HasNoPlaceholders_ToString()
        {
            // arrange
            var s = new TemplateString(new ITemplateFragment[] { new TextFragment("hello"), new TextFragment("world") });

            // act
            var result = s.ToString(new Dictionary <string, string> {
                { "what", "is that" }
            });

            // assert
            Assert.Equal("helloworld", result);
        }
        public async Task <IList <string> > FindMatchingDirectories(TemplateString directoryTemplate)
        {
            const char escapeChar = '\\';

            var pattern = directoryTemplate.ToLikePattern(escapeChar);

            if (!pattern.EndsWith("%"))
            {
                pattern += "%";                         // as we match file names with a directory pattern
            }
            return(await _appDbContext.Set <FileLocation>().Where(x => EF.Functions.Like(x.RelativeFilename, pattern, escapeChar.ToString()))
                   .Select(x => x.RelativeFilename.Substring(0, x.RelativeFilename.LastIndexOf('/'))).Distinct().ToListAsync());
        }
Exemple #30
0
        /// <summary>
        ///   Extracts embedded resource based on the inparam <paramref name="assemblyAndNamespace" />,
        ///   <see cref="Assembly" /> and <see cref="Type.Namespace" />.
        /// </summary>
        /// <param name="assemblyAndNamespace">The assemlby and namesspace to start searching for resources to extract.</param>
        /// <param name="targetPath">The target base filepath to start the extraction from.</param>
        /// <param name="files">
        ///   Optional explicit files that are direct children of the <paramref name="assemblyAndNamespace" />
        ///   namespace.
        /// </param>
        /// <remarks>
        ///   This function extract recursively embedded resources if no <paramref name="files" /> has been specified. If any
        ///   <paramref name="files" /> has been specifies it won't do a recurive extraction, instead all files in the provided
        ///   namespace (in <paramref name="assemblyAndNamespace" />) will be matched against the <paramref name="files" />.
        /// </remarks>
        public static void ResourceExtract(this Type assemblyAndNamespace, TemplateString targetPath, params string[] files)
        {
            if (null == files || 0 == files.Length)
            {
                assemblyAndNamespace.ResuorceQuery().ToFile(targetPath);
                return;
            }

            new ResourceQuery().From(assemblyAndNamespace.GetTypeInfo().Assembly.GetName().Name)
            .Namespace(assemblyAndNamespace.Namespace, false)
            .Include(files)
            .ToFile(targetPath);
        }