Example #1
0
        private static void Cleanup()
        {
            using (HelpContext db = new HelpContext())
            {
                foreach (User user in db.Users.Where(u => u.SerializedRoles == "" || u.SerializedRoles == null || u.SerializedRoles.StartsWith(",")))
                {
                    var roles = user.Roles.ToList();
                    if (!roles.Contains(Role.UserRole))
                    {
                        roles.Add(Role.UserRole);
                    }
                    roles.Remove("");
                    user.Roles = roles.Distinct().ToArray();
                }
                var usersToRemove = new List <User>();
                foreach (User user in db.Users.Where(u => u.EmailAddress == "" || u.EmailAddress == null).ToList())
                {
                    if (string.IsNullOrWhiteSpace(user.VirtualId))
                    {
                        bool shouldDelete = user.LoginTokens.Any(loginToken => loginToken.CreatedAt.AddDays(31) < DateTime.Now);
                        if (shouldDelete)
                        {
                            usersToRemove.Add(user);
                        }
                    }
                }
                db.Users.RemoveRange(usersToRemove);

                db.Channels.RemoveRange(db.Channels.Where(c => !c.Users.Any()));
                db.SaveChanges();
            }
        }
Example #2
0
        public override bool AddHelpContext(string contextName, string pathToContextFile)
        {
            if (_contextToDictionary.ContainsKey(contextName))
            {
                return(false);
            }

            try
            {
                bool bExists = System.IO.File.Exists(pathToContextFile);
                if (bExists == false)
                {
                    Log.Error("The CSV file '{0}' does not exist and thus cannot be added as a help context!", pathToContextFile);
                    return(false);
                }

                HelpContext hc = new HelpContext(pathToContextFile, this);
                if (!hc.Reload())
                {
                    return(false);
                }

                _contextToDictionary.Add(contextName, hc);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #3
0
        public override string GetHelpPage(string key, string contextName = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }

            // If a context is given, try that one first to prevent key collisions in different contexts
            if (!string.IsNullOrEmpty(contextName) && _contextToDictionary.ContainsKey(contextName))
            {
                HelpContext hc = null;
                if (_contextToDictionary.TryGetValue(contextName, out hc))
                {
                    string sPage = null;
                    if (hc._dict.TryGetValue(key, out sPage))
                    {
                        return(sPage);
                    }
                }
            }

            foreach (HelpContext context in _contextToDictionary.Values)
            {
                string sPage = null;
                if (context._dict.TryGetValue(key, out sPage))
                {
                    return(sPage);
                }
            }

            return(null);
        }
Example #4
0
        public Task CanShowTemplateOptions_MultipleTemplate_MultipleParams()
        {
            var template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group", precedence: 0)
                            .WithChoiceParameter("choice", new[] { "val1", "val2" }, description: "my description", defaultValue: "def-val-not-shown", defaultIfNoOptionValue: "def-val-not-shown")
                            .WithParameter("bool", paramType: "boolean", description: "my bool", defaultValue: "false", defaultIfNoOptionValue: "false");
            var template2 = new MockTemplateInfo("foo", identity: "foo.2", groupIdentity: "foo.group", precedence: 2)
                            .WithChoiceParameter("choice", new[] { "val1", "val3" }, description: "my description", defaultValue: "def-val", defaultIfNoOptionValue: "def-val-no-arg")
                            .WithParameter("int", paramType: "integer", description: "my int", defaultValue: "0", defaultIfNoOptionValue: "10");
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template1, template2 }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand1 = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates[0]);
            TemplateCommand templateCommand2 = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates[1]);

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand2, templateCommand1 }, helpContext);
            return(Verifier.Verify(sw.ToString(), _verifySettings.Settings));
        }
Example #5
0
 public SimpleChannel(int id, bool isAdmin = false)
 {
     IsAdmin = isAdmin;
     using (HelpContext db = new HelpContext())
     {
         Channel c = db.Channels.Find(id);
         Id          = id;
         ChannelName = c.ChannelName;
         Questions   = new Dictionary <int, SimpleQuestion>();
         foreach (Question q in c.Questions)
         {
             Questions.Add(q.Id, q.ToSimpleQuestion());
         }
         ChatMessages = new Dictionary <int, SimpleChatMessage>();
         foreach (ChatMessage cm in c.ChatMessages)
         {
             ChatMessages.Add(cm.Id, cm.ToSimpleChatMessage());
         }
         Users = new Dictionary <int, SimpleUser>();
         foreach (User u in c.Users)
         {
             Users.Add(u.Id, u.ToSimpleUser());
         }
         if (IsAdmin)
         {
             TimeLeft = c.TimeLeft;
         }
     }
 }
Example #6
0
        public void CanShowUsage_ForMultipleShortNames()
        {
            ITemplateEngineHost host = TestHost.GetVirtualHost();

            NewCommand   myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowUsage(myCommand, new[] { "short-name1", "short-name2" }, helpContext);
            Assert.Equal($"Usage:{Environment.NewLine}  new short-name1 [options] [template options]{Environment.NewLine}  new short-name2 [options] [template options]{Environment.NewLine}{Environment.NewLine}", sw.ToString());
        }
Example #7
0
 private static IEnumerable <HelpSectionDelegate> CustomHelpLayout(HelpContext context)
 {
     if (context.ParseResult.CommandResult.Command is ICustomHelp custom)
     {
         return(custom.CustomHelpLayout());
     }
     else
     {
         return(HelpBuilder.Default.GetLayout());
     }
 }
Example #8
0
 public string SaveHelpContent(string operation, string userId, string categoryId, string areaId, string itemCode, string value)
 {
     try
     {
         return(HelpContext.Content(operation, userId, categoryId, areaId, itemCode, "Help", value));
     }
     catch (Exception ex)
     {
         var em = ex.Message;
         return("");
     }
 }
