public void UpdatePackageReferenceFromTransitiveDependency(RequiredNugetUpdate update, string solutionFolder)
        {
            ColorConsole.WriteEmbeddedColorLine($"Update {update.Library.Name}\t\t from [red]{update.Library.Version}[/red]" +
                                                $" to [green]{update.TargetVersion}[/green] [yellow](Transitive)[/yellow] in\t\t{Path.GetFileName(update.ProjectPath)}");

            var projectName   = Path.GetFileName(update.ProjectPath);
            var projectFolder = Path.GetDirectoryName(update.ProjectPath);

            if (projectFolder == null)
            {
                ColorConsole.WriteWarning("Nothing patched - project was null");
                return;
            }
            var packageReferenceFile = Path.Combine(projectFolder, PROJECT_FILE_PROPS_FILE_NAME);
            var document             = CreateOrOpenBuildPropsFile(packageReferenceFile);
            var itemGroup            = document.Root?.Descendants("ItemGroup").FirstOrDefault();

            if (itemGroup != null)
            {
                itemGroup.Add(new XComment($"Required to update transitive reference of {update.RootReferenceName}\r\n" +
                                           $"\t\t\tin {projectName} from {update.Library.Version}\r\n" +
                                           $"\t\t\tbecause {update.TargetVersion} is used in {update.UpateCausedBy}\r\n" +
                                           "\t\t"),
                              new XElement("PackageReference", new XAttribute("Include", update.Library.Name), new XAttribute("Version", update.TargetVersion.ToString())));
                using XmlWriter w = XmlWriter.Create(packageReferenceFile, new XmlWriterSettings()
                {
                    OmitXmlDeclaration = true, Indent = true
                });
                document.Save(w);
            }
            else
            {
                ColorConsole.WriteError($"File {packageReferenceFile} not patched - invalid. Run this tool again with clean flag");
            }
        }
        public void UpdateDirectPackageReference(RequiredNugetUpdate update)
        {
            ColorConsole.WriteEmbeddedColorLine($"Update {update.Library.Name}\t\t from [red]{update.Library.Version}[/red] to" +
                                                $" [green]{update.TargetVersion}[/green] [green](Direct)[/green] in\t\t{Path.GetFileName(update.ProjectPath)}");
            var doc     = XDocument.Load(update.ProjectPath);
            var element = doc.Root?
                          .Descendants("PackageReference")
                          .SingleOrDefault(e => e.Attribute("Include")?.Value.Equals(update.Library.Name, StringComparison.OrdinalIgnoreCase) == true);

            if (element != null)
            {
                var versionAttribute = element.Attribute("Version");
                if (versionAttribute != null)
                {
                    if (versionAttribute.Value != update.Library.Version.ToString())
                    {
                        ColorConsole.WriteWarning(
                            $"Expected version {update.Library.Version} but {versionAttribute.Value} found");
                    }
                }

                element.SetAttributeValue("Version", update.TargetVersion);
                doc.Save(update.ProjectPath);
            }
            else
            {
                ColorConsole.WriteError("No package reference node found");
            }
        }
        /// <summary> Executes a provided REST client and a success action, if the REST client succeeds.
        /// </summary>
        /// <remarks> Pretty-prints error messages for common HTTP status codes. </remarks>
        /// <param name="dalSoftRestClientFunc">REST client function</param>
        /// <param name="successAction">Success action that gets the reponse from the REST client</param>
        /// <returns>Exit code</returns>
        public static int Execute(Func <dynamic> dalSoftRestClientFunc, Func <dynamic, int> successAction)
        {
            if (dalSoftRestClientFunc == null)
            {
                throw new ArgumentNullException(nameof(dalSoftRestClientFunc));
            }
            if (successAction == null)
            {
                throw new ArgumentNullException(nameof(successAction));
            }

            try {
                dynamic theResponse = dalSoftRestClientFunc();

                if (theResponse.HttpResponseMessage.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Console.WriteLine();

                    ColorConsole.WriteError(" ERROR ");
                    Console.WriteLine(" Invalid or expired token.");

                    return(1);
                }
                if (theResponse.HttpResponseMessage.StatusCode == HttpStatusCode.Forbidden)
                {
                    Console.WriteLine();

                    ColorConsole.WriteError(" ERROR ");
                    Console.WriteLine(" You are not authorized to execute this command.");

                    return(1);
                }
                else if (!theResponse.HttpResponseMessage.IsSuccessStatusCode)
                {
                    Console.WriteLine();

                    ColorConsole.WriteError(" ERROR ");
                    Console.WriteLine($" {theResponse.ToString()}");

                    return(1);
                }

                Console.WriteLine();

                return(successAction(theResponse));
            } catch (Exception theException) {
                Console.WriteLine();

                ColorConsole.WriteError(" ERROR ");
                Console.WriteLine($" {theException.Message}");

                return(1);
            }
        }
        private void RestoreSolution()
        {
            var runner = new ProcessRunner();

            ColorConsole.WriteInfo($"Restore {m_options.SolutionFile}");
            var result = runner.Run("dotnet", null, new[] { "restore", m_options.SolutionFile });

            if (!result.IsSuccess)
            {
                ColorConsole.WriteError($"restoring failed {result.Errors} ");
            }
        }
