Beispiel #1
0
 public int Run(Cli console,string[] args)
 {
     console.Out.Write(_waitText);
     console.In.Read();
     console.Out.WriteLine();
     return 0;
 }
Beispiel #2
0
 public static void Main(string[] args)
 {
     Cli.Configure(ConfigureNFlags)
     .Root(RootCommand.Configure)
     .Run(args);
 }
Beispiel #3
0
    /// <summary>Build project for this repository.</summary>
    /// <param name="arguments">A list of targets to run or list.</param>
    /// <param name="clear">Clear the console before execution.</param>
    /// <param name="dryRun">Do a dry run without executing actions.</param>
    /// <param name="host">Force the mode for a specific host environment (normally auto-detected).</param>
    /// <param name="listDependencies">List all (or specified) targets and dependencies, then exit.</param>
    /// <param name="listInputs">List all (or specified) targets and inputs, then exit.</param>
    /// <param name="listTargets">List all (or specified) targets, then exit.</param>
    /// <param name="listTree">List all (or specified) targets and dependency trees, then exit.</param>
    /// <param name="noColor">Disable colored output.</param>
    /// <param name="parallel">Run targets in parallel.</param>
    /// <param name="skipDependencies">Do not run targets' dependencies.</param>
    /// <param name="verbose">Enable verbose output.</param>
    /// <param name="cancellationToken"></param>
    /// <param name="configuration">The configuration for building</param>
    /// <param name="framework">The framework to build for</param>
    private static async Task Main(
        string[] arguments,
        bool clear,
        bool dryRun,
        Host host,
        bool listDependencies,
        bool listInputs,
        bool listTargets,
        bool listTree,
        bool noColor,
        bool parallel,
        bool skipDependencies,
        bool verbose,
        CancellationToken cancellationToken,
        // Our own options
        string configuration = "",
        string framework     = "")
    {
        var publicBuildEnvVar = Environment.GetEnvironmentVariable("PUBLIC_BUILD")?.Trim() ?? "";
        var isPublicRelease   = false;

        if (bool.TryParse(publicBuildEnvVar, out var v))
        {
            isPublicRelease = v;
        }
        if (int.TryParse(publicBuildEnvVar, out var vi))
        {
            isPublicRelease = vi != 0;
        }

        SetDefaults("Stl.Fusion.sln", isPublicRelease);
        var options = new Options {
            Clear            = clear,
            DryRun           = dryRun,
            Host             = host,
            ListDependencies = listDependencies,
            ListInputs       = listInputs,
            ListTargets      = listTargets,
            ListTree         = listTree,
            NoColor          = noColor,
            Parallel         = parallel,
            SkipDependencies = skipDependencies,
            Verbose          = verbose,
        };

        var artifactsPath  = FilePath.New("artifacts").FullPath;
        var nupkgPath      = artifactsPath & "nupkg";
        var testOutputPath = artifactsPath & "tests" & "output";
        var dotnetExePath  = TryFindDotNetExePath() ?? throw new FileNotFoundException(
                                       "'dotnet' command isn't found. Use DOTNET_ROOT env. var to specify the path to custom 'dotnet' tool.");

        // For Nerdbank.GitVersioning: https://github.com/dotnet/Nerdbank.GitVersioning/blob/master/doc/public_vs_stable.md
        var publicReleaseProperty = $"-p:PublicRelease={isPublicRelease} ";

        Target("clean", () => {
            DeleteDir(artifactsPath);
            CreateDir(nupkgPath, true);
        });

        Target("clean-nupkg", () => {
            DeleteDir(nupkgPath);
            CreateDir(nupkgPath, true);
        });

        Target("restore-tools", async() => {
            await Cli.Wrap(dotnetExePath).WithArguments(new[] { "tool", "restore", "--ignore-failed-sources" })
            .ToConsole()
            .ExecuteAsync(cancellationToken).ConfigureAwait(false);
        });

        Target("restore", async() => {
            await Cli.Wrap(dotnetExePath).WithArguments(new[] {
                "msbuild",
                "-noLogo",
                "-t:Restore",
                "-p:RestoreForce=true",
                "-p:RestoreIgnoreFailedSources=True",
                publicReleaseProperty
            }).ToConsole()
            .ExecuteAsync(cancellationToken).ConfigureAwait(false);
        });

        Target("build", async() => {
            await Cli.Wrap(dotnetExePath).WithArguments(args => args
                                                        .Add("build")
                                                        .Add("-noLogo")
                                                        .AddOption("-c", configuration)
                                                        .AddOption("-f", framework)
                                                        .Add("--no-restore")
                                                        .Add(publicReleaseProperty)
                                                        )
            .ToConsole()
            .ExecuteAsync(cancellationToken).ConfigureAwait(false);
        });

        // Technically it should depend on "build" target, but such a setup fails
        // due to https://github.com/dotnet/orleans/issues/6073 ,
        // that's why we make "pack" to run "build" too here
        Target("pack", DependsOn("clean", "restore"), async() => {
            await Cli.Wrap(dotnetExePath).WithArguments(args => args
                                                        .Add("pack")
                                                        .Add("-noLogo")
                                                        .AddOption("-c", configuration)
                                                        .AddOption("-f", framework)
                                                        .Add("--no-restore")
                                                        .Add(publicReleaseProperty)
                                                        )
            .ToConsole()
            .ExecuteAsync(cancellationToken).ConfigureAwait(false);
        });

        Target("publish", DependsOn("clean-nupkg", "pack"), async() => {
            const string feed  = "https://api.nuget.org/v3/index.json";
            var nugetOrgApiKey = Environment.GetEnvironmentVariable("NUGET_ORG_API_KEY") ?? "";
            if (string.IsNullOrWhiteSpace(nugetOrgApiKey))
            {
                throw new InvalidOperationException("NUGET_ORG_API_KEY env. var isn't set.");
            }
            var nupkgPaths = Directory
                             .EnumerateFiles(nupkgPath.FullPath, "*.nupkg", SearchOption.TopDirectoryOnly)
                             .Select(FilePath.New)
                             .ToArray();
            foreach (var nupkgPath in nupkgPaths)
            {
                await Cli.Wrap(dotnetExePath).WithArguments(new string[] {
                    "nuget",
                    "push",
                    nupkgPath,
                    "--force-english-output",
                    "--timeout", "60",
                    "--api-key", nugetOrgApiKey,
                    "--source", feed,
                    "--skip-duplicate"
                })
                .ToConsole()
                .ExecuteAsync(cancellationToken)
                .ConfigureAwait(false);
            }
        });

        Target("coverage", DependsOn("build"), async() => {
            CreateDir(testOutputPath);
            var cmd = await Cli.Wrap(dotnetExePath)
                      .WithArguments(args => args
                                     .Add("test")
                                     .Add("--nologo")
                                     .Add("--no-restore")
                                     .Add("--blame")
                                     .Add("--collect:\"XPlat Code Coverage\"")
                                     .Add("--results-directory").Add(testOutputPath)
                                     .AddOption("-c", configuration)
                                     .AddOption("-f", framework)
                                     .Add("--")
                                     .Add("DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=json,cobertura")
                                     ).ToConsole()
                      .ExecuteBufferedAsync(cancellationToken)
                      .ConfigureAwait(false);

            MoveCoverageOutputFiles(testOutputPath);

            // Removes all files in inner folders, workaround for https://github.com/microsoft/vstest/issues/2334
            foreach (var path in Directory.EnumerateDirectories(testOutputPath).Select(FilePath.New))
            {
                DeleteDir(path);
            }
        });

        Target("default", DependsOn("build"));

        try {
            // RunTargetsAndExitAsync hangs Target on Ctrl+C
            await RunTargetsWithoutExitingAsync(arguments, options, ex => ex is OperationCanceledException).ConfigureAwait(false);
        }
        catch (TargetFailedException tfe) {
            if (tfe.InnerException is OperationCanceledException oce)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(oce.Message);
                Console.ResetColor();
            }
        }
        catch (Exception e) {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"Unhandled exception: {e}");
            Console.ResetColor();
        }
    }