Example #9
0
File: Parser.cs Project: nohwnd/sdk
            public override void Write(HelpContext context)
            {
                var command  = context.Command;
                var helpArgs = new string[] { "--help" };

                if (command.Equals(RootCommand))
                {
                    Console.Out.WriteLine(HelpUsageText.UsageText);
                }
                else if (command.Name.Equals(NuGetCommandParser.GetCommand().Name))
                {
                    NuGetCommand.Run(helpArgs);
                }
                else if (command.Name.Equals(MSBuildCommandParser.GetCommand().Name))
                {
                    new MSBuildForwardingApp(helpArgs).Execute();
                }
                else if (command.Name.Equals(VSTestCommandParser.GetCommand().Name))
                {
                    new VSTestForwardingApp(helpArgs).Execute();
                }
                else if (command is Microsoft.TemplateEngine.Cli.Commands.ICustomHelp helpCommand)
                {
                    var blocks = helpCommand.CustomHelpLayout();
                    foreach (var block in blocks)
                    {
                        block(context);
                    }
                }
                else if (command.Name.Equals(FormatCommandParser.GetCommand().Name))
                {
                    new DotnetFormatForwardingApp(helpArgs).Execute();
                }
                else
                {
                    if (command.Name.Equals(ListProjectToProjectReferencesCommandParser.GetCommand().Name))
                    {
                        ListCommandParser.SlnOrProjectArgument.Name        = CommonLocalizableStrings.ProjectArgumentName;
                        ListCommandParser.SlnOrProjectArgument.Description = CommonLocalizableStrings.ProjectArgumentDescription;
                    }
                    else if (command.Name.Equals(AddPackageParser.GetCommand().Name) || command.Name.Equals(AddCommandParser.GetCommand().Name))
                    {
                        // Don't show package completions in help
                        AddPackageParser.CmdPackageArgument.Completions.Clear();
                    }

                    base.Write(context);
                }
            }
Example #10
0
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                var serializeModel = JsonConvert.DeserializeObject <PrincipalSerializeModel>(authTicket.UserData);
                using (HelpContext db = new HelpContext())
                {
                    HttpContext.Current.User = db.Users.Find(serializeModel.UserId);
                }
            }
        }
Example #11
0
        internal static void ShowCommandOptions(
            IEnumerable <TemplateCommand> templatesToShow,
            TemplateCommand preferredTemplate,
            HelpContext context)
        {
            List <Option> optionsToShow = new List <Option>()
            {
                preferredTemplate.NameOption,
                preferredTemplate.OutputOption,
                preferredTemplate.DryRunOption,
                TemplateCommand.ForceOption,
                preferredTemplate.NoUpdateCheckOption
            };

            foreach (var template in templatesToShow)
            {
                if (template.LanguageOption != null)
                {
                    optionsToShow.Add(template.LanguageOption);
                    break;
                }
            }
            foreach (var template in templatesToShow)
            {
                if (template.TypeOption != null)
                {
                    optionsToShow.Add(template.TypeOption);
                    break;
                }
            }
            foreach (var template in templatesToShow)
            {
                if (template.AllowScriptsOption != null)
                {
                    optionsToShow.Add(template.AllowScriptsOption);
                    break;
                }
            }

            context.Output.WriteLine(context.HelpBuilder.LocalizationResources.HelpOptionsTitle());
            IEnumerable <TwoColumnHelpRow> optionsToWrite = optionsToShow.Select(o => context.HelpBuilder.GetTwoColumnRow(o, context));

            context.HelpBuilder.WriteColumns(optionsToWrite.ToArray(), context);
            context.Output.WriteLine();
        }
Example #12
0
        internal static void ShowTemplateSpecificOptions(
            IEnumerable <TemplateCommand> templates,
            HelpContext context)
        {
            IEnumerable <TemplateOption> optionsToShow = CollectOptionsToShow(templates, context);

            context.Output.WriteLine(HelpStrings.SectionHeader_TemplateSpecificOptions);
            if (!optionsToShow.Any())
            {
                context.Output.WriteLine(HelpStrings.Text_NoTemplateOptions.Indent());
                return;
            }

            IEnumerable <TwoColumnHelpRow> optionsToWrite = optionsToShow.Select(o => context.HelpBuilder.GetTwoColumnRow(o.Option, context));

            context.HelpBuilder.WriteColumns(optionsToWrite.ToArray(), context);
            context.Output.WriteLine();
        }
Example #13
0
        private static void WriteCustomInstantiateHelp(HelpContext context, Command command)
        {
            //unhide arguments of NewCommand. They are hidden not to appear in subcommands help.
            foreach (Argument arg in command.Arguments)
            {
                arg.IsHidden = false;
            }

            HelpBuilder.Default.SynopsisSection()(context);
            context.Output.WriteLine();
            CustomUsageSection(context, command);
            context.Output.WriteLine();
            HelpBuilder.Default.CommandArgumentsSection()(context);
            context.Output.WriteLine();
            HelpBuilder.Default.OptionsSection()(context);
            HelpBuilder.Default.SubcommandsSection()(context);
            context.Output.WriteLine();
        }
Example #14
0
            public override void Write(HelpContext context)
            {
                var command  = context.Command;
                var helpArgs = new string[] { "--help" };

                if (command.Equals(RootCommand))
                {
                    Console.Out.WriteLine(HelpUsageText.UsageText);
                }
                else if (command.Name.Equals(NuGetCommandParser.GetCommand().Name))
                {
                    NuGetCommand.Run(helpArgs);
                }
                else if (command.Name.Equals(MSBuildCommandParser.GetCommand().Name))
                {
                    new MSBuildForwardingApp(helpArgs).Execute();
                }
                else if (command.Name.Equals(NewCommandParser.GetCommand().Name))
                {
                    NewCommandShim.Run(helpArgs);
                }
                else if (command.Name.Equals(VSTestCommandParser.GetCommand().Name))
                {
                    new VSTestForwardingApp(helpArgs).Execute();
                }
                else
                {
                    if (command.Name.Equals(ListProjectToProjectReferencesCommandParser.GetCommand().Name))
                    {
                        ListCommandParser.SlnOrProjectArgument.Name        = CommonLocalizableStrings.ProjectArgumentName;
                        ListCommandParser.SlnOrProjectArgument.Description = CommonLocalizableStrings.ProjectArgumentDescription;
                    }
                    else if (command.Name.Equals(AddPackageParser.GetCommand().Name) || command.Name.Equals(AddCommandParser.GetCommand().Name))
                    {
                        // Don't show package suggestions in help
                        AddPackageParser.CmdPackageArgument.Suggestions.Clear();
                    }

                    base.Write(context);
                }
            }