Beispiel #5
0
        static async Task Main(string[] args)
        {
            var waitSequence = new List <TimeSpan>()
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(3),
                TimeSpan.FromSeconds(5)
            };

            var retryPolicy = Policy
                              .Handle <NotImplementedException>()
                              .WaitAndRetryAsync(waitSequence);

            var breakerPolicy = Policy
                                .Handle <NotImplementedException>()
                                .CircuitBreakerAsync(
                exceptionsAllowedBeforeBreaking: 4,
                durationOfBreak: TimeSpan.FromSeconds(5),
                onBreak: (err, ctx) => ColorConsole.WriteError($"Breaking !"),
                onReset: () => ColorConsole.WriteError($"Resetting !"));

            var wrapPolicy = Policy.WrapAsync(retryPolicy, breakerPolicy);

            try
            {
                //await wrapPolicy.ExecuteAsync(() => DoSomething("retry + circuit breaker policy"));

                //await retryPolicy.ExecuteAsync(() => DoSomething("retry policy"));

                // why passing context doesn't work ?
                //await breakerPolicy.ExecuteAsync(a => DoSomething(a.PolicyKey));

                // why circuit breaker doesn't work?
                await breakerPolicy.ExecuteAsync(() => DoSomething("circuit breaker policy"));
            }
            catch (Exception)
            {
                ColorConsole.WriteError($"Failed !");
                //throw;
            }
        }
        public void IncludeGeneratedPackageReferenceInBuildTargets(string solutionFile)
        {
            var solutionFolder   = Path.GetDirectoryName(solutionFile);
            var buildTargetsFile = Path.Combine(solutionFolder, "Directory.Build.targets");
            var doc = CreateOrOpenBuildTargetsFile(buildTargetsFile);

            if (doc.Root != null)
            {
                // check import already exits
                if (doc.Root.Elements("Import").All(x => x.Attribute("Project")?.Value.Contains(PROJECT_FILE_PROPS_FILE_NAME, StringComparison.OrdinalIgnoreCase) != true))
                {
                    doc.Root.Add(new XElement("Import",
                                              new XAttribute("Project", $"$(ProjectDir){PROJECT_FILE_PROPS_FILE_NAME}"),
                                              new XAttribute("Condition", $"Exists('$(ProjectDir){PROJECT_FILE_PROPS_FILE_NAME}')")));
                    doc.Save(buildTargetsFile);
                }
            }
            else
            {
                ColorConsole.WriteError($"The file {buildTargetsFile} not patched - invalid");
            }
        }
