Esempio n. 1
0
        public void Execute(ICommandDefinition command)
        {
            var     handlerType = typeof(ICommandHandler <>).MakeGenericType(command.GetType());
            dynamic handler     = _lifeTimeScope.Resolve(handlerType);

            handler.Handle((dynamic)command);
        }
Esempio n. 2
0
        static IList <IOptionDefinition> ResolveFlagOptionLabels(
            ICommandDefinition selectedCommand,
            string argument)
        {
            if (OptionSymbol.CanBeFullForm(argument))
            {
                return(selectedCommand.GetRegisteredOptions()
                       .Where(o => o.Type == OptionType.Flag && o.IsMatch(argument))
                       .ToArray());
            }

            if (OptionSymbol.CanBeAbbreviationForm(argument))
            {
                string[] flagArguments = SplitAbbrArgument(argument);
                if (flagArguments.HasDuplication(StringComparer.OrdinalIgnoreCase))
                {
                    throw new ArgParsingException(ArgsParsingErrorCode.DuplicateFlagsInArgs, argument);
                }

                IOptionDefinition[] resolvedDefinitions = selectedCommand.GetRegisteredOptions()
                                                          .Where(o => o.Type == OptionType.Flag && flagArguments.Any(o.IsMatch))
                                                          .ToArray();

                return(resolvedDefinitions.Length != flagArguments.Length
                    ? Array.Empty <IOptionDefinition>()
                    : resolvedDefinitions);
            }

            return(Array.Empty <IOptionDefinition>());
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="definition"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static List <T> ToList <T>(this ICommandDefinition definition, T parameter = null)
            where T : class, new()
        {
            List <T> ret = new List <T>();

            using (var connection = new SqlConnection(definition.ConnectionString)) {
                using (var command = definition.GetCommand()) {
                    command.Connection = connection;
                    connection.Open();
                    try {
                        ParameterMethods.SetInputs(parameter, command);
                        executeReaderAndFillList(command, ret);
                        ParameterMethods.SetOutputs(parameter, command);
                    }
                    catch (SqlException sqlEx) when(sqlEx.ShouldTryReexecute())
                    {
                        if (command.IsCommandBuilt())
                        {
                            ret = definition.ToList(parameter);
                        }
                        else
                        {
                            throw sqlEx;
                        }
                    }
                    catch {
                        throw;
                    }
                }
            }
            return(ret);
        }
Esempio n. 4
0
        /// <summary>
        /// the command should have the connections string set,  doesnt have to be open but
        /// the string should be set. IBattleAxe assumes that the object is controlling
        /// all the value setting through the Indexer.
        /// beware this has no error trapping so make sure to trap your errors
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objs"></param>
        /// <param name="where"></param>
        /// <param name="definition"></param>
        public static void Update <T>(this List <T> objs, Func <T, bool> where, ICommandDefinition definition)
            where T : class
        {
            var updates = objs.Where(where).ToList();

            definition.Update(objs);
        }
Esempio n. 5
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="definition"></param>
 /// <param name="parameter"></param>
 /// <returns></returns>
 public static T Execute <T>(this ICommandDefinition definition, T parameter = null)
     where T : class
 {
     using (var connection = new SqlConnection(definition.ConnectionString)) {
         using (var command = definition.GetCommand()) {
             command.Connection = connection;
             connection.Open();
             try {
                 ParameterMethods.SetInputs(parameter, command);
                 command.ExecuteNonQuery();
                 ParameterMethods.SetOutputs(parameter, command);
             }
             catch (SqlException sqlEx) when(sqlEx.ShouldTryReexecute())
             {
                 if (command.IsCommandBuilt())
                 {
                     parameter = definition.Execute(parameter);
                 }
                 else
                 {
                     throw sqlEx;
                 }
             }
             catch {
                 throw;
             }
         }
     }
     return(parameter);
 }
Esempio n. 6
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="definition"></param>
 /// <param name="objs"></param>
 /// <returns></returns>
 public static List <T> Update <T>(this ICommandDefinition definition, List <T> objs)
     where T : class
 {
     using (var connection = new SqlConnection(definition.ConnectionString)) {
         using (var command = definition.GetCommand()) {
             command.Connection = connection;
             connection.Open();
             try {
                 foreach (var obj in objs)
                 {
                     ParameterMethods.SetInputs(obj, command);
                     command.ExecuteNonQuery();
                     ParameterMethods.SetOutputs(obj, command);
                 }
             }
             catch (SqlException sqlEx) when(sqlEx.ShouldTryReexecute())
             {
                 if (command.IsCommandBuilt())
                 {
                     objs = definition.Update(objs);
                 }
                 else
                 {
                     throw sqlEx;
                 }
             }
             catch {
                 throw;
             }
         }
     }
     return(objs);
 }
Esempio n. 7
0
 internal KonsoleApplication(IServiceCollection serviceDescriptors, IConfigurationRoot configuration, ICommandDefinition rootCommand)
 {
     _serviceDescriptors = serviceDescriptors;
     Configuration       = configuration;
     ServiceProvider     = serviceDescriptors.BuildServiceProvider();
     _rootCommand        = rootCommand;
 }
        /// <summary>
        /// the command should have the connections string set,  doesnt have to be open but
        /// the string should be set.
        /// </summary>
        /// <typeparam name="R"></typeparam>
        /// <typeparam name="P"></typeparam>
        /// <param name="parameter"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public static R FirstOrDefault <R, P>(this P parameter, ICommandDefinition definition)
            where R : class, new()
            where P : class
        {
            R newObj = null;

            using (var connection = new SqlConnection(definition.ConnectionString)) {
                using (var command = definition.GetCommand()) {
                    command.Connection = connection;
                    connection.Open();
                    try {
                        ParameterMethods.SetInputs(parameter, command);
                        newObj = DataReaderMethods.GetFirst <R>(command);
                        ParameterMethods.SetOutputs(parameter, command);
                    }
                    catch (SqlException sqlEx) when(sqlEx.ShouldTryReexecute())
                    {
                        if (command.IsCommandBuilt())
                        {
                            newObj = parameter.FirstOrDefault <R, P>(definition);
                        }
                        else
                        {
                            throw sqlEx;
                        }
                    }
                    catch {
                        throw;
                    }
                }
            }
            return(newObj);
        }
Esempio n. 9
0
        public async Task ExecuteCommandAsync_When_Always_Then_ExecuteCorrectCommand(
            string argsC,
            bool hasCatchAll,
            string invokedCmd,

            ICommandDefinition catchAllCmd,
            IList <ICommandDefinition> defs,
            IServiceProvider sp)
        {
            // -- arrange
            string executedAction = null;
            var    args           = argsC?.Split(" ");

            catchAllCmd.Name.Returns("catch");
            defs.First().Name.Returns("child");
            var sut = new CompositeCommandDefinition("sut", defs, hasCatchAll ? catchAllCmd : null);

            defs.ToList().ForEach(c => c.WhenForAnyArgs(async a => await a.ExecuteCommandAsync(null, null)).Do(a => executedAction = c.Name));
            catchAllCmd.WhenForAnyArgs(async a => await a.ExecuteCommandAsync(null, null)).Do(a => executedAction = catchAllCmd.Name);


            // -- act
            await sut.ExecuteCommandAsync(sp, args);


            // -- assert
            Assert.Equal(invokedCmd, executedAction);
        }
Esempio n. 10
0
        public ContinueState(ICommandDefinition command, PreParserResultBuilder resultBuilder)
        {
            Debug.Assert(command != null);
            Debug.Assert(resultBuilder != null);

            this.command       = command;
            this.resultBuilder = resultBuilder;
        }
Esempio n. 11
0
 public override bool IsConflict(ICommandDefinition commandDefinition)
 {
     if (!(commandDefinition is CommandDefinition c))
     {
         return(true);
     }
     return(Symbol.Equals(c.Symbol, StringComparison.OrdinalIgnoreCase));
 }
        internal void RegisterCommand(ICommandDefinition command)
        {
            if (Commands.Any(e => e.Symbol == command.Symbol))
            {
                throw new InvalidOperationException("This command already exists.");
            }

            Commands.Add(command);
        }
Esempio n. 13
0
        public void SetCommand(ICommandDefinition commandDefinition)
        {
            Debug.Assert(commandDefinition != null);

            if (command != null)
            {
                throw new InvalidOperationException("The command has been set.");
            }

            command = commandDefinition;
        }
Esempio n. 14
0
        public void RegisterCommand(ICommandDefinition command)
        {
            ICommandDefinition conflict = commands.FirstOrDefault(c => c.IsConflict(command));

            if (conflict != null)
            {
                throw new ArgumentException(
                          $"The command '{command}' conflicts with command '{conflict}'");
            }

            commands.Add(command);
        }
Esempio n. 15
0
        static IOptionDefinition ResolveKeyValueOptionLabel(
            ICommandDefinition selectedCommand,
            string argument)
        {
            if (!OptionSymbol.CanBeFullForm(argument) && !OptionSymbol.CanBeAbbreviationSingleForm(argument))
            {
                return(null);
            }

            return(selectedCommand.GetRegisteredOptions()
                   .FirstOrDefault(o => o.Type == OptionType.KeyValue && o.IsMatch(argument)));
        }
Esempio n. 16
0
 internal ArgsParsingResult(
     ICommandDefinition command,
     IEnumerable <KeyValuePair <IOptionDefinition, IList <string> > > optionValues,
     IEnumerable <KeyValuePair <IOptionDefinition, bool> > optionFlags,
     IList <KeyValuePair <IFreeValueDefinition, string> > freeValues)
 {
     Command           = command ?? throw new ArgumentNullException(nameof(command));
     this.optionValues = TransformHelper.TransformOptionValues(optionValues);
     this.optionFlags  = optionFlags?.ToArray() ?? Array.Empty <KeyValuePair <IOptionDefinition, bool> >();
     this.freeValues   = TransformHelper.TransformFreeValues(freeValues);
     IsSuccess         = true;
 }
Esempio n. 17
0
        protected static IPreParsingState HandleFreeValueArgument(ICommandDefinition selectedCommand,
                                                                  PreParserResultBuilder resultBuilder, string argument)
        {
            if (selectedCommand.AllowFreeValue)
            {
                resultBuilder.AppendFreeValue(argument);
                return(new ContinueFreeValueState(selectedCommand, resultBuilder));
            }

            throw new ArgParsingException(
                      ArgsParsingErrorCode.FreeValueNotSupported,
                      argument);
        }
Esempio n. 18
0
        protected static IPreParsingState HandleKeyValueOptionArgument(
            ICommandDefinition command,
            PreParserResultBuilder resultBuilder,
            string argument)
        {
            IOptionDefinition kvOption = ResolveKeyValueOptionLabel(
                command,
                argument);

            return(kvOption != null
                ? new WaitingValueState(command, kvOption, argument, resultBuilder)
                : null);
        }
Esempio n. 19
0
        public void DefineCommand <TPayload>(string commandName, ICommandDefinition <TStage, TPayload> command)
        {
            var key = commandName ?? string.Empty;
            List <IStageCommandFactory <TStage> > commands;

            if (!_commands.TryGetValue(key, out commands))
            {
                commands       = new List <IStageCommandFactory <TStage> >();
                _commands[key] = commands;
            }

            commands.Add(new StageCommandFactory <TStage, TPayload>(command));
        }
Esempio n. 20
0
        public async Task ExecuteCommandAsync_When_NoArgsAndCatchAll_Then_ThrowInvalidCommand(string argsC)
        {
            // -- arrange
            var args     = argsC?.Split(" ");
            var defs     = new ICommandDefinition[] { };
            var catchAll = (ICommandDefinition)null;
            var sut      = new CompositeCommandDefinition("sut", defs, catchAll);

            // -- act
            Func <Task> action = () => sut.ExecuteCommandAsync(null, args);


            // -- assert
            await Assert.ThrowsAsync <InvalidCommandException>(action);
        }
Esempio n. 21
0
        public WaitingValueState(
            ICommandDefinition command,
            IOptionDefinition kvOption,
            string labelArgument,
            PreParserResultBuilder resultBuilder)
        {
            Debug.Assert(command != null);
            Debug.Assert(kvOption != null);
            Debug.Assert(resultBuilder != null);

            this.command       = command;
            this.kvOption      = kvOption;
            this.labelArgument = labelArgument;
            this.resultBuilder = resultBuilder;
        }
Esempio n. 22
0
        protected static IPreParsingState HandleFlagOptionArgument(
            ICommandDefinition command,
            PreParserResultBuilder resultBuilder,
            string argument)
        {
            IList <IOptionDefinition> flagOptions = ResolveFlagOptionLabels(
                command,
                argument);

            if (flagOptions.Count > 0)
            {
                foreach (IOptionDefinition flagOption in flagOptions)
                {
                    resultBuilder.AppendOptionToken(new OptionToken(flagOption), argument);
                }
                return(new ContinueState(command, resultBuilder));
            }

            return(null);
        }
Esempio n. 23
0
        public override IPreParsingState MoveToNext(string argument)
        {
            if (IsEndOfArguments(argument))
            {
                return(HandleEndOfArgument());
            }

            ICommandDefinition selectedCommand = ResolveCommand(argument);

            if (selectedCommand != null)
            {
                resultBuilder.SetCommand(selectedCommand);
                return(new ContinueState(selectedCommand, resultBuilder));
            }

            selectedCommand = EnsureDefaultCommandSet(argument);

            IPreParsingState nextStateForKeyValueOption = HandleKeyValueOptionArgument(
                selectedCommand,
                resultBuilder,
                argument);

            if (nextStateForKeyValueOption != null)
            {
                return(nextStateForKeyValueOption);
            }

            IPreParsingState nextStateForFlagOption = HandleFlagOptionArgument(selectedCommand, resultBuilder, argument);

            if (nextStateForFlagOption != null)
            {
                return(nextStateForFlagOption);
            }

            return(HandleFreeValueArgument(selectedCommand, resultBuilder, argument));
        }
Esempio n. 24
0
 public StageCommand(TStage stage, ICommandDefinition <TStage, TPayload> commandDefinition)
 {
     _stage             = stage;
     _commandDefinition = commandDefinition;
 }
Esempio n. 25
0
 public ICompositeCommandBuilder DefineCommand(ICommandDefinition commandDefinition)
 {
     _commandDefinitions.Add(commandDefinition);
     return(this);
 }
Esempio n. 26
0
 public ICompositeCommandBuilder DefineCatchAllCommand(ICommandDefinition commandDefinition)
 {
     _catchAll = commandDefinition;
     return(this);
 }
Esempio n. 27
0
 private static string GetOrderedVerbs(ICommandDefinition command)
 {
     return String.Join("|", command.Verbs.OrderBy(_ => _));
 }
Esempio n. 28
0
 void SetCommand()
 {
     command = commands.GetCommand();
 }
 public TValue Query <TValue>(ICommandDefinition <TValue> query)
 {
     return(_dapperHandler.ExecuteScalar <TValue>(query.Command));
 }
 public IEnumerable <TValue> Get <TValue>(ICommandDefinition <TValue> query)
     where TValue : DapperEntity
 {
     return(_dapperHandler.Query <TValue>(query.Command));
 }
Esempio n. 31
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="objs"></param>
 /// <param name="definition"></param>
 /// <returns></returns>
 public static List <T> Update <T>(this List <T> objs, ICommandDefinition definition)
     where T : class => definition.Update(objs);
Esempio n. 32
0
        private void ShowHelp(ICommandDefinition command, OptionSet set)
        {
            WriteUsage(command);

            set.WriteOptionDescriptions(Console.Out);
            Console.WriteLine();

            WriteHelpFooter();
        }
Esempio n. 33
0
        private void WriteHelpSection(ICommandDefinition command)
        {
            ColorWrite(HelpSectionHeaderColor, "  ");
            ColorWrite(HelpSectionHeaderColor, GetOrderedVerbs(command));

            if (command.IsDefault) ColorWrite(HelpSectionHeaderColor, " (default)");
            if (!String.IsNullOrWhiteSpace(command.Description)) ColorWrite(HelpSectionHeaderColor, ": " + command.Description);

            Console.WriteLine();
        }
Esempio n. 34
0
        private void WriteUsage(ICommandDefinition command = null)
        {
            ColorWrite(ConsoleColor.White, "Usage: ");
            ColorWrite(ConsoleColor.White, Path.GetFileName(Assembly.GetEntryAssembly().CodeBase));

            Console.Write(" ");
            ColorWrite(ConsoleColor.Cyan, command == null ? "command" : GetOrderedVerbs(command));

            ColorWrite(ConsoleColor.White, " [options]");
            Console.WriteLine();

            Console.WriteLine();
        }