Example #15
0
        public Task CanShowCommandOptions_Basic()
        {
            var           template      = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group");
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowCommandOptions(new[] { templateCommand }, templateCommand, helpContext);
            return(Verifier.Verify(sw.ToString(), _verifySettings.Settings));
        }
Example #16
0
        public void CanShowCommandOptions_NoOptions()
        {
            var           template      = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group").WithTag("type", "MyType");
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand }, helpContext);
            Assert.Equal($"Template options:{Environment.NewLine}   (No options){Environment.NewLine}", sw.ToString());
        }
Example #17
0
 public Question RequestHelp(Channel ch, string question = null)
 {
     if (ch != null)
     {
         using (HelpContext db = new HelpContext())
         {
             bool help = ch.RequestHelp(this);
             if (!help)
             {
                 return(null);
             }
             if (AreUserQuestioning(ch))
             {
                 return(null);
             }
             Question q = new Question(ch, question, this);
             return(q);
         }
     }
     return(null);
 }
Example #18
0
        public void CanShowTemplateOptions_RequiredIsNotShownWhenDefaultValueIsGiven()
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithChoiceParameter("choice", new[] { "val1", "val2" }, description: "my description", defaultValue: "def-val", defaultIfNoOptionValue: "def-val-no-arg", isRequired: true);
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand }, helpContext);
            Assert.DoesNotContain("(REQUIRED)", sw.ToString());
        }
Example #19
0
        public bool SendPasswordRecovery(string email)
        {
            using (HelpContext db = new HelpContext())
            {
                User user =
                    db.Users.SingleOrDefault(
                        u => u.EmailAddress.Equals(email, StringComparison.InvariantCultureIgnoreCase));
                if (user == null)
                {
                    return(false);
                }

                string resetKey = user.GenerateResetKey();
                db.SaveChanges();

                string resetLink = "https://" + HttpContext.Current.Request.Url.Host +
                                   (HttpContext.Current.Request.Url.Port != 430
                                       ? ":" + HttpContext.Current.Request.Url.Port
                                       : "") + "/Account/ResetPassword2?key=" + resetKey + "&email=" + HttpUtility.UrlEncode(email);
                SendGridMessage message = new SendGridMessage
                {
                    From    = new MailAddress("*****@*****.**", "NoReply"),
                    Subject = "Nulstilling af kodeord",
                    Html    =
                        "<p>Du har anmodet om at få nulstillet dit kodeord.</p><p>Brug denne nøgle for at nulstille dit kodeord. </p>" +
                        "<pre>" + resetKey + "</pre>" +
                        "<p>Eller gå til <a href=\"" + resetLink + "\">" + resetLink + "</a>" +
                        "<p>Du har til " + user.ResetExpiresAt.ToUniversalTime() + " UTC til at nulstille dit kodeord.</p>" +
                        "<p>Har du ikke anmodet om at få dit kodeord nulstillet kan du se bort fra denne mail."
                };

                message.AddTo(email);

                Web transportWeb = new Web(key);
                transportWeb.DeliverAsync(message);
            }

            return(true);
        }
Example #20
0
        public Task CanShowTemplateOptions_SingleTemplate_Choice_ShortenedUsage()
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithChoiceParameter("choice", new[] { "val1", "val2", "val3", "val4", "val5", "val6" }, description: "my description", defaultValue: "def-val", defaultIfNoOptionValue: "def-val-no-arg");
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance, maxWidth: 50), myCommand, sw);

            InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand }, helpContext);
            return(Verifier.Verify(sw.ToString(), _verifySettings.Settings));
        }
Example #21
0
File: Parser.cs Project: nohwnd/sdk
        private static CommandLineBuilder UseParseErrorReporting(this CommandLineBuilder builder, string commandName)
        {
            builder.AddMiddleware(async(context, next) =>
            {
                CommandResult currentCommandResult = context.ParseResult.CommandResult;
                while (currentCommandResult != null && currentCommandResult.Command.Name != commandName)
                {
                    currentCommandResult = currentCommandResult.Parent as CommandResult;
                }

                if (currentCommandResult == null || !context.ParseResult.Errors.Any())
                {
                    //different command was launched or no errors
                    await next(context).ConfigureAwait(false);
                }
                else
                {
                    context.ExitCode = 127; //parse error
                    //TODO: discuss to make coloring extensions public
                    //context.Console.ResetTerminalForegroundColor();
                    //context.Console.SetTerminalForegroundRed();
                    foreach (var error in context.ParseResult.Errors)
                    {
                        context.Console.Error.WriteLine(error.Message);
                    }
                    context.Console.Error.WriteLine();
                    //context.Console.ResetTerminalForegroundColor();
                    var output      = context.Console.Out.CreateTextWriter();
                    var helpContext = new HelpContext(context.HelpBuilder,
                                                      context.ParseResult.CommandResult.Command,
                                                      output,
                                                      context.ParseResult);
                    context.HelpBuilder
                    .Write(helpContext);
                }
            }, MiddlewareOrder.ErrorReporting);
            return(builder);
        }
Example #22
0
        private static IEnumerable <string> GetCustomUsageParts(
            HelpContext context,
            Command command,
            bool showSubcommands = true,
            bool showArguments   = true,
            bool showOptions     = true)
        {
            List <Command> parentCommands = new List <Command>();
            Command?       nextCommand    = command;

            while (nextCommand is not null)
            {
                parentCommands.Add(nextCommand);
                nextCommand = nextCommand.Parents.FirstOrDefault(c => c is Command) as Command;
            }
            parentCommands.Reverse();

            foreach (Command parentCommand in parentCommands)
            {
                yield return(parentCommand.Name);
            }
            if (showArguments)
            {
                yield return(CommandLineUtils.FormatArgumentUsage(command.Arguments.ToArray()));
            }

            if (showSubcommands)
            {
                yield return(context.HelpBuilder.LocalizationResources.HelpUsageCommand());
            }

            if (showOptions)
            {
                yield return(context.HelpBuilder.LocalizationResources.HelpUsageOptions());
            }
        }