Beispiel #7
0
        /// <summary>
        /// mm markdowntopdf [inputfile] [outputFile] -open
        /// </summary>
        public void MarkdownToPdf()
        {
            Processor.ConsoleHeader();

            string inputFile  = Arguments.InputFile;
            string outputFile = Arguments.OutputFile;

            if (string.IsNullOrEmpty(inputFile) || !File.Exists(inputFile))
            {
                var fd = new System.Windows.Forms.OpenFileDialog
                {
                    DefaultExt = ".md",
                    Filter     = "HTML files (*.md, *.markdown, *.mdcrypt)|*.md;*.markdown,*.mdcrypt|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = true,
                    RestoreDirectory = true,
                    Title            = "Open Markdown File",
                    InitialDirectory = Environment.CurrentDirectory
                };
                var res = fd.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.Cancel || res == System.Windows.Forms.DialogResult.Abort)
                {
                    return;
                }
                inputFile = fd.FileName;
            }

            if (string.IsNullOrEmpty(outputFile) || !File.Exists(outputFile))
            {
                var fd = new System.Windows.Forms.SaveFileDialog
                {
                    DefaultExt = ".pdf",
                    Filter     = "Pdf files (*.pdf)|*.pdf|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = false,
                    RestoreDirectory = true,
                    Title            = "Save as Pdf File",
                    InitialDirectory = Path.GetDirectoryName(inputFile),
                    FileName         = Path.ChangeExtension(Path.GetFileName(inputFile), "pdf")
                };
                var res = fd.ShowDialog();
                if (res == DialogResult.Cancel || res == DialogResult.Abort)
                {
                    return;
                }
                outputFile = fd.FileName;
            }

            var doc = new MarkdownDocument();

            if (!string.IsNullOrEmpty(Arguments.Theme))
            {
                mmApp.Configuration.PreviewTheme = Arguments.Theme;
            }

            try
            {
                if (!doc.Load(inputFile))
                {
                    throw new AccessViolationException();
                }
            }
            catch
            {
                ColorConsole.WriteError("Failed: Couldn't read input file.");
                Processor.ConsoleFooter();
                return;
            }

            string htmlFilename = System.IO.Path.ChangeExtension(doc.Filename, "html");
            var    pdfGenerator = new HtmlToPdfGeneration();

            pdfGenerator.PageSize    = Arguments.PageSize;
            pdfGenerator.Orientation = Arguments.Orientation;
            pdfGenerator.DisplayPdfAfterGeneration = Arguments.OpenOutputFile;

            try
            {
                // render the document with template and return only as string (no output yet)
                doc.RenderHtmlToFile(filename: htmlFilename, removeBaseTag: true);

                if (!pdfGenerator.GeneratePdfFromHtml(htmlFilename, outputFile))
                {
                    throw new InvalidOperationException(pdfGenerator.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                ColorConsole.WriteError("Failed: PDF output generation failed: " + ex.Message);
                Processor.ConsoleFooter();
                return;
            }
            finally
            {
                File.Delete(htmlFilename);
            }

            ColorConsole.WriteSuccess("PDF file generated: " + outputFile);
            Processor.ConsoleFooter();
        }
        /// <summary>
        ///
        /// mm htmltomarkdown [inputfile] [outputFile] -open
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <param name="openOutputFile"></param>
        public void HtmlToMarkdown()
        {
            Processor.ConsoleHeader();
            string inputFile  = Arguments.InputFile;
            string outputFile = Arguments.OutputFile;

            if (string.IsNullOrEmpty(inputFile) || !File.Exists(inputFile))
            {
                var fd = new OpenFileDialog
                {
                    DefaultExt = ".html",
                    Filter     = "HTML files (*.html, *.htm)|*.html;*.htm|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = true,
                    RestoreDirectory = true,
                    Title            = "Open HTML File",
                    InitialDirectory = Environment.CurrentDirectory
                };
                var res = fd.ShowDialog();
                if (res == null)
                {
                    return;
                }
                inputFile = fd.FileName;
            }

            if (string.IsNullOrEmpty(outputFile))
            {
                var fd = new SaveFileDialog
                {
                    DefaultExt = ".md",
                    Filter     = "Markdown files (*.md,*.markdown,*.mdcrypt)|*.md;*.markdown;*.mdcrypt|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = false,
                    RestoreDirectory = true,
                    Title            = "Save as Markdown File",
                    InitialDirectory = Path.GetDirectoryName(inputFile),
                    FileName         = Path.ChangeExtension(Path.GetFileName(inputFile), "md")
                };
                var res = fd.ShowDialog();
                if (res == null)
                {
                    return;
                }
                outputFile = fd.FileName;
            }


            string md;

            try
            {
                var html = File.ReadAllText(inputFile);
                md = MarkdownUtilities.HtmlToMarkdown(html, true);
            }
            catch
            {
                ColorConsole.WriteError("Failed: Couldn't read input file.");
                Processor.ConsoleFooter();
                return;
            }


            if (!string.IsNullOrEmpty(outputFile))
            {
                try
                {
                    File.WriteAllText(outputFile, md);
                }
                catch
                {
                    ColorConsole.WriteError("Failed: Couldn't write output file.");
                    Processor.ConsoleFooter();
                    return;
                }

                if (Arguments.OpenOutputFile)
                {
                    ShellUtils.ExecuteProcess("markdownmonster.exe", $"'{outputFile}'");
                }


                ColorConsole.WriteSuccess($"Created Markdown file: {outputFile}");

                Processor.ConsoleFooter();
            }
        }
        /// <summary>
        ///
        /// mm markdowntohtml <inputfile> <outputFile> <rendermode> -open
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <param name="openOutputFile"></param>
        /// <param name="fileMode">html,packagedhtml,zip</param>
        public void MarkdownToHtml()
        {
            Processor.ConsoleHeader();

            string inputFile  = Arguments.InputFile;
            string outputFile = Arguments.OutputFile;

            if (string.IsNullOrEmpty(inputFile) || !File.Exists(inputFile))
            {
                var fd = new OpenFileDialog
                {
                    DefaultExt = ".md",
                    Filter     = "Markdown files (*.md,*.markdown)|*.md;*.markdown|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = true,
                    RestoreDirectory = true,
                    Title            = "Open Markdown File",
                    InitialDirectory = Environment.CurrentDirectory
                };
                var res = fd.ShowDialog();
                if (res == null)
                {
                    return;
                }
                inputFile = fd.FileName;
            }

            if (string.IsNullOrEmpty(outputFile))
            {
                var fd = new SaveFileDialog
                {
                    DefaultExt = ".html",
                    Filter     = "HTML files (*.html,*.htm)|*.html;*.htm|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = false,
                    RestoreDirectory = true,
                    Title            = "Save as HTML File",
                    InitialDirectory = Path.GetDirectoryName(inputFile),
                    FileName         = Path.ChangeExtension(Path.GetFileName(inputFile), "html")
                };
                var res = fd.ShowDialog();
                if (res == null)
                {
                    return;
                }
                outputFile = fd.FileName;
            }

            string html;
            var    doc = new MarkdownDocument();

            if (!string.IsNullOrEmpty(Arguments.Theme))
            {
                mmApp.Configuration.PreviewTheme = Arguments.Theme;
            }

            try
            {
                if (!doc.Load(inputFile))
                {
                    throw new AccessViolationException();
                }
            }
            catch
            {
                ColorConsole.WriteError("Failed: Couldn't read input file.");
                Processor.ConsoleFooter();
                return;
            }

            try
            {
                string renderMode = Arguments.HtmlRenderMode?.ToLower();

                if (renderMode == "fragment" || renderMode == "raw")
                {
                    try
                    {
                        var parser = new MarkdownParserMarkdig();
                        html = parser.Parse(doc.CurrentText);

                        File.WriteAllText(outputFile, html, new UTF8Encoding(false));
                    }
                    catch
                    {
                        ColorConsole.WriteError("Failed: Couldn't convert Markdown document or generate output file.");
                        Processor.ConsoleFooter();
                        return;
                    }
                }
                else
                {
                    if (doc.RenderHtmlToFile(filename: outputFile) == null)
                    {
                        throw new AccessViolationException();
                    }
                }

                if (renderMode == "packagedhtml")
                {
                    var    packager   = new Westwind.HtmlPackager.HtmlPackager();
                    string outputHtml = packager.PackageHtml(outputFile);
                    try
                    {
                        File.WriteAllText(outputFile, outputHtml);
                    }
                    catch
                    {
                        ColorConsole.WriteError("Failed: Couldn't write output file.");
                        Processor.ConsoleFooter();
                        return;
                    }
                }
                else if (renderMode == "htmlfiles")
                {
                    var packager = new Westwind.HtmlPackager.HtmlPackager();
                    if (!packager.PackageHtmlToFolder(outputFile, outputFile))
                    {
                        ColorConsole.WriteLine("Failed: Create output folder.", ConsoleColor.Red);
                    }
                }
                else if (renderMode == "zip")
                {
                    var packager = new Westwind.HtmlPackager.HtmlPackager();
                    if (!packager.PackageHtmlToZipFile(Path.ChangeExtension(outputFile, "html"), Path.ChangeExtension(outputFile, "zip")))
                    {
                        ColorConsole.WriteError("Failed: Couldn't create Packaged HTML Zip files.");
                    }

                    try
                    {
                        File.Delete(Path.ChangeExtension(outputFile, "html"));
                    }catch {}
                }
            }

            catch
            {
                ColorConsole.WriteError("Failed: Couldn't write output file.");
                Processor.ConsoleFooter();
                return;
            }

            if (Arguments.OpenOutputFile)
            {
                ShellUtils.GoUrl($"{outputFile}");
            }

            ColorConsole.WriteSuccess($"Created file: {outputFile}");
            ColorConsole.WriteSuccess($" Output Mode: {Arguments.HtmlRenderMode}");

            Processor.ConsoleFooter();
        }