public ContentFileInput AddContentFile(string fileName, string fileContent)
        {
            var contentFileInput = GetContentFileInput(fileName, fileContent);

            ContentFiles.Add(contentFileInput);
            return(contentFileInput);
        }
Example #2
0
        void UpdateContent()
        {
            SortedList <string, string> keys = new SortedList <string, string>();

            foreach (string v in GetParameters("ContentItems", Parameters.ContentItems, "Content"))
            {
                keys.Add(v, "Item");
            }

            foreach (ProjectItem i in BuildItems)
            {
                if (i.Name.StartsWith("_"))
                {
                    continue;
                }

                string name;
                if (!keys.TryGetValue(i.Name, out name))
                {
                    continue;
                }

                ContentFiles.AddUnique(i.Include);
            }
        }
Example #3
0
        public override bool Execute()
        {
            string outputFileName = String.Format("{0}.area-manifest.xml", AreaName);
            string outputFullPath = Path.Combine(ManifestPath, outputFileName);

            AreaInfo info = new AreaInfo()
            {
                Name         = AreaName,
                Path         = AreaPath,
                Type         = (AreaType)Enum.Parse(typeof(AreaType), AreaType),
                ContentFiles = ContentFiles.Select(o => o.ItemSpec).ToArray()
            };

            // ensure output directory exists before file creation
            string outputDir = Path.GetDirectoryName(outputFullPath);

            FileSystem.CreateDirectory(outputDir);

            XmlSerializer serializer = new XmlSerializer(typeof(AreaInfo));

            using (Stream stream = FileSystem.FileOpen(outputFullPath, FileMode.Create)) {
                serializer.Serialize(stream, info);
            }

            // if we got this far, success!
            return(true);
        }
        public bool Equals(LockFileTargetLibrary other)
        {
            if (other == null)
            {
                return(false);
            }

            if (Object.ReferenceEquals(this, other))
            {
                return(true);
            }

            return(string.Equals(Name, other.Name) &&
                   VersionComparer.Default.Equals(Version, other.Version) &&
                   string.Equals(Type, other.Type, StringComparison.Ordinal) &&
                   string.Equals(Framework, other.Framework, StringComparison.Ordinal) &&
                   Dependencies.OrderedEquals(other.Dependencies, dependency => dependency.Id, StringComparer.OrdinalIgnoreCase) &&
                   FrameworkAssemblies.OrderedEquals(other.FrameworkAssemblies, s => s, StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase) &&
                   FrameworkReferences.OrderedEquals(other.FrameworkReferences, s => s, StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase) &&
                   RuntimeAssemblies.OrderedEquals(other.RuntimeAssemblies, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   ResourceAssemblies.OrderedEquals(other.ResourceAssemblies, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   CompileTimeAssemblies.OrderedEquals(other.CompileTimeAssemblies, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   NativeLibraries.OrderedEquals(other.NativeLibraries, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   ContentFiles.OrderedEquals(other.ContentFiles, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   RuntimeTargets.OrderedEquals(other.RuntimeTargets, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   Build.OrderedEquals(other.Build, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   BuildMultiTargeting.OrderedEquals(other.BuildMultiTargeting, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   ToolsAssemblies.OrderedEquals(other.ToolsAssemblies, item => item.Path, StringComparer.OrdinalIgnoreCase) &&
                   EmbedAssemblies.OrderedEquals(other.EmbedAssemblies, item => item.Path, StringComparer.OrdinalIgnoreCase));
        }
 private bool HasLinkedWebConfigFile()
 {
     return(ContentFiles.Any(f =>
     {
         var link = f.GetMetadata("Link");
         var hasLink = !string.IsNullOrEmpty(link) && link.Equals("web.config", StringComparison.OrdinalIgnoreCase);
         return hasLink;
     }));
 }
Example #6
0
        public RepoPage()
        {
            this.InitializeComponent();
            DataTransferManager.GetForCurrentView().DataRequested += (sender, args) =>
            {
                DataRequest request = args.Request;
                request.Data.SetText(repo.html_url);
                request.Data.Properties.Title = "Github Repo, Shared by GithubX";
            };
            SizeChanged += (sender, args) =>
            {
                FilesList.Height =
                    MarkdownScrollViewer.Height =
                        ActualHeight -
                        92 -
                        buttonPanel.ActualHeight -
                        buttonPanel.Margin.Top -
                        32 -
                        48;
                //48 for expander
                //92 for header
                MarkdownText.Width = MarkdownScrollViewer.ActualWidth;
            };
            Loaded += async(sender, args) =>
            {
                PFix = string.Format("https://github.com/{0}/raw/master", repo.full_name);
                md   = LoadTheme();
                if (md == null)
                {
                    md = new MarkdownSetting();
                }
                try
                {
                    ContentFiles = await ApiHandler.GetContentListAsync(repo);

                    var readme = ContentFiles.Find(o => o.name.ToLower().Equals("readme.md"));
                    Url = readme.download_url;
                    var res = await ApiHandler.GetReadMeMdAsync(repo.id, Url, true);

                    MarkdownText.Text = res.Item2;
                    if (!res.Item1)
                    {
                        MainPage.NotifyElement.Show("There was a problem in loading README properly!", 2000);
                    }
                }
                catch { MarkdownText.Text = "> Nothing 😣"; }
                Bindings.Update();
                if (repo.Color == "#ffffff")
                {
                    MarkdownText.LinkForeground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.LightBlue);
                }
            };
        }
Example #7
0
        public ContentFileInput AddContentFile(string fileName, string fileContent)
        {
            var contentFileInput     = new ContentFileInput(fileName, fileContent);
            var existingContentFiles = ContentFiles.Where(cf => cf.FileName == fileName).ToList();

            if (existingContentFiles.Any())
            {
                existingContentFiles.ForEach(i => ContentFiles.Remove(i));
            }

            ContentFiles.Add(contentFileInput);
            return(contentFileInput);
        }
        public override int GetHashCode()
        {
            var combiner = new HashCodeCombiner();

            combiner.AddObject(Name);
            combiner.AddObject(Version);
            combiner.AddObject(Type);
            combiner.AddObject(Framework);

            foreach (var dependency in Dependencies.OrderBy(dependency => dependency.Id, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(dependency);
            }

            foreach (var reference in FrameworkAssemblies.OrderBy(s => s, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddStringIgnoreCase(reference);
            }

            foreach (var item in RuntimeAssemblies.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            foreach (var item in ResourceAssemblies.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            foreach (var item in CompileTimeAssemblies.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            foreach (var item in NativeLibraries.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            foreach (var item in ContentFiles.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            foreach (var item in RuntimeTargets.OrderBy(item => item.Path, StringComparer.OrdinalIgnoreCase))
            {
                combiner.AddObject(item);
            }

            return(combiner.CombinedHash);
        }
Example #9
0
        private void CopyContentFiles()
        {
            var contentFiles = new ContentFiles(_context);

            if (_compilerOptions.CopyToOutputInclude != null)
            {
                var includeEntries = IncludeFilesResolver.GetIncludeFiles(
                    _compilerOptions.CopyToOutputInclude,
                    PathUtility.EnsureTrailingSlash(_runtimeOutputPath),
                    diagnostics: null);

                contentFiles.StructuredCopyTo(_runtimeOutputPath, includeEntries);
            }
            else
            {
                contentFiles.StructuredCopyTo(_runtimeOutputPath);
            }
        }
Example #10
0
        private void FindContentAndScripts(XPathDocument doc)
        {
            SortedList <string, string> extensions = new SortedList <string, string>(StringComparer.OrdinalIgnoreCase);

            if (Parameters.ScriptExtensions != null)
            {
                foreach (string extension in Parameters.ScriptExtensions)
                {
                    string ext = extension;

                    if (!ext.StartsWith("."))
                    {
                        ext = '.' + ext;
                    }

                    if (!extensions.ContainsKey(ext))
                    {
                        extensions.Add(ext, "Item");
                    }
                }
            }

            foreach (XPathNavigator nav in doc.CreateNavigator().Select("//File[@RelativePath]"))
            {
                string file = nav.GetAttribute("RelativePath", "");
                bool   deploymentContent = ("true" == nav.GetAttribute("DeploymentContent", ""));

                if (deploymentContent)
                {
                    ContentFiles.AddUnique(file);
                }

                if (extensions.ContainsKey(Path.GetExtension(file)))
                {
                    ScriptFiles.AddUnique(file);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Publish the project for given 'framework (ex - netstandardapp1.5)' and 'runtimeID (ex - win7-x64)'
        /// </summary>
        /// <param name="context">project that is to be published</param>
        /// <param name="baseOutputPath">Location of published files</param>
        /// <param name="configuration">Debug or Release</param>
        /// <param name="nativeSubdirectories"></param>
        /// <returns>Return 0 if successful else return non-zero</returns>
        private bool PublishProjectContext(ProjectContext context, string buildBasePath, string outputPath, string configuration, bool nativeSubdirectories)
        {
            var target = context.TargetFramework.DotNetFrameworkName;

            if (!string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                target = $"{target}/{context.RuntimeIdentifier}";
            }
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {target.Yellow()}");

            var options     = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var outputPaths = context.GetOutputPaths(configuration, buildBasePath, outputPath);

            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(outputPaths.RuntimeOutputPath, PublishSubfolderName);
            }

            var contextVariables = new Dictionary <string, string>
            {
                { "publish:ProjectPath", context.ProjectDirectory },
                { "publish:Configuration", configuration },
                { "publish:OutputPath", outputPath },
                { "publish:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "publish:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "publish:Runtime", context.RuntimeIdentifier },
            };

            RunScripts(context, ScriptNames.PrePublish, contextVariables);

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

            // Compile the project (and transitively, all it's dependencies)
            if (ShouldBuild && !InvokeBuildOnProject(context, buildBasePath, configuration))
            {
                return(false);
            }

            // Use a library exporter to collect publish assets
            var exporter = context.CreateExporter(configuration);

            var isPortable = string.IsNullOrEmpty(context.RuntimeIdentifier);

            // Collect all exports and organize them
            var exports = exporter.GetAllExports()
                          .Where(e => e.Library.Identity.Type.Equals(LibraryType.Package))
                          .ToDictionary(e => e.Library.Identity.Name);
            var collectExclusionList = isPortable ? GetExclusionList(context, exports) : new HashSet <string>();

            foreach (var export in exporter.GetAllExports().Where(e => !collectExclusionList.Contains(e.Library.Identity.Name)))
            {
                Reporter.Verbose.WriteLine($"Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishAssetGroups(export.RuntimeAssemblyGroups, outputPath, nativeSubdirectories: false, includeRuntimeGroups: isPortable);
                PublishAssetGroups(export.NativeLibraryGroups, outputPath, nativeSubdirectories, includeRuntimeGroups: isPortable);
                export.RuntimeAssets.StructuredCopyTo(outputPath, outputPaths.IntermediateOutputDirectoryPath);

                if (options.PreserveCompilationContext.GetValueOrDefault())
                {
                    PublishRefs(export, outputPath);
                }
            }

            if (context.ProjectFile.HasRuntimeOutput(configuration) && !context.TargetFramework.IsDesktop())
            {
                // Get the output paths used by the call to `dotnet build` above (since we didn't pass `--output`, they will be different from
                // our current output paths)
                var buildOutputPaths = context.GetOutputPaths(configuration, buildBasePath);
                PublishFiles(
                    new[] {
                    buildOutputPaths.RuntimeFiles.DepsJson,
                    buildOutputPaths.RuntimeFiles.RuntimeConfigJson
                },
                    outputPath);
            }

            var contentFiles = new ContentFiles(context);

            contentFiles.StructuredCopyTo(outputPath);

            // Publish a host if this is an application
            if (options.EmitEntryPoint.GetValueOrDefault() && !string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                Reporter.Verbose.WriteLine($"Copying native host to output to create fully standalone output.");
                PublishHost(context, outputPath, options);
            }

            RunScripts(context, ScriptNames.PostPublish, contextVariables);

            Reporter.Output.WriteLine($"Published to {outputPath}".Green().Bold());

            return(true);
        }
Example #12
0
        /// <summary>
        /// Publish the project for given 'framework (ex - dnxcore50)' and 'runtimeID (ex - win7-x64)'
        /// </summary>
        /// <param name="context">project that is to be published</param>
        /// <param name="baseOutputPath">Location of published files</param>
        /// <param name="configuration">Debug or Release</param>
        /// <param name="nativeSubdirectories"></param>
        /// <returns>Return 0 if successful else return non-zero</returns>
        private bool PublishProjectContext(ProjectContext context, string buildBasePath, string outputPath, string configuration, bool nativeSubdirectories)
        {
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}/{context.RuntimeIdentifier.Yellow()}");

            var options = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(context.GetOutputPaths(configuration, buildBasePath, outputPath).RuntimeOutputPath, PublishSubfolderName);
            }

            var contextVariables = new Dictionary <string, string>
            {
                { "publish:ProjectPath", context.ProjectDirectory },
                { "publish:Configuration", configuration },
                { "publish:OutputPath", outputPath },
                { "publish:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "publish:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "publish:Runtime", context.RuntimeIdentifier },
            };

            RunScripts(context, ScriptNames.PrePublish, contextVariables);

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

            // Compile the project (and transitively, all it's dependencies)
            var args = new List <string>()
            {
                "--framework",
                $"{context.TargetFramework.DotNetFrameworkName}",
                "--runtime",
                context.RuntimeIdentifier,
                "--configuration",
                configuration,
                context.ProjectFile.ProjectDirectory
            };

            if (!string.IsNullOrEmpty(VersionSuffix))
            {
                args.Add("--version-suffix");
                args.Add(VersionSuffix);
            }

            if (!string.IsNullOrEmpty(buildBasePath))
            {
                args.Add("--build-base-path");
                args.Add(buildBasePath);
            }

            var result = Build.BuildCommand.Run(args.ToArray());

            if (result != 0)
            {
                return(false);
            }

            // Use a library exporter to collect publish assets
            var exporter = context.CreateExporter(configuration);

            foreach (var export in exporter.GetAllExports())
            {
                Reporter.Verbose.WriteLine($"Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishFiles(export.RuntimeAssemblies, outputPath, nativeSubdirectories: false);
                PublishFiles(export.NativeLibraries, outputPath, nativeSubdirectories);
                export.RuntimeAssets.StructuredCopyTo(outputPath);

                if (options.PreserveCompilationContext.GetValueOrDefault())
                {
                    PublishRefs(export, outputPath);
                }
            }

            var contentFiles = new ContentFiles(context);

            contentFiles.StructuredCopyTo(outputPath);

            // Publish a host if this is an application
            if (options.EmitEntryPoint.GetValueOrDefault())
            {
                Reporter.Verbose.WriteLine($"Making {context.ProjectFile.Name.Cyan()} runnable ...");
                PublishHost(context, outputPath);
            }

            RunScripts(context, ScriptNames.PostPublish, contextVariables);

            Reporter.Output.WriteLine($"Published to {outputPath}".Green().Bold());

            return(true);
        }
Example #13
0
 private void CopyContentFiles(string outputPath)
 {
     var contentFiles = new ContentFiles(_context);
     contentFiles.StructuredCopyTo(outputPath);
 }
Example #14
0
 private void CopyContentFiles()
 {
     var contentFiles = new ContentFiles(_context);
     contentFiles.StructuredCopyTo(_runtimeOutputPath);
 }
Example #15
0
 public void SetUp()
 {
     folders         = MockRepository.GenerateMock <IContentFolderService>();
     theContentFiles = new ContentFiles(folders, ContentType.images);
 }
Example #16
0
        /// <summary>
        /// Reads the config file
        /// </summary>
        /// <returns>an empty string if no exception occurrs</returns>
        public string Read()
        {
            try
            {
                ParityFile  = string.Empty;
                QParityFile = string.Empty;
                ContentFiles.Clear();
                SnapShotSources.Clear();
                ExcludePatterns.Clear();
                IncludePatterns.Clear();
                BlockSizeKB = 256;
                AutoSaveGB  = 250;

                foreach (string line in File.ReadLines(ConfigPath))
                {
                    string lineStart = line.TrimStart();
                    if (!string.IsNullOrWhiteSpace(lineStart) &&
                        !lineStart.StartsWith("#")
                        )
                    {
                        // Not a comment, so off we go.
                        int    splitIndex = lineStart.IndexOf(' ');
                        string value      = lineStart.Substring(splitIndex + 1);
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            continue;
                        }
                        switch (lineStart.Substring(0, splitIndex).ToLower())
                        {
                        case "parity":
                            ParityFile = value;
                            break;

                        case "q-parity":
                            QParityFile = value;
                            break;

                        case "content":
                            ContentFiles.Add(value);
                            break;

                        case "disk":
                        {
                            // Step over the disk name
                            int diskSplitIndex = value.IndexOf(' ');
                            SnapShotSources.Add(value.Substring(diskSplitIndex + 1));
                        }
                        break;

                        case "exclude":
                            ExcludePatterns.Add(value);
                            break;

                        case "include":
                            IncludePatterns.Add(value);
                            break;

                        case "block_size":
                            BlockSizeKB = uint.Parse(value);
                            break;

                        case "nohidden":
                            Nohidden = true;
                            break;

                        case "autosave":
                            AutoSaveGB = uint.Parse(value);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Example #17
0
        /// <summary>
        /// Writes the config file
        /// </summary>
        /// <returns>an empty string if no exception occurrs</returns>
        public string Write()
        {
            try
            {
                List <string> fileContents = new List <string>
                {
                    "# Configuration for snapraid via Elucidate",
                    string.Empty,
                    "# Defines the file to use as Parity storage",
                    "# It must NOT be in a data disk",
                    "parity " + (Directory.Exists(ParityFile)? Path.Combine(ParityFile, "SnapRAID.parity"):ParityFile),
                    string.Empty,
                    "# Defines the file to use as Q-Parity storage",
                    "# If specified, it enables a double failures protection like RAID6",
                    "# It must NOT be in a data disk"
                };
                if (string.IsNullOrEmpty(QParityFile))
                {
                    fileContents.Add(@"#q-parity F:\qar\q-parity\SnapRAID.Q.parity");
                }
                else
                {
                    fileContents.Add("q-parity " + (Directory.Exists(QParityFile) ? Path.Combine(QParityFile, "SnapRAID.Q.parity") : QParityFile));
                }
                fileContents.Add(string.Empty);
                fileContents.Add("# Defines the file to use as content list");
                fileContents.Add("# You can use multiple specification to store more copies of the file");
                fileContents.Add("# It's suggested to have at least N+1 copies of the file, where N is the number of parity files.");
                fileContents.Add("# It can be in a data disk");
                fileContents.Add("# It can be in the disks used for parity storage");
                fileContents.AddRange(ContentFiles.Select(contentFile => "content " + (Directory.Exists(contentFile) ? Path.Combine(contentFile, "SnapRAID.content") : contentFile)));
                fileContents.Add(string.Empty);
                fileContents.Add("# Defines the data disks to use");
                fileContents.Add("# The order is relevant for parity, do not change it");
                fileContents.AddRange(SnapShotSources.Select((t, index) => string.Concat("disk d", index, ' ', t)));
                fileContents.Add(string.Empty);

                fileContents.Add("# Excludes hidden files and directories (uncomment to enable).");
                fileContents.Add(Nohidden ? "nohidden" : "# nohidden");
                fileContents.Add(string.Empty);

                fileContents.Add("# Defines files and directories to exclude");
                fileContents.Add("# Remember that all the paths are relative at the mount points");
                fileContents.Add("# Format: \"exclude FILE\"");
                fileContents.Add("# Format: \"exclude DIR\\\"");
                fileContents.Add("# Format: \"exclude \\PATH\\FILE\"");
                fileContents.Add("# Format: \"exclude \\PATH\\DIR\\\"");
                if (ExcludePatterns.Any())
                {
                    fileContents.AddRange(ExcludePatterns.Select(pattern => "exclude " + pattern));
                }
                if (IncludePatterns.Any())
                {
                    fileContents.AddRange(IncludePatterns.Select(pattern => "include " + pattern));
                }
                fileContents.Add(string.Empty);
                fileContents.Add("# Defines the block size in kibi bytes (1024 bytes).");
                fileContents.Add("# Default value is 256 -> 256 kibi bytes -> 262144 bytes");
                fileContents.Add("block_size " + BlockSizeKB);
                fileContents.Add(string.Empty);

                fileContents.Add("# Automatically save the state when synching after the specied amount of GiB processed.");
                fileContents.Add("# This option is useful to avoid to restart from scratch long 'sync'");
                fileContents.Add("# commands interrupted by a machine crash.");
                fileContents.Add("# The SIZE argument is specified in gibi bytes -> 1073741824 bytes");
                fileContents.Add("# Default value is 0, meaning disabled.");
                fileContents.Add("# Format: \"autosave SIZE_IN_GiB\"");
                fileContents.Add("autosave " + AutoSaveGB);
                fileContents.Add(string.Empty);
                File.WriteAllLines(ConfigPath, fileContents);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Example #18
0
        /// <summary>
        /// Reads the config file
        /// </summary>
        /// <returns>an empty string if no exception occurrs</returns>
        public bool Read()
        {
            try
            {
                if (!ConfigFileExists)
                {
                    return(false);
                }

                ParityFile1 = string.Empty;
                ParityFile2 = string.Empty;
                ParityFile3 = string.Empty;
                ParityFile4 = string.Empty;
                ParityFile5 = string.Empty;
                ParityFile6 = string.Empty;
                ContentFiles.Clear();
                SnapShotSources.Clear();
                ExcludePatterns.Clear();
                IncludePatterns.Clear();
                BlockSizeKB = 256;
                AutoSaveGB  = 250;

                foreach (string line in File.ReadLines(ConfigPath))
                {
                    string lineStart = line.Trim();
                    if (string.IsNullOrWhiteSpace(lineStart) || lineStart.StartsWith("#"))
                    {
                        continue;
                    }

                    // Not a comment so process the line

                    // split the line by the first space encountered
                    string[] configItem      = lineStart.Split(new[] { ' ' }, 2);
                    string   configItemName  = configItem[0] ?? string.Empty;
                    string   configItemValue = (configItem.Length > 1) ? configItem[1] : string.Empty;

                    // ignore the line if it is not an a recognized setting
                    if (!_validConfigNames.Contains(configItemName))
                    {
                        continue;
                    }

                    switch (configItemName)
                    {
                    case "parity":
                        ParityFile1 = configItemValue;
                        break;

                    case "q-parity":
                        Log.Instance.Warn("'q-parity' entry in config file should be changed to '2-parity'");
                        ParityFile2 = configItemValue;
                        break;

                    case "2-parity":
                        // handle legacy 'q-parity' entry by giving it priority over any '2-parity' entry; saving config will rename 'q-parity' to '2-parity' and leave the path unchanged
                        if (string.IsNullOrEmpty(ParityFile2))
                        {
                            ParityFile2 = configItemValue;
                        }
                        break;

                    case "3-parity":
                        ParityFile3 = configItemValue;
                        break;

                    case "4-parity":
                        ParityFile4 = configItemValue;
                        break;

                    case "5-parity":
                        ParityFile5 = configItemValue;
                        break;

                    case "6-parity":
                        ParityFile6 = configItemValue;
                        break;

                    case "content":
                        ContentFiles.Add(configItemValue);
                        break;

                    case "disk":
                        // Step over the disk name
                        int diskSplitIndex = configItemValue.IndexOf(' ');
                        SnapShotSources.Add(configItemValue.Substring(diskSplitIndex + 1));
                        break;

                    case "exclude":
                        ExcludePatterns.Add(configItemValue);
                        break;

                    case "include":
                        IncludePatterns.Add(configItemValue);
                        break;

                    case "block_size":
                        BlockSizeKB = uint.Parse(configItemValue);
                        break;

                    case "nohidden":
                        Nohidden = true;
                        break;

                    case "autosave":
                        AutoSaveGB = uint.Parse(configItemValue);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
                return(false);
            }
            return(true);
        }
Example #19
0
        /// <summary>
        /// Writes the config file
        /// </summary>
        /// <returns>an empty string if no exception occurs</returns>
        public string Write(string trgtFileName)
        {
            try
            {
                StringBuilder fileContents = new StringBuilder();

                fileContents.Append(Section1);

                // parity
                fileContents.Append(Section2);
                AddParityToConfig(fileContents, ParityFile1, char.MinValue);

                // #-parity
                fileContents.Append(Section3);

                AddParityToConfig(fileContents, ParityFile2, '2');
                AddParityToConfig(fileContents, ZParityFile, 'z');
                AddParityToConfig(fileContents, ParityFile3, '3');
                AddParityToConfig(fileContents, ParityFile4, '4');
                AddParityToConfig(fileContents, ParityFile5, '5');
                AddParityToConfig(fileContents, ParityFile6, '6');

                // content
                fileContents.Append(Section4);
                ContentFiles.ForEach(item => fileContents.AppendLine($"content {(Directory.Exists(item) ? Path.Combine(item, @"snapraid.content") : item)}"));

                // data sources
                fileContents.Append(Section5);
                foreach (SnapShotSource shotSource in SnapShotSources)
                {
                    fileContents.Append(@"disk ").Append(shotSource.Name).Append(@" ").AppendLine(shotSource.DirSource);
                }

                // exclude hidden files
                fileContents.Append(Section6);
                fileContents.AppendLine(Nohidden ? @"nohidden" : @"#nohidden");

                // exclude files and directories
                fileContents.Append(Section7);
                if (ExcludePatterns.Any())
                {
                    ExcludePatterns.ForEach(item => fileContents.Append(@"exclude ").AppendLine(item));
                }

                // include files and directories
                if (IncludePatterns.Any())
                {
                    IncludePatterns.ForEach(item => fileContents.Append(@"include ").AppendLine(item));
                }

                // blocksize
                fileContents.Append(Section8);
                BlockSizeKB = BlockSizeKB >= Constants.MinBlockSize && BlockSizeKB <= Constants.MaxBlockSize ? BlockSizeKB : Constants.DefaultBlockSize;
                fileContents.Append("block_size ").Append(BlockSizeKB).AppendLine();

                // hashsize
                fileContents.Append(Section9);

                // autosave
                fileContents.Append(Section10);
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                AutoSaveGB = AutoSaveGB >= Constants.MinAutoSave && AutoSaveGB <= Constants.MaxAutoSave ? AutoSaveGB : Constants.DefaultAutoSave;
                fileContents.Append(@"autosave ").Append(AutoSaveGB).AppendLine();

                // pool
                fileContents.Append(Section11);

                // windows share

                // smartctl
                Directory.CreateDirectory(Path.GetDirectoryName(trgtFileName));
                File.WriteAllText(trgtFileName, fileContents.ToString());
            }
            catch (Exception ex)
            {
                Log.Fatal(ex);
                return(ex.Message);
            }
            return(string.Empty);
        }
Example #20
0
 public override string ToString()
 {
     return($"Config@{GetHashCode()} [First data file : {DataFiles.FirstOrDefault()} ; First output file : {OutputFiles.FirstOrDefault()} ; First content file : {ContentFiles.FirstOrDefault()}]");
 }
Example #21
0
        private async void ButtonBar_Click(object sender, RoutedEventArgs e)
        {
            var btn = e.OriginalSource as Button;

            switch (btn.Tag.ToString())
            {
            case "0":
                if (ApiKeys.AppCenter != null)
                {
                    Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Tap ReadMe.Share");
                }
                DataTransferManager.ShowShareUI();
                break;

            case "1":
                if (ApiKeys.AppCenter != null)
                {
                    Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Tap ReadMe.OpenBrowser");
                }
                await Windows.System.Launcher.LaunchUriAsync(new Uri(repo.html_url));

                break;

            case "2":
                if (ApiKeys.AppCenter != null)
                {
                    Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Tap ReadMe.ChangeCategory");
                }
                #region Flyout
                MenuFlyout menu = new MenuFlyout {
                    MenuFlyoutPresenterStyle = DarkFlyoutStyle
                };
                var tempCategoriesId = new List <int>(repo.CategoriesId);
                foreach (var item in ApiHandler.AllCategories)
                {
                    if (item.Id == 0)
                    {
                        continue;
                    }
                    var el = new ToggleMenuFlyoutItem {
                        Text = item.Text, Tag = item.Id.ToString(), IsChecked = tempCategoriesId.Contains(item.Id)
                    };
                    el.Click += El_Click;
                    menu.Items.Add(el);
                }
                async void El_Click(object sen, RoutedEventArgs ee)
                {
                    var tag = (sen as FrameworkElement).Tag;

                    try
                    {
                        if (tag == null)
                        {
                            throw new Exception();
                        }
                        var inx = Convert.ToInt32(tag.ToString());
                        if (tempCategoriesId.Contains(inx))
                        {
                            //toggle off
                            tempCategoriesId.Remove(inx);
                        }
                        else
                        {
                            //toggle on
                            tempCategoriesId.Add(inx);
                        }
                        repo.CategoriesId = tempCategoriesId.ToArray();
                        await ApiHandler.UpdateRepoAsync(App.UserLoginAccountName, repo);

                        MainPage.NotifyElement.Show("✔ Categories Updated", 3000);
                    }
                    catch { MainPage.NotifyElement.Show("Something is not right!!", 2000); }
                }

                menu.ShowAt(btn);
                #endregion
                break;

            case "3":
                if (ApiKeys.Pocket == null)
                {
                    return;
                }
                if (ApiKeys.AppCenter != null)
                {
                    Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Tap ReadMe.Pocket");
                }
                if (!Services.Utils.CheckConnection)
                {
                    MainPage.NotifyElement.Show("✖ Error! No internet", 3000);
                }
                var pocket = new PocketApi();
                if (pocket.CheckLogin())
                {
                    var item = await pocket.Post(repo.html_url, new[] { "github", "github" });

                    if (item == null)
                    {
                        MainPage.NotifyElement.Show("Error! Something with the Pocket", 3000);
                    }
                    else
                    {
                        MainPage.NotifyElement.Show("Saved to Pocket", 3000);
                    }
                }
                else
                {
                    var dialog = new MessageDialog("✔ Login to Pocket then try Again");
                    dialog.Commands.Add(new UICommand("OK", async(IUICommand command) =>
                    {
                        var uri = await pocket.LoginUriAsync();
                        WebAuthenticationResult auth =
                            await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, uri, new Uri(App.PocketProtocol));
                        if (auth.ResponseStatus == WebAuthenticationStatus.Success)
                        {
                            if (await pocket.LoginUser())
                            {
                                MainPage.NotifyElement.Show("✔ Logged in Pocket", 3000);
                            }
                            else
                            {
                                MainPage.NotifyElement.Show("✖ Failed to login", 3000);
                            }
                        }
                    }));
                    dialog.Commands.Add(new UICommand("Cancel"));
                    await dialog.ShowAsync();
                }
                break;

            case "4":
                if (ApiKeys.AppCenter != null)
                {
                    Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Tap ReadMe.Refresh");
                }
                try
                {
                    ContentFiles = await ApiHandler.GetContentListAsync(repo, false);

                    FilesList.ItemsSource = ContentFiles;
                    var readme = ContentFiles.Find(o => o.name.ToLower().Equals("readme.md"));
                    Url = readme.download_url;
                    var res = await ApiHandler.GetReadMeMdAsync(repo.id, Url, false);

                    MarkdownText.Text = res.Item2;
                }
                catch { }
                break;
            }
        }
Example #22
0
        /// <summary>
        /// Reads the config file
        /// </summary>
        /// <returns>an empty string if no exception occurs</returns>
        public bool Read()
        {
            Log.Trace(@"ConfigFileHelper.Read() ...");

            try
            {
                if (!ConfigFileExists)
                {
                    return(false);
                }

                bool isConfigRead = true;

                ParityFile1 = string.Empty;
                ParityFile2 = string.Empty;
                ZParityFile = string.Empty;
                ParityFile3 = string.Empty;
                ParityFile4 = string.Empty;
                ParityFile5 = string.Empty;
                ParityFile6 = string.Empty;

                ConfigErrors.Clear();

                ConfigWarnings.Clear();

                ContentFiles.Clear();

                SnapShotSources.Clear();

                ExcludePatterns.Clear();

                IncludePatterns.Clear();

                BlockSizeKB = Constants.DefaultBlockSize;

                AutoSaveGB = Constants.DefaultAutoSave;

                foreach (string line in File.ReadLines(ConfigPath))
                {
                    string lineStart = line.Trim();

                    if (string.IsNullOrWhiteSpace(lineStart) || lineStart.StartsWith(@"#"))
                    {
                        continue;
                    }

                    // Not a comment so process the line

                    // split the line by the first space encountered
                    string[] configItem = lineStart.Split(new[] { ' ' }, 2);
                    Log.Trace(@"configItem [{0}]", string.Join(" ", configItem));
                    string configItemName = configItem[0] ?? string.Empty;
                    Log.Trace(@"configItemName [{0}]", configItemName);
                    string configItemValue = (configItem.Length > 1) ? configItem[1] : string.Empty;
                    Log.Trace(@"configItemValue [{0}]", configItemValue);

                    // ignore the line if it is not an a recognized setting
                    if (!validConfigNames.Contains(configItemName))
                    {
                        continue;
                    }
                    Log.Trace(@"configItemName found in validConfigNames");

                    switch (configItemName)
                    {
                    case @"parity":
                        ParityFile1 = configItemValue;
                        break;

                    case @"q-parity":
                        Log.Warn(@"'q-parity' entry in config file will be changed to '2-parity' when config is saved");
                        ParityFile2 = configItemValue;
                        break;

                    case @"2-parity":
                        // handle legacy 'q-parity' entry by giving it priority over any '2-parity' entry; saving config will rename 'q-parity' to '2-parity' and leave the path unchanged
                        if (string.IsNullOrEmpty(ParityFile2))
                        {
                            ParityFile2 = configItemValue;
                        }
                        break;

                    case @"z-parity":
                        // #WARNING! Your CPU doesn't have a fast implementation for triple parity.
                        // #WARNING! It's recommended to switch to 'z-parity' instead than '3-parity'.
                        ZParityFile = configItemValue;
                        ParityFile3 = string.Empty;
                        break;

                    case @"3-parity":
                        if (string.IsNullOrWhiteSpace(ZParityFile))
                        {
                            ParityFile3 = configItemValue;
                        }
                        break;

                    case @"4-parity":
                        ParityFile4 = configItemValue;
                        break;

                    case @"5-parity":
                        ParityFile5 = configItemValue;
                        break;

                    case @"6-parity":
                        ParityFile6 = configItemValue;
                        break;

                    case @"content":
                        ContentFiles.Add(configItemValue);
                        break;

                    case @"disk":
                    case @"data":     // Handle older configs
                    {
                        // get the data name, d1,d2,d3 etc
                        string diskName = configItemValue.Split(' ')[0];

                        // get the path
                        int diskSplitIndex = configItemValue.IndexOf(' ');

                        string diskPath = configItemValue.Substring(diskSplitIndex + 1);

                        // special handling of data sources since order preservation is extremely important
                        if (!string.IsNullOrEmpty(diskName) && !string.IsNullOrEmpty(diskPath))
                        {
                            SnapShotSources.Add(new SnapShotSource {
                                    Name = diskName, DirSource = diskPath
                                });
                        }
                    }
                    break;

                    case @"exclude":
                        ExcludePatterns.Add(configItemValue);
                        break;

                    case @"include":
                        IncludePatterns.Add(configItemValue);
                        break;

                    case @"block_size":
                        BlockSizeKB = uint.Parse(configItemValue);
                        if (BlockSizeKB < Constants.MinBlockSize || BlockSizeKB > Constants.MaxBlockSize)
                        {
                            isConfigRead = false;
                        }
                        break;

                    case @"autosave":
                        AutoSaveGB = uint.Parse(configItemValue);
                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        if (AutoSaveGB < Constants.MinAutoSave || AutoSaveGB > Constants.MaxAutoSave)
                        {
                            isConfigRead = false;
                        }
                        break;

                    case @"nohidden":
                        Nohidden = true;
                        break;
                    }
                }

                return(isConfigRead);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(false);
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public VulkanSandcastlePresentationStyle()
        {
            // The base path of the presentation style files relative to the assembly's location.  If your
            // assembly will reside in the same folder as the presentation style content, you can remove this
            // property setting.  If adding multiple presentation styles to the assembly, set this to the name
            // of the subfolder that contains the presentation style content folders.
            BasePath = "VulkanSandcastlePresentation";

            // TODO: Adjust the rest of these properties as needed.

            SupportedFormats = HelpFileFormats.Website;


            SupportsNamespaceGrouping = SupportsCodeSnippetGrouping = true;

            // If relative, these paths are relative to the base path
            ResourceItemsPath = "Content";

            ToolResourceItemsPath = "SHFBContent";


            DocumentModelTransformation = new TransformationFile(
                @"%SHFBROOT%\ProductionTransforms\ApplyVSDocModel.xsl", new Dictionary <string, string> {
                { "IncludeAllMembersTopic", "false" },
                { "project", "{@ProjectNodeIDOptional}" }
            });


            IntermediateTocTransformation = new TransformationFile(
                @"%SHFBROOT%\ProductionTransforms\CreateVSToc.xsl");


            BuildAssemblerConfiguration = @"Configuration\BuildAssembler.config";

            // Note that UNIX based web servers may be case-sensitive with regard to folder and filenames so
            // match the case of the folder and filenames in the literals to their actual casing on the file
            // system.

            ContentFiles.Add(new ContentFiles(SupportedFormats, @"icons\*.*"));

            ContentFiles.Add(new ContentFiles(SupportedFormats, @"scripts\*.*"));

            ContentFiles.Add(new ContentFiles(SupportedFormats, @"styles\*.*"));

            // By default, this will use the standard web file content from the Sandcastle Help File Builder
            ContentFiles.Add(new ContentFiles(HelpFileFormats.Website, null, @"Web\*.*",
                                              string.Empty, new[] { ".aspx", ".html", ".htm", ".php" }));


            TransformComponentArguments.Add(new TransformComponentArgument("logoFile", true, true, null,
                                                                           "An optional logo file to insert into the topic headers.  Specify the filename only, omit " +
                                                                           "the path.  Place the file in your project in an icons\\ folder and set the Build Action to " +
                                                                           "Content.  If blank, no logo will appear in the topic headers.  If building website output " +
                                                                           "and your web server is case-sensitive, be sure to match the case of the folder name in your " +
                                                                           "project with that of the presentation style.  The same applies to the logo filename itself."));


            TransformComponentArguments.Add(new TransformComponentArgument("logoFileSvg", true, true, null,
                                                                           "An optional logo svg file to replace the logo file image.  Specify the filename only, omit " +
                                                                           "the path.  Place the file in your project in an icons\\ folder and set the Build Action to " +
                                                                           "Content.  If blank, only the non-svg logo will appear in the topic headers.  If building website output " +
                                                                           "and your web server is case-sensitive, be sure to match the case of the folder name in your " +
                                                                           "project with that of the presentation style.  The same applies to the logo filename itself."));

            TransformComponentArguments.Add(new TransformComponentArgument("logoHeight", true, true, null,
                                                                           "An optional logo height.  If left blank, the actual logo image height is used."));

            TransformComponentArguments.Add(new TransformComponentArgument("logoWidth", true, true, null,
                                                                           "An optional logo width.  If left blank, the actual logo image width is used."));

            TransformComponentArguments.Add(new TransformComponentArgument("logoAltText", true, true, null,
                                                                           "Optional logo alternate text.  If left blank, no alternate text is added."));

            TransformComponentArguments.Add(new TransformComponentArgument("logoPlacement", true, true,
                                                                           "left", "An optional logo placement.  Specify left, right, or above.  If not specified, the " +
                                                                           "default is left."));

            TransformComponentArguments.Add(new TransformComponentArgument("logoAlignment", true, true,
                                                                           "left", "An optional logo alignment when using the 'above' placement option.  Specify left, " +
                                                                           "right, or center.  If not specified, the default is left."));

            TransformComponentArguments.Add(new TransformComponentArgument("maxVersionParts", false, true,
                                                                           null, "The maximum number of assembly version parts to show in API member topics.  Set to 2, " +
                                                                           "3, or 4 to limit it to 2, 3, or 4 parts or leave it blank for all parts including the " +
                                                                           "assembly file version value if specified."));

            TransformComponentArguments.Add(new TransformComponentArgument("defaultLanguage", true, true,
                                                                           "cs", "The default language to use for syntax sections, code snippets, and a language-specific " +
                                                                           "text.  This should be set to cs, vb, cpp, fs, or the keyword style parameter value of a " +
                                                                           "third-party syntax generator if you want to use a non-standard language as the default."));

            TransformComponentArguments.Add(new TransformComponentArgument("includeEnumValues", false, true,
                                                                           "true", "Set this to 'true' to include the column for the numeric value of each field in " +
                                                                           "enumerated type topics.  Set it to 'false' to omit the numeric values column."));

            TransformComponentArguments.Add(new TransformComponentArgument("baseSourceCodeUrl", false, true,
                                                                           null, "If you set the Source Code Base Path property in the Paths category, specify the URL to " +
                                                                           "the base source code folder on your project's website here.  Some examples for GitHub are " +
                                                                           "shown below.\r\n\r\n" +
                                                                           "Important: Be sure to set the Source Code Base Path property and terminate the URL below with " +
                                                                           "a slash if necessary.\r\n\r\n" +
                                                                           "Format: https://github.com/YourUserID/YourProject/blob/BranchNameOrCommitHash/BaseSourcePath/ \r\n\r\n" +
                                                                           "Master branch: https://github.com/JohnDoe/WidgestProject/blob/master/src/ \r\n" +
                                                                           "A different branch: https://github.com/JohnDoe/WidgestProject/blob/dev-branch/src/ \r\n" +
                                                                           "A specific commit: https://github.com/JohnDoe/WidgestProject/blob/c6e41c4fc2a4a335352d2ae8e7e85a1859751662/src/"));

            TransformComponentArguments.Add(new TransformComponentArgument("requestExampleUrl", false, true,
                                                                           null, "To include a link that allows users to request an example for an API topic, set the URL " +
                                                                           "to which the request will be sent.  This can be a web page URL or an e-mail URL.  Only include " +
                                                                           "the URL as the parameters will be added automatically by the topic.  For example:\r\n\r\n" +
                                                                           "Create a new issue on GitHub: https://github.com/YourUserID/YourProject/issues/new \r\n" +
                                                                           "Send via e-mail: mailto:[email protected]"));

            // Add plug-in dependencies
            PlugInDependencies.Add(new PlugInDependency("Lightweight Website Style", null));
        }
Example #24
0
        /// <summary>
        /// Publish the project for given 'framework (ex - netcoreapp1.0)' and 'runtimeID (ex - win7-x64)'
        /// </summary>
        /// <param name="context">project that is to be published</param>
        /// <param name="baseOutputPath">Location of published files</param>
        /// <param name="configuration">Debug or Release</param>
        /// <param name="nativeSubdirectories"></param>
        /// <returns>Return 0 if successful else return non-zero</returns>
        private bool PublishProjectContext(ProjectContext context, string buildBasePath, string outputPath, string configuration, bool nativeSubdirectories)
        {
            var target = context.TargetFramework.DotNetFrameworkName;

            if (!string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                target = $"{target}/{context.RuntimeIdentifier}";
            }
            Reporter.Output.WriteLine($"Publishing {context.RootProject.Identity.Name.Yellow()} for {target.Yellow()}");

            var options     = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var outputPaths = context.GetOutputPaths(configuration, buildBasePath, outputPath);

            if (string.IsNullOrEmpty(outputPath))
            {
                outputPath = Path.Combine(outputPaths.RuntimeOutputPath, PublishSubfolderName);
            }

            var contextVariables = new Dictionary <string, string>
            {
                { "publish:ProjectPath", context.ProjectDirectory },
                { "publish:Configuration", configuration },
                { "publish:OutputPath", outputPath },
                { "publish:TargetFramework", context.TargetFramework.GetShortFolderName() },
                { "publish:FullTargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "publish:Runtime", context.RuntimeIdentifier },
            };

            RunScripts(context, ScriptNames.PrePublish, contextVariables);

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

            // Compile the project (and transitively, all it's dependencies)
            if (ShouldBuild && !InvokeBuildOnProject(context, buildBasePath, configuration))
            {
                return(false);
            }

            // Use a library exporter to collect publish assets
            var exporter = context.CreateExporter(configuration, buildBasePath);

            // Get the output paths used by the call to `dotnet build` above (since we didn't pass `--output`, they will be different from
            // our current output paths)
            var buildOutputPaths = context.GetOutputPaths(configuration, buildBasePath);

            var exports = exporter.GetAllExports();

            var exportsLookup         = exports.ToDictionary(e => e.Library.Identity.Name, StringComparer.OrdinalIgnoreCase);
            var platformExclusionList = context.GetPlatformExclusionList(exportsLookup);
            var buildExclusionList    = context.GetTypeBuildExclusionList(exportsLookup);
            var allExclusionList      = new HashSet <string>(platformExclusionList);

            allExclusionList.UnionWith(buildExclusionList);
            var filteredExports = exports.FilterExports(allExclusionList);

            foreach (var export in filteredExports)
            {
                Reporter.Verbose.WriteLine($"publish: Publishing {export.Library.Identity.ToString().Green().Bold()} ...");

                PublishAssetGroups(export.RuntimeAssemblyGroups, outputPath, nativeSubdirectories: false, includeRuntimeGroups: context.IsPortable);
                PublishAssetGroups(export.NativeLibraryGroups, outputPath, nativeSubdirectories, includeRuntimeGroups: context.IsPortable);

                var runtimeAssetsToCopy = export.RuntimeAssets.Where(a => ShouldCopyExportRuntimeAsset(context, buildOutputPaths, export, a));
                runtimeAssetsToCopy.StructuredCopyTo(outputPath, outputPaths.IntermediateOutputDirectoryPath);

                foreach (var resourceAsset in export.ResourceAssemblies)
                {
                    var dir = Path.Combine(outputPath, resourceAsset.Locale);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.Copy(resourceAsset.Asset.ResolvedPath, Path.Combine(dir, resourceAsset.Asset.FileName), overwrite: true);
                }
            }
            foreach (var export in exports)
            {
                if (options.PreserveCompilationContext.GetValueOrDefault())
                {
                    PublishRefs(export, outputPath);
                }
            }

            if (context.ProjectFile.HasRuntimeOutput(configuration) && !context.TargetFramework.IsDesktop())
            {
                // Make executable in the new location
                var executable         = new Executable(context, buildOutputPaths, outputPath, buildOutputPaths.IntermediateOutputDirectoryPath, exporter, configuration);
                var runtimeExports     = filteredExports;
                var compilationExports = exports.FilterExports(buildExclusionList);

                executable.WriteConfigurationFiles(exports, runtimeExports, compilationExports, includeDevConfig: false);
            }

            var contentFiles = new ContentFiles(context);

            if (context.ProjectFile.PublishOptions != null)
            {
                var includeEntries = IncludeFilesResolver.GetIncludeFiles(
                    context.ProjectFile.PublishOptions,
                    PathUtility.EnsureTrailingSlash(outputPath),
                    diagnostics: null);

                contentFiles.StructuredCopyTo(outputPath, includeEntries);
            }
            else
            {
                contentFiles.StructuredCopyTo(outputPath);
            }

            // Publish a host if this is an application
            if (options.EmitEntryPoint.GetValueOrDefault() && !string.IsNullOrEmpty(context.RuntimeIdentifier))
            {
                Reporter.Verbose.WriteLine($"publish: Renaming native host in output to create fully standalone output.");
                RenamePublishedHost(context, outputPath, options);
            }

            RunScripts(context, ScriptNames.PostPublish, contextVariables);

            Reporter.Output.WriteLine($"publish: Published to {outputPath}".Green().Bold());

            return(true);
        }
Example #25
0
        /// <summary>
        /// Writes the config file
        /// </summary>
        /// <returns>an empty string if no exception occurs</returns>
        public string Write()
        {
            try
            {
                StringBuilder fileContents = new StringBuilder();

                fileContents.Append(Section1);

                // parity
                fileContents.Append(Section2);
                fileContents.AppendLine($"parity {(Directory.Exists(ParityFile1) ? Path.Combine(ParityFile1, "SnapRAID.parity") : ParityFile1)}");

                // X-parity
                fileContents.Append(Section3);
                if (!string.IsNullOrEmpty(ParityFile2))
                {
                    fileContents.AppendLine($"2-parity {(Directory.Exists(ParityFile2) ? Path.Combine(ParityFile2, "SnapRAID.2-parity") : ParityFile2)}");
                }
                if (!string.IsNullOrEmpty(ParityFile3))
                {
                    fileContents.AppendLine($"3-parity {(Directory.Exists(ParityFile3) ? Path.Combine(ParityFile3, "SnapRAID.3-parity") : ParityFile3)}");
                }
                if (!string.IsNullOrEmpty(ParityFile4))
                {
                    fileContents.AppendLine($"4-parity {(Directory.Exists(ParityFile4) ? Path.Combine(ParityFile4, "SnapRAID.4-parity") : ParityFile4)}");
                }
                if (!string.IsNullOrEmpty(ParityFile5))
                {
                    fileContents.AppendLine($"5-parity {(Directory.Exists(ParityFile5) ? Path.Combine(ParityFile5, "SnapRAID.5-parity") : ParityFile5)}");
                }
                if (!string.IsNullOrEmpty(ParityFile6))
                {
                    fileContents.AppendLine($"6-parity {(Directory.Exists(ParityFile6) ? Path.Combine(ParityFile6, "SnapRAID.6-parity") : ParityFile6)}");
                }

                // content
                fileContents.Append(Section4);
                ContentFiles.ForEach(item => fileContents.AppendLine($"content {(Directory.Exists(item) ? Path.Combine(item, "SnapRAID.content") : item)}"));

                // data sources
                fileContents.Append(Section5);
                List <string> strSnapShotSources = new List <string>();
                strSnapShotSources.AddRange(SnapShotSources.Select((t, index) => string.Concat("disk d", index + 1, ' ', t)));
                strSnapShotSources.ForEach(item => fileContents.AppendLine(item));

                // exclude hidden files
                fileContents.Append(Section6);
                fileContents.AppendLine(Nohidden ? "nohidden" : "#nohidden");

                // exclude files and directories
                fileContents.Append(Section7);
                if (ExcludePatterns.Any())
                {
                    ExcludePatterns.ForEach(item => fileContents.AppendLine("exclude " + item));
                }

                // include files and directories
                if (IncludePatterns.Any())
                {
                    IncludePatterns.ForEach(item => fileContents.AppendLine("include " + item));
                }

                // blocksize
                fileContents.Append(Section8);
                fileContents.AppendLine("block_size " + BlockSizeKB);

                // hashsize
                fileContents.Append(Section9);

                // autosave
                fileContents.Append(Section10);
                fileContents.AppendLine("autosave " + AutoSaveGB);

                // pool
                fileContents.Append(Section11);

                // windows share

                // smartctl

                File.WriteAllText(ConfigPath, fileContents.ToString());
            }
            catch (Exception ex)
            {
                ExceptionHandler.ReportException(ex);
                return(ex.Message);
            }
            return(string.Empty);
        }