Example #23
0
 static void ShowHelp(HelpContext context = HelpContext.Usage)
 {
     switch (context)
     {
         case HelpContext.Usage:
             Console.WriteLine("Usage: srtDownload.exe [options...] <directory>");
             Console.WriteLine("Options:");
             Console.WriteLine(" -v, --verbose     Shows more information, otherwise nothing is output (cron");
             Console.WriteLine("                   mode)");
             Console.WriteLine(" -s, --state       Path of state file (remembers when files were scanned)");
             Console.WriteLine(" -g, --giveupdays  The number of days after which the program gives up getting");
             Console.WriteLine("                   the subtitle and writes a .nosrt file.");
             Console.WriteLine(" -l, --language    The subtitle language requested (defaults to \"eng\").");
             Console.WriteLine(" -d, --downloaders Comma-separated list of downloaders to use.");
             Console.WriteLine(" -i, --ignore      Path of file containing ignored shows.");
             Console.WriteLine("                   A text file with a show name on each line. The name is the");
             Console.WriteLine("                   part of the the filename up to the season/episode id.");
             Console.WriteLine("                   E.g. \"Criminal.Minds.S08E07.HDTV.x264-LOL.mp4\" will be ");
             Console.WriteLine("                   ignored with a line of \"Criminal Minds\" in the file.");
             Console.WriteLine(" -h, --help        [|downloaders|languages] Show Help.");
             break;
         case HelpContext.Downloaders:
             Console.WriteLine("The following subtitle downloaders are available:");
             foreach (string dl in SubtitleDownloaderFactory.GetSubtitleDownloaderNames())
                 Console.WriteLine(dl);
             break;
         case HelpContext.Languages:
             Console.WriteLine("The following languages are possible:");
             Console.WriteLine("alb Albanian    fre French      nor Norwegian");
             Console.WriteLine("ara Arabic      ger German      per Persian");
             Console.WriteLine("bel Belarusian  gre Greek       pol Polish");
             Console.WriteLine("bos Bosnian     heb Hebrew      por Portuguese");
             Console.WriteLine("bul Bulgarian   hin Hindi       rum Romanian");
             Console.WriteLine("cat Catalan     hun Hungarian   rus Russian");
             Console.WriteLine("chi Chinese     ice Icelandic   srp Serbian");
             Console.WriteLine("hrv Croatian    ind Indonesian  slo Slovak");
             Console.WriteLine("cze Czech       gle Irish       slv Slovenian");
             Console.WriteLine("dan Danish      ita Italian     spa Spanish");
             Console.WriteLine("nld Dutch       jpn Japanese    swe Swedish");
             Console.WriteLine("dut Dutch       kor Korean      tha Thai");
             Console.WriteLine("eng English     lav Latvian     tur Turkish");
             Console.WriteLine("est Estonian    lit Lithuanian  ukr Ukrainian");
             Console.WriteLine("fin Finnish     mac Macedonian  vie Vietnamese");
             break;
     }
 }
Example #24
0
 private static void CustomUsageSection(HelpContext context, Command command)
 {
     context.Output.WriteLine(context.HelpBuilder.LocalizationResources.HelpUsageTitle());
     context.Output.WriteLine(Indent + string.Join(" ", GetCustomUsageParts(context, command, showSubcommands: false)));
     context.Output.WriteLine(Indent + string.Join(" ", GetCustomUsageParts(context, command, showArguments: false)));
 }