Beispiel #4
0
 private static void Main()
 {
     Cli.Execute <Commands>();
 }
Beispiel #5
0
        /// <summary>Build project for repository</summary>
        /// <param name="arguments">A list of targets to run or list.</param>
        /// <param name="clear">Clear the console before execution.</param>
        /// <param name="dryRun">Do a dry run without executing actions.</param>
        /// <param name="host">Force the mode for a specific host environment (normally auto-detected).</param>
        /// <param name="listDependencies">List all (or specified) targets and dependencies, then exit.</param>
        /// <param name="listInputs">List all (or specified) targets and inputs, then exit.</param>
        /// <param name="listTargets">List all (or specified) targets, then exit.</param>
        /// <param name="listTree">List all (or specified) targets and dependency trees, then exit.</param>
        /// <param name="noColor">Disable colored output.</param>
        /// <param name="parallel">Run targets in parallel.</param>
        /// <param name="skipDependencies">Do not run targets' dependencies.</param>
        /// <param name="verbose">Enable verbose output.</param>
        /// <param name="configuration">The configuration for building</param>
        private static async Task Main(
            string[] arguments,
            bool clear,
            bool dryRun,
            Host host,
            bool listDependencies,
            bool listInputs,
            bool listTargets,
            bool listTree,
            bool noColor,
            bool parallel,
            bool skipDependencies,
            bool verbose,
            // our options here
            string configuration = "Debug"
            )
        {
            SetEnvVariables();

            var options = new Options {
                Clear            = clear,
                DryRun           = dryRun,
                Host             = host,
                ListDependencies = listDependencies,
                ListInputs       = listInputs,
                ListTargets      = listTargets,
                ListTree         = listTree,
                NoColor          = noColor,
                Parallel         = parallel,
                SkipDependencies = skipDependencies,
                Verbose          = verbose,
            };

            var dotnet = TryFindDotNetExePath()
                         ?? throw new FileNotFoundException("'dotnet' command isn't found. Try to set DOTNET_ROOT variable.");

            Target("restore-tools", async() => {
                var cmd = await Cli.Wrap(dotnet).WithArguments($"tool restore --ignore-failed-sources").ToConsole()
                          .ExecuteBufferedAsync().Task.ConfigureAwait(false);
            });

            Target("restore", async() => {
                var isPublicRelease = bool.Parse(Environment.GetEnvironmentVariable("NBGV_PublicRelease") ?? "false");
                var cmd             = await Cli.Wrap(dotnet).WithArguments($"msbuild -noLogo " +
                                                                           "-t:Restore " +
                                                                           "-p:RestoreForce=true " +
                                                                           "-p:RestoreIgnoreFailedSources=True " +
                                                                           $"-p:Configuration={configuration} " +
                                                                           // for Nerdbank.GitVersioning
                                                                           $"-p:PublicRelease={isPublicRelease} "
                                                                           ).ToConsole()
                                      .ExecuteBufferedAsync().Task.ConfigureAwait(false);
            });

            Target("build", async() => {
                var cmd = await Cli.Wrap(dotnet).WithArguments($"build -noLogo -c {configuration}")
                          .ToConsole()
                          .ExecuteBufferedAsync().Task.ConfigureAwait(false);
            });

            Target("coverage", async() => {
                var resultsDirectory = Path.GetFullPath(Path.Combine("artifacts", "tests", "output"));
                var cmd = await Cli.Wrap(dotnet)
                          .WithArguments($"test " +
                                         "--nologo " +
                                         "--no-restore " +
                                         $"--collect:\"XPlat Code Coverage\" --results-directory {resultsDirectory} " +
                                         $"--logger trx;LogFileName=\"{Path.Combine(resultsDirectory, "tests.trx").Replace("\"", "\\\"")}\" " +
                                         $"-c {configuration} " +
                                         "-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=json,cobertura"
                                         )
                          .ToConsole()
                          .ExecuteBufferedAsync().Task.ConfigureAwait(false);

                MoveAttachmentsToResultsDirectory(resultsDirectory, cmd.StandardOutput);
                TryRemoveTestsOutputDirectories(resultsDirectory);
        public async Task <(string, string)> ExecuteWithCliWrap()
        {
            var result = await Cli.Wrap(FilePath).WithArguments(Args).ExecuteBufferedAsync();

            return(result.StandardOutput, result.StandardError);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Cli.WriteHeader("Haplogroup Tree Builder", "~|Blue~~White~");
            Cli.WriteLine("Loading trunk");
            var treePath  = PathHelper.GetExecutingPath("trees");
            var trunkFile = GetTreeFile(Path.Combine(treePath, "ydnatree.txt"));
            var trunk     = ParseTree(trunkFile);
            var treeFiles = Directory.GetFiles(treePath, "ydnatree_*.txt");

            Cli.WriteLine("Loading ~Cyan~{0}~R~ trees", treeFiles.Length);
            var trees = treeFiles.Select(ParseTree).ToList();

            Cli.WriteLine("Merging trees");
            var lastCount = -1;

            while (trees.Any())
            {
                foreach (var childTree in trees.ToArray())
                {
                    var match = FindHaplogroup(childTree.Name, trunk);

                    if (match == null)
                    {
                        continue;
                    }

                    match.Children.AddRange(childTree.Children);
                    foreach (var c in childTree.Children)
                    {
                        c.Parent = match;
                    }

                    trees.Remove(childTree);
                }

                if (lastCount == trees.Count)
                {
                    break;
                }

                lastCount = trees.Count;
            }

            trunk = RemoveFiller(trunk);

            if (!trees.Any())
            {
                Cli.WriteLine("All trees merged");
            }
            else
            {
                Cli.WriteLine("~Yellow~Tree merge failed~r~");
            }

            Cli.WriteLine("Loading SNP index");
            var snpIndexZipFile = GetTreeFile("ISOGG 2015 Y-DNA SNP Index.zip");
            var tempDir         = PathHelper.GetExecutingPath("Temp");

            Directory.CreateDirectory(tempDir);
            ZipFile.ExtractToDirectory(snpIndexZipFile, tempDir);
            var snpIndexHtmlFile = Path.Combine(tempDir, "ISOGG 2015 Y-DNA SNP Index.html");
            var snpIndex         = ParseSnpIndex(GetTreeFile(snpIndexHtmlFile));

            File.Delete(snpIndexHtmlFile);
            SaveSnpIndex(snpIndex);

            var snpHaplogroupTable = snpIndex
                                     .GroupBy(x => x.Haplogroup)
                                     .ToDictionary(x => x.Key, x => x.ToArray());

            Cli.WriteLine(
                "~Cyan~{0:n0}~R~ SNPs loaded for ~Cyan~{1:n0}~R~ haplogroups",
                snpIndex.Length,
                snpHaplogroupTable.Count);


            var groupMatches = snpHaplogroupTable
                               .Select(x => new
            {
                Group = FindHaplogroup(x.Key, trunk),
                Snps  = x,
            })
                               .Where(x => x.Group != null)
                               .ToArray();

            foreach (var g in groupMatches)
            {
                g.Group.Mutations = g.Snps.Value.ToList();
            }

            Cli.WriteLine("Saving trees");
            JsonSerializer.SerializeToFile(@"ydnatree.json", trunk);
            File.WriteAllText(@"ydnatree.txt", Dump(trunk, dumpSnps: true));
            File.WriteAllText(@"ydnatree_nosnps.txt", Dump(trunk, dumpSnps: false));
            Cli.WriteLine("~Green~Done~R~");
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Client c = new Client();
            ClientBindingList.MyClientList.Clear();
            userNumbersList.Clear();

            c.SearchClients(search.Text);
            List<Cli> myLi = new List<Cli>();
            foreach (Client inC in ClientBindingList.MyClientList)
            {
                userNumbersList.Add(inC.UserNumber);
                Cli me = new Cli();
                me.FirstName = inC.FirstName;
                me.Surname = inC.Surname;
                me.ContactNumber = inC.ContactNumber;
                myLi.Add(me);
            }
            gvwStudents.DataSource = myLi;
            gvwStudents.DataBind();
        }
Beispiel #9
0
 public void WriteSubheaderTest(string text, string style)
 {
     Cli.WriteSubheader(text, style);
     // TODO: add assertions to method CliTest.WriteSubheaderTest(String, String)
 }
Beispiel #10
0
 public void WriteQueryMessageTest09(string format, object[] arg)
 {
     Cli.WriteQueryMessage(format, arg);
     // TODO: add assertions to method CliTest.WriteQueryMessageTest09(String, Object[])
 }
Beispiel #11
0
 public void WriteQueryMessageTest08(string message)
 {
     Cli.WriteQueryMessage(message);
     // TODO: add assertions to method CliTest.WriteQueryMessageTest08(String)
 }
Beispiel #12
0
 public void WriteLineTest10()
 {
     Cli.WriteLine();
     // TODO: add assertions to method CliTest.WriteLineTest10()
 }
Beispiel #13
0
 public void WriteLineTest09(string message)
 {
     Cli.WriteLine(message);
     // TODO: add assertions to method CliTest.WriteLineTest09(String)
 }
Beispiel #14
0
 public void WriteLineTest08(string format, object[] arg)
 {
     Cli.WriteLine(format, arg);
     // TODO: add assertions to method CliTest.WriteLineTest08(String, Object[])
 }
Beispiel #15
0
 public void EraseStylesTest01(string text, Func <StringBuilder, StringBuilder> callback)
 {
     Cli.EraseStyles(text, callback);
     // TODO: add assertions to method CliTest.EraseStylesTest01(String, Func`2<StringBuilder,StringBuilder>)
 }
        protected void Unnamed_Click(object sender, EventArgs e)
        {
            int rowIndex = gvwStudents.SelectedIndex;
            usernumber = userNumbersList[rowIndex];

            User u = new User();
            string firstName = FirstName.Text;
            string surname = Surname.Text;
            string email = MCEmail.Text;
            string contactNumber = ContactNumber.Text;
            string address = PhysicalAddress.Text;
            string date = default_datetimepickerss.Text;

            if (String.IsNullOrEmpty(date))
            {
                date = "10/10/2010";
            }

            string[] words = date.Split('/');

            words[2] = words[2].Substring(0, 4);

            DateTime birthday = new DateTime(Convert.ToInt32(words[2]), Convert.ToInt32(words[0]), Convert.ToInt32(words[1]));

            int cityNumber = Convert.ToInt32(CityDDL.SelectedIndex) + 1;
            string gender = GenderDDL.Text;
            Boolean active = true;

            //Automatically assign as Client because a Dealer/Employee is added by a manager
            int securityRoleNumber = 1;

            foreach (Client c in ClientBindingList.MyClientList)
            {
                if (usernumber == c.UserNumber)
                {
                    //Update Client & Dealer normal details
                    User updateUser = new User(usernumber, firstName, surname, email, contactNumber, address, password, securityRoleNumber, cityNumber, birthday, gender, active);
                    //When Client is changed into a Dealer
                    if (c.ClientType == "Client" && CheckBox1.Checked == true)
                    {
                        updateUser.SecurityRoleNumber = 4;
                        updateUser.UpdateUser(updateUser);
                        Dealer d = new Dealer();
                        bool found = false;
                        //If a Client used to be a dealer
                        foreach (Dealer inD in DealerBindingList.DealerList)
                        {
                            if (c.UserNumber == inD.UserNumber)
                            {
                                d.UpdateDealer(inD.UserNumber, Convert.ToInt32(TextBox8.Text), true);
                                c.UpdateClient(c.UserNumber, "Dealer", true);
                                found = true;
                            }
                        }
                        //If the client has never been a dealer
                        if (found == false)
                        {
                            updateUser.UpdateUser(updateUser);
                            d.InsertNewDealer(c.UserNumber, Convert.ToInt32(TextBox8.Text), true);
                            c.UpdateClient(c.UserNumber, "Dealer", true);
                        }

                    }
                    //When a dealer is changed back into a client
                    else if (c.ClientType == "Dealer" && CheckBox1.Checked == false)
                    {
                        Dealer d = new Dealer();
                        updateUser.UpdateUser(updateUser);
                        d.UpdateDealer(c.UserNumber, 0, false);
                        c.UpdateClient(c.UserNumber, "Client", true);
                    }
                    //changing the details associated with an existing dealer
                    else if (c.ClientType == "Dealer" && CheckBox1.Checked == true)
                    {
                        Dealer d = new Dealer();
                        updateUser.SecurityRoleNumber = 4;
                        updateUser.UpdateUser(updateUser);
                        d.UpdateDealer(c.UserNumber, Convert.ToInt32(TextBox8.Text), true);
                    }
                    //Changing the details of an existing client that has never been a dealer
                    else if (c.ClientType == "Client" && CheckBox1.Checked == false)
                    {
                        updateUser.UpdateUser(updateUser);
                    }
                }
            }
            List<Cli> myLi = new List<Cli>();

            foreach (Client inC in ClientBindingList.MyClientList)
            {
                userNumbersList.Add(inC.UserNumber);

                Cli me = new Cli();
                me.FirstName = inC.FirstName;
                me.Surname = inC.Surname;
                me.ContactNumber = inC.ContactNumber;
                myLi.Add(me);
            }
            gvwStudents.DataSource = myLi;
            gvwStudents.DataBind();
        }
 public static int Main(string[] args) {
   var cli = new Cli();
   cli.Run(args);
   return cli.Succeeded ? 0 : 1;
 }
Beispiel #18
0
 public void WriteSuccessMessageTest(string format, object arg0)
 {
     Cli.WriteSuccessMessage(format, arg0);
     // TODO: add assertions to method CliTest.WriteSuccessMessageTest(String, Object)
 }
Beispiel #19
0
 public void DumpTableTest(IEnumerable <KeyValuePair <string, string> > nameValuePairs)
 {
     Cli.DumpTable(nameValuePairs);
     // TODO: add assertions to method CliTest.DumpTableTest(IEnumerable`1<KeyValuePair`2<String,String>>)
 }
Beispiel #20
0
        public async Task CompactTask(List.TaskInfo currentTask, CancellationToken cancellationToken)
        {
            try
            {
                /*
                 *  Syntax
                 *  compact [{/c|/u}] [/s[:dir]] [/a] [/i] [/f] [/q] [FileName[...]]
                 *
                 *  Parameters
                 *
                 *  /c : Compresses the specified directory or file.
                 *  /u : Uncompresses the specified directory or file.
                 *  /s : dir : Specifies that the requested action (compress or uncompress) be applied to all subdirectories of the specified directory, or of the current directory if none is specified.
                 *  /a : Displays hidden or system files.
                 *  /i : Ignores errors.
                 *  /f : Forces compression or uncompression of the specified directory or file. This is used in the case of a file that was partly compressed when the operation was interrupted by a system crash. To force the file to be compressed in its entirety, use the /c and /f parameters and specify the partially compressed file.
                 *  /q : Reports only the most essential information.
                 *  FileName : Specifies the file or directory. You can use multiple file names and wildcard characters (* and ?).
                 *  /? : Displays help at the command prompt.
                 */

                LogToTM($"Current status of {AppName} is {(IsCompacted ? "compressed" : "not compressed")} and the task is set to {(currentTask.Compact ? "compress" : "uncompress")} the app.");
                currentTask.ElapsedTime.Start();

                currentTask.mre.WaitOne();

                var result = await Cli.Wrap("compact")
                             .SetArguments($"{(currentTask.Compact ? "/c" : "/u")} /i /q {(currentTask.ForceCompact ? "/f" : "")} /EXE:{currentTask.CompactLevel} /s")
                             .SetWorkingDirectory(InstallationDirectory.FullName)
                             .SetCancellationToken(cancellationToken)
                             .SetStandardOutputCallback(OnCompactFolderProgress)
                             .SetStandardErrorCallback(OnCompactFolderProgress)
                             .EnableStandardErrorValidation()
                             .ExecuteAsync().ConfigureAwait(false);

                var exitCode = result.ExitCode;
                var stdErr   = result.StandardError;
                var runTime  = result.RunTime;

                LogToTM(string.IsNullOrEmpty(stdErr)
                    ? $"[{AppName}] Task completed in {runTime} - ExitCode: {exitCode}"
                    : $"[{AppName}] Task failed with error message: {stdErr} - ExitCode: {exitCode}");

                currentTask.ElapsedTime.Stop();
                IsCompacted = CompactStatus();
            }
            catch (OperationCanceledException)
            {
                if (!currentTask.ErrorHappened)
                {
                    currentTask.ErrorHappened = true;
                    Functions.TaskManager.Stop();
                    currentTask.Active    = false;
                    currentTask.Completed = true;

                    LogToTM(Framework.StringFormat.Format(Functions.SLM.Translate(nameof(Properties.Resources.TaskCancelled_ElapsedTime)), new { AppName, ElapsedTime = currentTask.ElapsedTime.Elapsed }));
                    Logger.Info(Framework.StringFormat.Format(Functions.SLM.Translate(nameof(Properties.Resources.TaskCancelled_ElapsedTime)), new { AppName, ElapsedTime = currentTask.ElapsedTime.Elapsed }));
                }
            }
            catch (Exception ex)
            {
                LogToTM(ex.ToString());
                Debug.WriteLine(ex);
            }
        }
        public void WriteCommentedFiles(string outputFolder)
        {
            var pageTemplate = GetPageTemplate();

            if (pageTemplate == null)
            {
                Cli.WriteLine("~Red~Could not read code coverage page template~R~");
                return;
            }

            var codePageTable = new CodePageTable();

            var coverageDir = GetCodeCoveragePath(outputFolder);

            _table.Items.Iter(x =>
            {
                Cli.WriteLine("Writing coverage comments for ~Cyan~{0}~R~", x.Plugin);

                var pluginDir         = GetCommentedFilePath(outputFolder, x.Plugin);
                var relativePluginDir = pluginDir.Substring(coverageDir.Length + 1);

                Directory.CreateDirectory(pluginDir);

                var codePages = new List <CodePage>();

                x.Items.Iter(y =>
                {
                    var commentedCode = CreateCommentedCode(y);

                    if (commentedCode == null)
                    {
                        return;
                    }

                    var codeFilename = GetRelativeCodePath(y);

                    var page = string.Format(
                        pageTemplate,
                        codeFilename,
                        HttpUtility.HtmlEncode(x.Plugin),
                        HttpUtility.HtmlEncode(commentedCode));

                    var pageFilename = Path.Combine(pluginDir, GetPageFilename(y));

                    File.WriteAllText(pageFilename, page);

                    var relateivePageFilename = Path.Combine(relativePluginDir, GetPageFilename(y));

                    codePages.Add(new CodePage(codeFilename, relateivePageFilename));

                    Cli.WriteLine("[~Green~+~R~] {0}", codeFilename);
                });

                codePageTable.Add(x.Plugin, codePages);

                Cli.WriteLine();
            });

            var index = Path.Combine(coverageDir, "index.html");

            File.WriteAllText(index, codePageTable.ToHtml());

            var highlighterDir = new DirectoryInfo(PathHelper.GetEntryPath("SyntaxHighlighter"));

            highlighterDir.CopyTo(coverageDir);
        }
 public void ExecuteAndForget_EchoArgsToStdout_Test()
 {
     Cli.Wrap(EchoArgsToStdoutBat).ExecuteAndForget();
 }
Beispiel #23
0
 public VBoxManager()
 {
     VBoxManagerProcess = Cli.Wrap(@"C:\Program Files\Oracle\VirtualBox\VBoxManage.exe");
 }
Beispiel #24
0
 public Datastorage(Cli setcontroler)
 {
     controler = setcontroler;
     attach_events();
 }
Beispiel #25
0
        public void ExecuteAndForget_EchoArgs_Test()
        {
            var cli = new Cli(EchoArgsBat);

            cli.ExecuteAndForget("Hello world");
        }
        public static async Task <ExecuteResponse> ExecuteAsync(ExecuteRequest request)
        {
            string shellScriptFile       = null;
            string shellScriptOutputFile = null;

            // create script file

            shellScriptFile       = Path.Combine(request.WorkingDirectory, $"{Guid.NewGuid().ToString().Split('-').First()}.bat");
            shellScriptOutputFile = $"{shellScriptFile}.output";
            File.WriteAllText(shellScriptFile, $@"""{request.FilePath}"" {request.Arguments} > ""{shellScriptOutputFile}""");

            // run script file

            var commandTask = Cli
                              .Wrap(shellScriptFile)
                              .WithValidation(CommandResultValidation.None)
                              .WithWorkingDirectory(request.WorkingDirectory)
                              .ExecuteBufferedAsync(CancellationToken);

            BufferedCommandResult result          = null;    // result is null when cancelled
            ExecuteResponse       executeResponse = null;

            try
            {
                result = await commandTask;
            }
            catch (OperationCanceledException)
            {
            }

            if (result != null)
            {
                var exitCode = result.ExitCode;

                // get script output

                var outputList = new List <string>();

                var directOutput = string.Join(Environment.NewLine, new[]
                {
                    result.StandardOutput,
                    Environment.NewLine,
                    result.StandardError
                }
                                               .Where(x => !string.IsNullOrWhiteSpace(x)))
                                   .Trim('\r', '\n')
                                   .Trim();

                if (!string.IsNullOrWhiteSpace(directOutput))
                {
                    outputList.Add(directOutput);
                }

                if (File.Exists(shellScriptOutputFile))
                {
                    var redirectOutput = File.ReadAllText(shellScriptOutputFile)
                                         .Trim('\r', '\n')
                                         .Trim();

                    if (!string.IsNullOrWhiteSpace(redirectOutput))
                    {
                        outputList.Add(redirectOutput);
                    }
                }
                else
                {
                    // There is a problem if the shellScriptOutputFile is not produced
                    exitCode = FAILED_TO_PRODUCE_OUTPUT_FILE_CODE;
                }

                var output = string.Join(Environment.NewLine, outputList)
                             .Trim('\r', '\n')
                             .Trim();

                executeResponse = new ExecuteResponse
                {
                    ExitCode  = exitCode,
                    ExitTime  = result.ExitTime,
                    RunTime   = result.RunTime,
                    StartTime = result.StartTime,
                    Output    = output
                };
            }

            FileSystemInfoDeleteExtensions.TryDelete(shellScriptFile);
            FileSystemInfoDeleteExtensions.TryDelete(shellScriptOutputFile);

            return(executeResponse);
        }
Beispiel #27
0
 internal CloudFoundryDriver(Context context)
 {
     _context   = context;
     _cfCli     = new CloudFoundryCli(context.Shell);
     _dotnetCli = new Cli("dotnet", _context.Shell);
 }
Beispiel #28
0
        public static void PerformanceCompare()
        {
            long msLib    = 0;
            long msCli    = 0;
            long msCliDm1 = 0;
            long msCliDm2 = 0;

            int sampleSize = 5;

            Console.WriteLine($"Testing {sampleSize}x libgphoto2");
            for (int i = 0; i < sampleSize; i++)
            {
                Stopwatch sw = new Stopwatch();

                sw.Start();

                TestLibCapture();

                sw.Stop();

                msLib += Convert.ToInt64(sw.Elapsed.TotalMilliseconds);
            }

            Console.WriteLine($"Average libgphoto2 was {msLib / sampleSize}ms");
            Console.WriteLine($"Total libgphoto2 was {msLib / 1000d}s");


            Console.WriteLine();

            Console.WriteLine($"Testing {sampleSize}x gphoto2_ci_binding");
            paths = new List <string>();
            for (int i = 0; i < sampleSize; i++)
            {
                Stopwatch sw = new Stopwatch();

                sw.Start();

                TestCliCapture();

                sw.Stop();

                msCli += Convert.ToInt64(sw.Elapsed.TotalMilliseconds);
            }
            Console.WriteLine($"Average gphoto2_ci_binding was {msCli / sampleSize}ms");
            Console.WriteLine($"Sub-Total gphoto2_ci_binding was {msCli / 1000d}s");
            Console.WriteLine();

            Console.WriteLine($"Downloading Method 1 {sampleSize}x gphoto2_ci_binding");
            List <Camera> cams = Cli.AutoDetect(false);

            Directory.CreateDirectory(Environment.CurrentDirectory + "/temp");
            string folder = "";

            foreach (string path in paths)
            {
                Stopwatch sw = new Stopwatch();

                sw.Start();

                cams[0].DownloadFile(Environment.CurrentDirectory + "/temp/" + Path.GetFileName(path), path);

                sw.Stop();

                folder = Path.GetDirectoryName(path);

                msCliDm1 += Convert.ToInt64(sw.Elapsed.TotalMilliseconds);
            }
            Console.WriteLine($"Average gphoto2_ci_binding was {msCliDm1 / sampleSize}ms");
            Console.WriteLine($"Sub-Total gphoto2_ci_binding was {msCliDm1 / 1000d}s");

            Console.WriteLine($"Downloading Method 2 {sampleSize}x gphoto2_ci_binding");
            Directory.Delete(Environment.CurrentDirectory + "/temp", true);
            Directory.CreateDirectory(Environment.CurrentDirectory + "/temp");

            Stopwatch ssw = new Stopwatch();

            ssw.Start();

            cams[0].DownloadLast(sampleSize, Environment.CurrentDirectory + "/temp", folder);

            ssw.Stop();

            msCliDm2 = Convert.ToInt64(ssw.Elapsed.TotalMilliseconds);
            Console.WriteLine($"Sub-Total gphoto2_ci_binding was {msCliDm2 / 1000d}s");

            Console.WriteLine();
            Console.WriteLine($"Total gphoto2_ci_binding w/download method 1 was {(msCliDm1+msCli) / 1000d}s");
            Console.WriteLine($"Total gphoto2_ci_binding w/download method 2 was {(msCliDm2+msCli) / 1000d}s");
            Console.WriteLine();
            Console.WriteLine($"Difference w/o downloading {(msLib-msCli) / 1000d}s");
            Console.WriteLine();
            Console.WriteLine($"Difference with downloading method 1 {(msLib-(msCliDm1+msCli)) / 1000d}s");
            Console.WriteLine($"Difference with downloading method 2 {(msLib-(msCliDm2+msCli)) / 1000d}s");
        }
 public void CommandException_Simple()
 {
     Assert.Throws <DivideByZeroException>(
         () => Cli.Execute <CommandModel_ExceptionThrow>(new string[] { }));
 }
Beispiel #30
0
        public static async Task <ExecuteResponse> ExecuteAsync(ExecuteRequest request)
        {
            Process process               = null;
            string  shellScriptFile       = null;
            string  shellScriptOutputFile = null;

            try
            {
                // create script file

                shellScriptFile       = Path.Combine(request.WorkingDirectory, $"{Path.GetFileNameWithoutExtension(request.FilePath)}-{Guid.NewGuid().ToString().Split('-').First()}.bat");
                shellScriptOutputFile = $"{shellScriptFile}.output";
                File.WriteAllText(shellScriptFile, $@"""{request.FilePath}"" {request.Arguments} > ""{shellScriptOutputFile}""");

                // run script file

                var commandTask = Cli
                                  .Wrap(shellScriptFile)
                                  .WithValidation(CommandResultValidation.None)
                                  .WithWorkingDirectory(request.WorkingDirectory)
                                  .ExecuteBufferedAsync();

                // enlist process

                try
                {
                    process = Process.GetProcessById(commandTask.ProcessId);
                    if (process != null)
                    {
                        Processes.Add(process);
                    }
                }
                catch
                {
                    // ignore
                }

                // run command

                var result   = await commandTask;
                var exitCode = result.ExitCode;

                // get script output

                var outputList = new List <string>();

                var directOutput = string.Join(Environment.NewLine, new[]
                {
                    result.StandardOutput,
                    Environment.NewLine,
                    result.StandardError
                }
                                               .Where(x => !string.IsNullOrWhiteSpace(x)))
                                   .Trim('\r', '\n')
                                   .Trim();

                if (!string.IsNullOrWhiteSpace(directOutput))
                {
                    outputList.Add(directOutput);
                }

                if (File.Exists(shellScriptOutputFile))
                {
                    var redirectOutput = File.ReadAllText(shellScriptOutputFile)
                                         .Trim('\r', '\n')
                                         .Trim();

                    if (!string.IsNullOrWhiteSpace(redirectOutput))
                    {
                        outputList.Add(redirectOutput);
                    }
                }
                else
                {
                    // There is a problem if the shellScriptOutputFile is not produced
                    exitCode = FAILED_TO_PRODUCE_OUTPUT_FILE_CODE;
                }

                var output = string.Join(Environment.NewLine, outputList)
                             .Trim('\r', '\n')
                             .Trim();

                // return

                return(new ExecuteResponse
                {
                    ExitCode = exitCode,
                    ExitTime = result.ExitTime,
                    RunTime = result.RunTime,
                    StartTime = result.StartTime,
                    Output = output
                });
            }
            finally
            {
                try
                {
                    File.Delete(shellScriptFile);
                }
                catch
                {
                    // ignore
                }

                try
                {
                    File.Delete(shellScriptOutputFile);
                }
                catch
                {
                    // ignore
                }

                try
                {
                    process?.Kill();
                }
                catch
                {
                    // ignore
                }

                try
                {
                    process?.Dispose();
                }
                catch
                {
                    // ignore
                }

                try
                {
                    Processes.Remove(process);
                }
                catch
                {
                    // ignore
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Client c = new Client();

            c.SearchClients("");

            List<Cli> myLi = new List<Cli>();

            foreach (Client inC in ClientBindingList.MyClientList)
            {
                userNumbersList.Add(inC.UserNumber);

                Cli me = new Cli();
                me.FirstName = inC.FirstName;
                me.Surname = inC.Surname;
                me.ContactNumber = inC.ContactNumber;
                myLi.Add(me);
            }

            gvwStudents.DataSource = myLi;
            gvwStudents.DataBind();

            //City
            DBConnection bindComboBox = new DBConnection();
            City cities = new City();
            DataTable DT = new DataTable();
            DT = bindComboBox.BindDropdown(cities.SearchCities(), "City_Name", "City_Number");
            CityDDL.DataSource = DT;
            CityDDL.DataValueField = "City_Number";
            CityDDL.DataTextField = "City_Name";

            CityDDL.DataBind();

            GenderDDL.Items.Add("Male");
            GenderDDL.Items.Add("Female");
        }
Beispiel #32
0
        static async Task <bool> DownloadVideo(string url, string resolution)
        {
            string videoUrl, audioUrl, dashUrl;

            videoUrl = audioUrl = dashUrl = String.Empty;
            string ptrn1 = @"(?<url>https?://(?:[^/]+\.)?reddit\.com/r/[^/]+/comments/(?<id>[^/?#&]+))";
            string ptrn2 = @"https?://v\.redd\.it/(?<id>[^/?#&]+)";

            if (Regex.IsMatch(url, ptrn1))
            {
                string id = Regex.Match(url, ptrn1).Groups["id"].Value;

                videoFileName = "video_" + id + ".mp4";
                audioFileName = "audio_" + id + ".mp3";

                string jsonData = await client.GetStringAsync(Regex.Match(url, ptrn1).Value + "/.json");

                JArray json = JArray.Parse(jsonData);

                videoUrl = json[0]["data"]["children"][0]["data"]["url"].ToString() + '/';
                audioUrl = videoUrl;
                dashUrl  = videoUrl + "DASHPlaylist.mpd";
            }
            else if (Regex.IsMatch(url, ptrn2))
            {
                string id = Regex.Match(url, ptrn2).Groups["id"].Value;

                videoFileName = "video_" + id + ".mp4";
                audioFileName = "audio_" + id + ".mp3";

                videoUrl = $"https://v.redd.it/{id}/";
                audioUrl = $"https://v.redd.it/{id}/";
                dashUrl  = $"https://v.redd.it/{id}/DASHPlaylist.mpd";
            }
            else
            {
                return(false);
            }
            bool downloadResultDash = await Download(dashUrl, "DASHPlaylist.mpd");

            if (downloadResultDash)
            {
                var doc = new XmlDocument();
                doc.Load("DASHPlaylist.mpd");

                var curr = doc.GetElementsByTagName("Representation");

                foreach (XmlNode node in curr)
                {
                    var attrs       = node.Attributes;
                    var parentAttrs = node.ParentNode.Attributes;
                    if (attrs["mimeType"]?.Value == "video/mp4" && attrs["height"]?.Value == resolution)
                    {
                        videoUrl += node.FirstChild.InnerText;
                    }
                    else if (attrs["mimeType"]?.Value == "audio/mp4")
                    {
                        audioUrl += node.ChildNodes[1].InnerText;
                    }
                    else if (parentAttrs["mimeType"]?.Value == "video/mp4" && attrs["height"]?.Value == resolution)
                    {
                        videoUrl += node.FirstChild.InnerText;
                    }
                    else if (parentAttrs["mimeType"]?.Value == "audio/mp4")
                    {
                        audioUrl += node.ChildNodes[1].InnerText;
                    }
                }
                System.Console.WriteLine(videoUrl);
                System.Console.WriteLine(audioUrl);

                bool downloadResultVideo = await Download(videoUrl, videoFileName);

                bool downloadResultAudio = await Download(audioUrl, audioFileName);

                if (downloadResultAudio == true && downloadResultVideo == true)
                {
                    string muxedFileName = "muxed_" + videoFileName;
                    var    result        = await Cli.Wrap("/usr/bin/ffmpeg")
                                           .WithArguments($"-y -i {videoFileName} -i {audioFileName} {muxedFileName}")
                                           .ExecuteAsync();

                    System.IO.File.Delete(videoFileName);
                    System.IO.File.Delete(audioFileName);
                    return(true);
                }
            }

            return(false);
        }
Beispiel #33
0
 Parser(object root, bool interactive, Cli.ITerminal terminal)
 {
     this.terminal = terminal;
     this.LineBuffer = interactive ? (Cli.LineBuffer.Abstract)new Cli.LineBuffer.InteractiveWithHistory(terminal) : new Cli.LineBuffer.Simple(terminal);
     this.Current = this.Root = new Object(root) { Parser = this };
 }
Beispiel #34
0
 public static void Main(string[] args)
 {
     /* CosturaUtility.Initialize(); */
     Cli.CliMenu();
 }
Beispiel #35
0
 public DockerWrapper()
 {
     _cliDocker = new Cli("docker");
 }
Beispiel #36
0
 public void ExecuteAndForget_EchoArgsToStdout_Test()
 {
     // Arrange & act & assert
     Cli.Wrap(EchoArgsToStdoutBat).ExecuteAndForget();
 }
Beispiel #37
0
 public int Run(Cli console,string[] args)
 {
     _shell.Stop();
     return 0;
 }
Beispiel #38
0
 public int Run(Cli console,string[] args)
 {
     console.Out.WriteLine(string.Join(" ",args));
     return 0;
 }