Example #25
0
	private ExprContext expr(int _p) {
		ParserRuleContext _parentctx = Context;
		int _parentState = State;
		ExprContext _localctx = new ExprContext(Context, _parentState);
		ExprContext _prevctx = _localctx;
		int _startState = 4;
		EnterRecursionRule(_localctx, 4, RULE_expr, _p);
		int _la;
		try {
			int _alt;
			EnterOuterAlt(_localctx, 1);
			{
			State = 129;
			switch ( Interpreter.AdaptivePredict(TokenStream,12,Context) ) {
			case 1:
				{
				_localctx = new SignContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;

				State = 35;
				_la = TokenStream.La(1);
				if ( !(_la==T__14 || _la==T__15) ) {
				ErrorHandler.RecoverInline(this);
				}
				else {
				    Consume();
				}
				State = 36; expr(35);
				}
				break;
			case 2:
				{
				_localctx = new NegationContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 37; Match(T__25);
				State = 38; expr(29);
				}
				break;
			case 3:
				{
				_localctx = new FormulaeContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 39; Match(T__30);
				State = 40; expr(26);
				}
				break;
			case 4:
				{
				_localctx = new FunctionContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 41; Match(T__34);
				State = 42; Match(T__7);
				State = 44;
				_la = TokenStream.La(1);
				if (_la==T__53 || _la==ID) {
					{
					State = 43; formlist();
					}
				}

				State = 46; Match(T__8);
				State = 47; expr(23);
				}
				break;
			case 5:
				{
				_localctx = new RepeatStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 48; Match(T__42);
				State = 52;
				ErrorHandler.Sync(this);
				_la = TokenStream.La(1);
				while (_la==NL) {
					{
					{
					State = 49; Match(NL);
					}
					}
					State = 54;
					ErrorHandler.Sync(this);
					_la = TokenStream.La(1);
				}
				State = 55; expr(17);
				}
				break;
			case 6:
				{
				_localctx = new HelpContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 56; Match(T__43);
				State = 57; expr(16);
				}
				break;
			case 7:
				{
				_localctx = new CompoundContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 58; Match(T__35);
				State = 60;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 59; Match(NL);
					}
				}

				State = 62; exprlist();
				State = 63; Match(T__36);
				}
				break;
			case 8:
				{
				_localctx = new IfStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 65; Match(T__37);
				State = 66; Match(T__7);
				State = 67; expr(0);
				State = 68; Match(T__8);
				State = 70;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 69; Match(NL);
					}
				}

				State = 72; expr(0);
				}
				break;
			case 9:
				{
				_localctx = new IfElseStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 74; Match(T__37);
				State = 75; Match(T__7);
				State = 76; expr(0);
				State = 77; Match(T__8);
				State = 79;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 78; Match(NL);
					}
				}

				State = 81; expr(0);
				State = 83;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 82; Match(NL);
					}
				}

				State = 85; Match(T__38);
				State = 87;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 86; Match(NL);
					}
				}

				State = 89; expr(0);
				}
				break;
			case 10:
				{
				_localctx = new ForEachStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 91; Match(T__39);
				State = 92; Match(T__7);
				State = 93; Match(ID);
				State = 94; Match(T__40);
				State = 95; expr(0);
				State = 96; Match(T__8);
				State = 98;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 97; Match(NL);
					}
				}

				State = 100; expr(0);
				}
				break;
			case 11:
				{
				_localctx = new WhileStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 102; Match(T__41);
				State = 103; Match(T__7);
				State = 104; expr(0);
				State = 105; Match(T__8);
				State = 107;
				_la = TokenStream.La(1);
				if (_la==NL) {
					{
					State = 106; Match(NL);
					}
				}

				State = 109; expr(0);
				}
				break;
			case 12:
				{
				_localctx = new NextStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 111; Match(T__44);
				}
				break;
			case 13:
				{
				_localctx = new BreakStatementContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 112; Match(T__45);
				}
				break;
			case 14:
				{
				_localctx = new ParenthesizedContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 113; Match(T__7);
				State = 114; expr(0);
				State = 115; Match(T__8);
				}
				break;
			case 15:
				{
				_localctx = new IdentifierContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 117; Match(ID);
				}
				break;
			case 16:
				{
				_localctx = new StringLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 118; Match(STRING);
				}
				break;
			case 17:
				{
				_localctx = new HexLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 119; Match(HEX);
				}
				break;
			case 18:
				{
				_localctx = new IntLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 120; Match(INT);
				}
				break;
			case 19:
				{
				_localctx = new FloatLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 121; Match(FLOAT);
				}
				break;
			case 20:
				{
				_localctx = new ComplexLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 122; Match(COMPLEX);
				}
				break;
			case 21:
				{
				_localctx = new NullLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 123; Match(T__46);
				}
				break;
			case 22:
				{
				_localctx = new NAContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 124; Match(T__47);
				}
				break;
			case 23:
				{
				_localctx = new InfLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 125; Match(T__48);
				}
				break;
			case 24:
				{
				_localctx = new NanLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 126; Match(T__49);
				}
				break;
			case 25:
				{
				_localctx = new TrueLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 127; Match(T__50);
				}
				break;
			case 26:
				{
				_localctx = new FalseLiteralContext(_localctx);
				Context = _localctx;
				_prevctx = _localctx;
				State = 128; Match(T__51);
				}
				break;
			}
			Context.Stop = TokenStream.Lt(-1);
			State = 185;
			ErrorHandler.Sync(this);
			_alt = Interpreter.AdaptivePredict(TokenStream,14,Context);
			while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.InvalidAltNumber ) {
				if ( _alt==1 ) {
					if ( ParseListeners!=null )
						TriggerExitRuleEvent();
					_prevctx = _localctx;
					{
					State = 183;
					switch ( Interpreter.AdaptivePredict(TokenStream,13,Context) ) {
					case 1:
						{
						_localctx = new NamespaceContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 131;
						if (!(Precpred(Context, 38))) throw new FailedPredicateException(this, "Precpred(Context, 38)");
						State = 132;
						_la = TokenStream.La(1);
						if ( !(_la==T__9 || _la==T__10) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 133; expr(39);
						}
						break;
					case 2:
						{
						_localctx = new MemberAccessContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 134;
						if (!(Precpred(Context, 37))) throw new FailedPredicateException(this, "Precpred(Context, 37)");
						State = 135;
						_la = TokenStream.La(1);
						if ( !(_la==T__11 || _la==T__12) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 136; expr(38);
						}
						break;
					case 3:
						{
						_localctx = new PowerContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 137;
						if (!(Precpred(Context, 36))) throw new FailedPredicateException(this, "Precpred(Context, 36)");
						State = 138; Match(T__13);
						State = 139; expr(37);
						}
						break;
					case 4:
						{
						_localctx = new SequenceContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 140;
						if (!(Precpred(Context, 34))) throw new FailedPredicateException(this, "Precpred(Context, 34)");
						State = 141; Match(T__16);
						State = 142; expr(35);
						}
						break;
					case 5:
						{
						_localctx = new UserOpContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 143;
						if (!(Precpred(Context, 33))) throw new FailedPredicateException(this, "Precpred(Context, 33)");
						State = 144; Match(USER_OP);
						State = 145; expr(34);
						}
						break;
					case 6:
						{
						_localctx = new MultiplicationContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 146;
						if (!(Precpred(Context, 32))) throw new FailedPredicateException(this, "Precpred(Context, 32)");
						State = 147;
						_la = TokenStream.La(1);
						if ( !(_la==T__17 || _la==T__18) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 148; expr(33);
						}
						break;
					case 7:
						{
						_localctx = new AdditionContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 149;
						if (!(Precpred(Context, 31))) throw new FailedPredicateException(this, "Precpred(Context, 31)");
						State = 150;
						_la = TokenStream.La(1);
						if ( !(_la==T__14 || _la==T__15) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 151; expr(32);
						}
						break;
					case 8:
						{
						_localctx = new ComparisonContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 152;
						if (!(Precpred(Context, 30))) throw new FailedPredicateException(this, "Precpred(Context, 30)");
						State = 153;
						_la = TokenStream.La(1);
						if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24))) != 0)) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 154; expr(31);
						}
						break;
					case 9:
						{
						_localctx = new LogicalAndContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 155;
						if (!(Precpred(Context, 28))) throw new FailedPredicateException(this, "Precpred(Context, 28)");
						State = 156;
						_la = TokenStream.La(1);
						if ( !(_la==T__26 || _la==T__27) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 157; expr(29);
						}
						break;
					case 10:
						{
						_localctx = new LogicalOrContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 158;
						if (!(Precpred(Context, 27))) throw new FailedPredicateException(this, "Precpred(Context, 27)");
						State = 159;
						_la = TokenStream.La(1);
						if ( !(_la==T__28 || _la==T__29) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 160; expr(28);
						}
						break;
					case 11:
						{
						_localctx = new FormulaeContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 161;
						if (!(Precpred(Context, 25))) throw new FailedPredicateException(this, "Precpred(Context, 25)");
						State = 162; Match(T__30);
						State = 163; expr(26);
						}
						break;
					case 12:
						{
						_localctx = new RightAssignmentContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 164;
						if (!(Precpred(Context, 24))) throw new FailedPredicateException(this, "Precpred(Context, 24)");
						State = 165;
						_la = TokenStream.La(1);
						if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__31) | (1L << T__32) | (1L << T__33))) != 0)) ) {
						ErrorHandler.RecoverInline(this);
						}
						else {
						    Consume();
						}
						State = 166; expr(25);
						}
						break;
					case 13:
						{
						_localctx = new ListAccessContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 167;
						if (!(Precpred(Context, 41))) throw new FailedPredicateException(this, "Precpred(Context, 41)");
						State = 168; Match(T__4);
						State = 169; sublist();
						State = 170; Match(T__5);
						State = 171; Match(T__5);
						}
						break;
					case 14:
						{
						_localctx = new IndexContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 173;
						if (!(Precpred(Context, 40))) throw new FailedPredicateException(this, "Precpred(Context, 40)");
						State = 174; Match(T__6);
						State = 175; sublist();
						State = 176; Match(T__5);
						}
						break;
					case 15:
						{
						_localctx = new FunctionCallContext(new ExprContext(_parentctx, _parentState));
						PushNewRecursionContext(_localctx, _startState, RULE_expr);
						State = 178;
						if (!(Precpred(Context, 39))) throw new FailedPredicateException(this, "Precpred(Context, 39)");
						State = 179; Match(T__7);
						State = 180; sublist();
						State = 181; Match(T__8);
						}
						break;
					}
					} 
				}
				State = 187;
				ErrorHandler.Sync(this);
				_alt = Interpreter.AdaptivePredict(TokenStream,14,Context);
			}
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			UnrollRecursionContexts(_parentctx);
		}
		return _localctx;
	}
Example #26
0
        /// <summary>
        /// Ensure <paramref name="templates"/> are sorted in priority order
        /// The highest priority should come first.
        /// </summary>
        private static IEnumerable <TemplateOption> CollectOptionsToShow(IEnumerable <TemplateCommand> templates, HelpContext context)
        {
            Dictionary <string, (CliTemplateParameter Parameter, IReadOnlyList <string> Aliases)> parametersToShow = new();

            //templates are in priority order
            //in case parameters are different in different templates
            //highest priority ones wins
            //except the choice parameter, where we merge possible values
            foreach (TemplateCommand command in templates)
            {
                foreach (CliTemplateParameter currentParam in command.Template.CliParameters.Values)
                {
                    if (currentParam.IsHidden && !currentParam.AlwaysShow)
                    {
                        continue;
                    }

                    if (parametersToShow.TryGetValue(currentParam.Name, out var existingParam))
                    {
                        if (currentParam is ChoiceTemplateParameter currentChoiceParam &&
                            existingParam.Parameter is ChoiceTemplateParameter existingChoiceParam)
                        {
                            if (existingChoiceParam is CombinedChoiceTemplateParameter combinedParam)
                            {
                                combinedParam.MergeChoices(currentChoiceParam);
                            }
                            else
                            {
                                var combinedChoice = new CombinedChoiceTemplateParameter(existingChoiceParam);
                                combinedChoice.MergeChoices(currentChoiceParam);
                                parametersToShow[currentParam.Name] = (combinedChoice, existingParam.Aliases);
                            }
                        }
                    }
                    else
                    {
                        var aliases = command.TemplateOptions[currentParam.Name].Aliases.OrderByDescending(s => s, StringComparer.OrdinalIgnoreCase).ToArray();
                        parametersToShow[currentParam.Name] = (currentParam, aliases);
                    }
                }
            }

            var optionsToShow = parametersToShow.Values.Select(p => new TemplateOption(p.Parameter, p.Aliases)).ToList();

            foreach (var option in optionsToShow)
            {
                context.HelpBuilder.CustomizeSymbol(
                    option.Option,
                    firstColumnText: option.TemplateParameter.GetCustomFirstColumnText(option),
                    secondColumnText: option.TemplateParameter.GetCustomSecondColumnText());
            }
            return(optionsToShow);
        }
Example #27
0
        internal static void ShowUsage(Command?command, IReadOnlyList <string> shortNames, HelpContext context)
        {
            List <string> usageParts = new List <string>();

            while (command is not null)
            {
                if (!string.IsNullOrWhiteSpace(command.Name))
                {
                    usageParts.Add(command.Name);
                }
                command = command.Parents.FirstOrDefault(c => c is Command) as Command;
            }

            usageParts.Reverse();
            context.Output.WriteLine(context.HelpBuilder.LocalizationResources.HelpUsageTitle());
            foreach (string shortName in shortNames)
            {
                var parts = usageParts.Concat(
                    new[]
                {
                    shortName,
                    context.HelpBuilder.LocalizationResources.HelpUsageOptions(),
                    HelpStrings.Text_UsageTemplateOptionsPart
                });
                context.Output.WriteLine(Indent + string.Join(" ", parts));
            }
            context.Output.WriteLine();
        }
Example #28
0
        public static void WriteHelp(HelpContext context, InstantiateCommandArgs instantiateCommandArgs, IEngineEnvironmentSettings environmentSettings)
        {
            if (string.IsNullOrWhiteSpace(instantiateCommandArgs.ShortName))
            {
                WriteCustomInstantiateHelp(context, instantiateCommandArgs.Command);
                return;
            }

            using TemplatePackageManager templatePackageManager = new TemplatePackageManager(environmentSettings);
            HostSpecificDataLoader hostSpecificDataLoader = new HostSpecificDataLoader(environmentSettings);

            //TODO: consider use cache only for help
            var selectedTemplateGroups = Task.Run(
                async() => await GetMatchingTemplateGroupsAsync(
                    instantiateCommandArgs,
                    templatePackageManager,
                    hostSpecificDataLoader,
                    default).ConfigureAwait(false))
                                         .GetAwaiter()
                                         .GetResult();

            if (!selectedTemplateGroups.Any())
            {
                //help do not return error exit code, so we write error to StdOut instead
                HandleNoMatchingTemplateGroup(instantiateCommandArgs, Reporter.Output);
                return;
            }
            if (selectedTemplateGroups.Take(2).Count() > 1)
            {
                HandleAmbiguousTemplateGroup(environmentSettings, templatePackageManager, selectedTemplateGroups, Reporter.Output);
                return;
            }

            TemplateGroup templateGroup = selectedTemplateGroups.Single();
            IEnumerable <TemplateCommand> matchingTemplates =
                GetMatchingTemplates(
                    instantiateCommandArgs,
                    environmentSettings,
                    templatePackageManager,
                    templateGroup);

            if (!matchingTemplates.Any())
            {
                //output is handled in HandleNoTemplateFoundResult
                HandleNoTemplateFoundResult(instantiateCommandArgs, environmentSettings, templatePackageManager, templateGroup, Reporter.Output);
                return;
            }

            if (!VerifyMatchingTemplates(
                    environmentSettings,
                    matchingTemplates,
                    Reporter.Output,
                    out IEnumerable <TemplateCommand>?templatesToShow))
            {
                //error
                //output is handled in VerifyMatchingTemplates
                return;
            }

            var preferredTemplate = templatesToShow.OrderByDescending(x => x.Template.Precedence).First();

            ShowTemplateDetailHeaders(preferredTemplate.Template, context.Output);
            //we need to show all possible short names (not just the one specified)
            ShowUsage(instantiateCommandArgs.Command, templateGroup.ShortNames, context);
            ShowCommandOptions(templatesToShow, preferredTemplate, context);
            ShowTemplateSpecificOptions(templatesToShow, context);
            ShowHintForOtherTemplates(templateGroup, preferredTemplate.Template, instantiateCommandArgs, context.Output);
        }
Example #29
0
    private static void DoWork(string f, string r, string d, string csv, string dt, bool debug, bool trace)
    {
        var levelSwitch = new LoggingLevelSwitch();

        var template = "{Message:lj}{NewLine}{Exception}";

        if (debug)
        {
            levelSwitch.MinimumLevel = LogEventLevel.Debug;
            template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
        }

        if (trace)
        {
            levelSwitch.MinimumLevel = LogEventLevel.Verbose;
            template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
        }

        var conf = new LoggerConfiguration()
                   .WriteTo.Console(outputTemplate: template)
                   .MinimumLevel.ControlledBy(levelSwitch);

        Log.Logger = conf.CreateLogger();

        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Console.WriteLine();
            Log.Fatal("Non-Windows platforms not supported due to the need to load ESI specific Windows libraries! Exiting...");
            Console.WriteLine();
            Environment.Exit(0);
            return;
        }

        if (f.IsNullOrEmpty() && d.IsNullOrEmpty())
        {
            var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);

            var hc = new HelpContext(helpBld, _rootCommand, Console.Out);

            helpBld.Write(hc);

            Log.Warning("Either -f or -d is required. Exiting\r\n");
            return;
        }


        if (f.IsNullOrEmpty() == false && !File.Exists(f))
        {
            Log.Warning("File '{File}' not found. Exiting", f);
            return;
        }

        if (d.IsNullOrEmpty() == false && !Directory.Exists(d))
        {
            Log.Warning("Directory '{D}' not found. Exiting", d);
            return;
        }

        if (csv.IsNullOrEmpty())
        {
            var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);

            var hc = new HelpContext(helpBld, _rootCommand, Console.Out);

            helpBld.Write(hc);

            Log.Warning("--csv is required. Exiting\r\n");
            return;
        }

        Log.Information("{Header}", Header);
        Console.WriteLine();
        Log.Information("Command line: {Args}\r\n", string.Join(" ", _args));

        if (IsAdministrator() == false)
        {
            Log.Warning("Warning: Administrator privileges not found!\r\n");
        }

        var sw = new Stopwatch();

        sw.Start();

        var ts = DateTimeOffset.UtcNow;

        Srum sr = null;

        if (d.IsNullOrEmpty() == false)
        {
            IEnumerable <string> files2;

#if NET6_0
            var enumerationOptions = new EnumerationOptions
            {
                IgnoreInaccessible    = true,
                MatchCasing           = MatchCasing.CaseInsensitive,
                RecurseSubdirectories = true,
                AttributesToSkip      = 0
            };

            files2 =
                Directory.EnumerateFileSystemEntries(d, "SRUDB.DAT", enumerationOptions);

            f = files2.FirstOrDefault();

            if (f.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SRUDB.dat'! Exiting");
                return;
            }

            Log.Information("Found SRUM database file '{F}'!", f);

            files2 =
                Directory.EnumerateFileSystemEntries(d, "SOFTWARE", enumerationOptions);

            r = files2.FirstOrDefault();

            if (r.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SOFTWARE'! Registry data will not be extracted");
            }
            else
            {
                Log.Information("Found SOFTWARE hive '{R}'!", r);
            }
            #elif NET462
            //kape mode, so find the files
            var ilter = new DirectoryEnumerationFilters();
            ilter.InclusionFilter = fsei =>
            {
                if (fsei.FileSize == 0)
                {
                    return(false);
                }

                if (fsei.FileName.ToUpperInvariant() == "SRUDB.DAT")
                {
                    return(true);
                }

                return(false);
            };

            ilter.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

            ilter.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

            const DirectoryEnumerationOptions dirEnumOptions =
                DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
                DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
                DirectoryEnumerationOptions.BasicSearch;

            files2 =
                Directory.EnumerateFileSystemEntries(d, dirEnumOptions, ilter);

            f = files2.FirstOrDefault();

            if (f.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SRUDB.dat'! Exiting");
                return;
            }

            Log.Information("Found SRUM database file '{F}'!", f);

            ilter = new DirectoryEnumerationFilters();
            ilter.InclusionFilter = fsei =>
            {
                if (fsei.FileSize == 0)
                {
                    return(false);
                }

                if (fsei.FileName.ToUpperInvariant() == "SOFTWARE")
                {
                    return(true);
                }

                return(false);
            };

            ilter.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

            ilter.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

            files2 =
                Directory.EnumerateFileSystemEntries(d, dirEnumOptions, ilter);


            r = files2.FirstOrDefault();

            if (r.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SOFTWARE'! Registry data will not be extracted");
            }
            else
            {
                Log.Information("Found SOFTWARE hive '{R}'!", r);
            }
#endif



            Console.WriteLine();
        }

        try
        {
            Log.Information("Processing '{F}'...", f);
            sr = new Srum(f, r);

            Console.WriteLine();
            Log.Information("Processing complete!");
            Console.WriteLine();

            Log.Information("{EnergyUse} {EnergyUsagesCount:N0}", "Energy Usage count:".PadRight(30),
                            sr.EnergyUsages.Count);
            Log.Information("{Unknown312s} {Unknown312sCount:N0}", "Unknown 312 count:".PadRight(30),
                            sr.TimelineProviders.Count);
            Log.Information("{UnknownD8Fs} {UnknownD8FsCount:N0}", "Unknown D8F count:".PadRight(30),
                            sr.Vfuprovs.Count);
            Log.Information("{AppResourceUseInfos} {AppResourceUseInfosCount:N0}",
                            "App Resource Usage count:".PadRight(30), sr.AppResourceUseInfos.Count);
            Log.Information("{NetworkConnections} {NetworkConnectionsCount:N0}",
                            "Network Connection count:".PadRight(30), sr.NetworkConnections.Count);
            Log.Information("{NetworkUsages} {NetworkUsagesCount}", "Network Usage count:".PadRight(30),
                            sr.NetworkUsages.Count);
            Log.Information("{PushNotifications} {PushNotificationsCount:N0}", "Push Notification count:".PadRight(30),
                            sr.PushNotifications.Count);
            Console.WriteLine();
        }
        catch (Exception e)
        {
            Log.Error(e,
                      "Error processing file! Message: {Message}.\r\n\r\nThis almost always means the database is dirty and must be repaired. This can be verified by running 'esentutl.exe /mh SRUDB.dat' and examining the 'State' property",
                      e.Message);
            Console.WriteLine();
            Log.Information(
                "If the database is dirty, **make a copy of your files**, ensure all files in the directory are not Read-only, open a PowerShell session as an admin, and repair by using the following commands (change directories to the location of SRUDB.dat first):\r\n\r\n'esentutl.exe /r sru /i'\r\n'esentutl.exe /p SRUDB.dat'\r\n\r\n");
            Environment.Exit(0);
        }

        if (csv.IsNullOrEmpty() == false)
        {
            if (Directory.Exists(csv) == false)
            {
                Log.Information(
                    "Path to '{Csv}' doesn't exist. Creating...", csv);

                try
                {
                    Directory.CreateDirectory(csv);
                }
                catch (Exception)
                {
                    Log.Fatal(
                        "Unable to create directory '{Csv}'. Does a file with the same name exist? Exiting", csv);
                    return;
                }
            }


            string outName;

            string outFile;

            Log.Information("CSV output will be saved to '{Csv}'\r\n", csv);

            StreamWriter swCsv;
            CsvWriter    csvWriter;
            try
            {
                Log.Debug("Dumping Energy Usage tables '{TableName}'", EnergyUsage.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_EnergyUsage_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <EnergyUsage>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EventTimestamp).Convert(t =>
                                                       $"{t.Value.EventTimestamp?.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <EnergyUsage>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.EnergyUsages.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'EnergyUsage' data! Error: {Message}", e.Message);
            }


            try
            {
                Log.Debug("Dumping Unknown 312 table '{TableName}'", TimelineProvider.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_Unknown312_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <TimelineProvider>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EndTime).Convert(t =>
                                                $"{t.Value.EndTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <TimelineProvider>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.TimelineProviders.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'Unknown312' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Unknown D8F table '{TableName}'", Vfuprov.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_UnknownD8F_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <Vfuprov>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EndTime).Convert(t =>
                                                $"{t.Value.EndTime.ToString(dt)}");
                foo.Map(t => t.StartTime).Convert(t =>
                                                  $"{t.Value.StartTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <Vfuprov>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.Vfuprovs.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'UnknownD8F' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping App Resource Use Info table '{TableName}'", AppResourceUseInfo.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_AppResourceUseInfo_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <AppResourceUseInfo>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <AppResourceUseInfo>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.AppResourceUseInfos.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'AppResourceUseInfo' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Network Connection table '{TableName}'", NetworkConnection.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkConnections_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <NetworkConnection>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.ConnectStartTime).Convert(t =>
                                                         $"{t.Value.ConnectStartTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <NetworkConnection>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.NetworkConnections.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'NetworkConnection' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Network Usage table '{TableName}'", NetworkUsage.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkUsages_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <NetworkUsage>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <NetworkUsage>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.NetworkUsages.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'NetworkUsage' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Push Notification table '{TableName}'", PushNotification.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_PushNotifications_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <PushNotification>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <PushNotification>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.PushNotifications.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'PushNotification' data! Error: {Message}", e.Message);
            }

            sw.Stop();

            Log.Information("Processing completed in {TotalSeconds:N4} seconds\r\n", sw.Elapsed.TotalSeconds);
        }
    }
Example #30
0
        public override bool AddHelpContext(string contextName, string pathToContextFile)
        {
            if (_contextToDictionary.ContainsKey(contextName))
            return false;

              try
              {
            bool bExists = System.IO.File.Exists(pathToContextFile);
            if (bExists == false)
            {
              Log.Error("The CSV file '{0}' does not exist and thus cannot be added as a help context!", pathToContextFile);
              return false;
            }

            HelpContext hc = new HelpContext(pathToContextFile, this);
            if (!hc.Reload())
              return false;

            _contextToDictionary.Add(contextName, hc);
              }
              catch
              {
            return false;
              }

              return true;
        }
Example #31
0
 public AuthController(HelpContext context)
 {
     _context = context;
 }
Example #32
0
 public StudentAssignmentModelsController(HelpContext context)
 {
     _context = context;
 }
Example #33
0
 public TestController(HelpContext context)
 {
     _context = context;
 }