Example #1
0
        public void BotRun()
        {
            context.Database.EnsureCreated();
            MainProvider provider = new MainProvider();

            client = new TelegramBotClient(Constant.Token);
            CommandProvider commandProvider = new CommandProvider(client, provider);

            client.StartReceiving();

            List <string> commandList = CommandList.GetCommands();
            var           scope       = new ServiceCollection()
                                        .AddScoped <IMessageHandler, MessageHandler>(x => new MessageHandler(client, provider, commandProvider))
                                        .AddScoped <ICallbackHandler, CallBackHandler>(i => new CallBackHandler(client, provider)).BuildServiceProvider();

            client.OnCallbackQuery += async(object sender, CallbackQueryEventArgs args) =>
            {
                var callbackHandler = scope.GetService <ICallbackHandler>();
                await callbackHandler.BaseCallBackHandler(args);
            };

            client.OnMessage += async(object sender, MessageEventArgs args) =>
            {
                var handler = scope.GetService <IMessageHandler>();
                await handler.BaseHandlerMessage(args, args.Message.Text);
            };
        }
Example #2
0
        /// <summary>
        /// Initialization of the package; this method is called right
        /// after the package is sited, so this is the place where you
        /// can put all the initialization code that rely on services
        /// provided by VisualStudio.
        /// </summary>
        ///
        /// <param name="cancellationToken">
        /// A cancellation token to monitor
        /// for initialization cancellation,
        /// which can occur when VS is
        /// shutting down.
        /// </param>
        ///
        /// <param name="progress">
        /// A provider for progress updates.
        /// </param>
        ///
        /// <returns>
        /// A task representing the async work of package initialization,
        /// or an already completed task if there is none. Do not return
        /// null from this method.
        /// </returns>
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            OleMenuCommandService oleMenuCommandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;

            IVsSolution vsSolution = await GetServiceAsync(typeof(IVsSolution)) as IVsSolution;

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            IMessageProvider messageProvider = new VsixMessageProvider(vsSolution, new ErrorListProvider(this));
            IProjectProvider projectProvider = new VsixProjectProvider();

            RegisterService(messageProvider);
            RegisterService(projectProvider);

            IOptionProvider optionProvider = new OptionProvider(messageProvider);

            RegisterService(optionProvider);

            VsixPackageOption vsixPackageOption = ((VsixPackageOption)GetDialogPage(typeof(VsixPackageOption)));

            AbstractSwitch projectSwtich = new ProjectSwitch(ReferenceType.ProjectReference, vsixPackageOption, projectProvider, messageProvider);
            AbstractSwitch packageSwitch = new PackageSwitch(ReferenceType.PackageReference, vsixPackageOption, projectProvider, messageProvider);
            AbstractSwitch librarySwitch = new LibrarySwitch(ReferenceType.Reference, vsixPackageOption, projectProvider, messageProvider);

            ICommandProvider commandRouter = new CommandProvider(vsixPackageOption, projectSwtich, packageSwitch, librarySwitch);

            new CommandProject(commandRouter, messageProvider).Initialize(oleMenuCommandService, new Guid("c6018e68-fcab-41d2-a34a-42f7df92b162"), 0x0100);
            new CommandPackage(commandRouter, messageProvider).Initialize(oleMenuCommandService, new Guid("c6018e68-fcab-41d2-a34a-42f7df92b162"), 0x0200);
            new CommandLibrary(commandRouter, messageProvider).Initialize(oleMenuCommandService, new Guid("c6018e68-fcab-41d2-a34a-42f7df92b162"), 0x0300);
        }
Example #3
0
        public ExecutionEngineFactory(ClientProvider clientProvider, CommandProvider commandProvider, IExtensionsConfiguration config)
            : base(clientProvider, commandProvider)
        {
            var extensions = config?.Extensions?.Where(x => typeof(IExecutionEngine).IsAssignableFrom(x.Key))?.Select(x => x.Key) ?? new Type[0];

            RegisterEngines(classics.Union(extensions).ToArray());
        }
Example #4
0
        public MainWindowVM()
        {
            rootFileLength = 12; // "database.xml"
            DB             = new DataContainer();
            //input tutorial
            List <string> _tutorial = new List <string>(new string[] { "THEA 2 MOD COMPILER",
                                                                       "", "Please point program to StreamingAssets\\database.xml", "mod folders should start with \"@\" and mirror game files",
                                                                       "eg:",
                                                                       "StreamingAssets/",
                                                                       "               @mod/",
                                                                       "                   eventModules.xml",
                                                                       "                   Modules/",
                                                                       "                           Alphaclan.xml",
                                                                       "Files compiled are eventmodules.xml, database.xml, and terrains.xml",
                                                                       "Backup of default game files saved in StreamingAssets/Backup",
                                                                       "",
                                                                       "Toggles:",
                                                                       "Strict/lax parameter parsing: Abort on parameter problem/revert to merge.",
                                                                       "Infer from prototype: when no parameter present, try and guess action from DataBase/Prototype.",
                                                                       "Defrault to: Default action if no params or prediction.",
                                                                       "",
                                                                       "Mod params:",
                                                                       "MOD_PARAM=\"OVERWRITE\":  (q,w,e) + (e,r,t) => (e,r,t)",
                                                                       "MOD_PARAM=\"MERGE\":  (q,w,e) + (e,r,t) => (q,w,e,r,t)",
                                                                       "MOD_PARAM=\"ADD\":  (q,w,e) + (e,r,t) => (q,w,e,e,r,t)" });

            FileList                   = new ObservableCollection <string>(_tutorial);
            BrowseClick                = new CommandProvider((x) => Browse());
            LoadFileClick              = new CommandProvider((x) => Crawl());
            CompileClick               = new CommandProvider((x) => Compile());
            ToggleParamFollowClick     = new CommandProvider((x) => ToggleParamFollow());
            UsePrototypeInferenceClick = new CommandProvider((x) => TogglePrototypeInference());
            AttemptMergeClick          = new CommandProvider((x) => ToggleAttemptMerge());
        }
Example #5
0
        public void BuildMdx_WithUselessParameter_CorrectResultSet()
        {
            var statement =
                "select " +
                "[Measures].[Order Count] on 0, " +
                "strToMember(@Param) on 1 " +
                "from " +
                "[Adventure Works]";
            var conn  = new AdomdClient(ConnectionStringReader.GetAdomd());
            var query = Mock.Of <IQuery>(
                x => x.ConnectionString == ConnectionStringReader.GetAdomd() &&
                x.Statement == statement &&
                x.Parameters == new List <QueryParameter>()
            {
                new QueryParameter("@Param", "[Product].[Model Name].[Bike Wash]"),
                new QueryParameter("UnusedParam", "Useless")
            });
            var factory = new CommandProvider();
            var cmd     = factory.Instantiate(conn, query).Implementation;

            Assert.IsInstanceOf <AdomdCommand>(cmd);

            (cmd as AdomdCommand).Connection.Open();
            var dr = (cmd as AdomdCommand).ExecuteReader(System.Data.CommandBehavior.CloseConnection);

            Assert.That(dr.Read(), Is.True);
            Assert.That(dr.GetValue(0), Is.EqualTo("Bike Wash"));
            Assert.That(dr.Read(), Is.False);
        }
Example #6
0
 public void Execute <TKey>(CommandProvider <TKey> commandProvider, IDbConnection connection)
 {
     foreach (var cmd in SqlCommands(commandProvider, connection))
     {
         connection.Execute(cmd);
     }
 }
 public override IEnumerable <string> SqlCommands <TKey>(CommandProvider <TKey> commandProvider, IDbConnection connection)
 {
     if (commandProvider.SupportsSchemas && !commandProvider.SchemaExists(connection, SchemaName))
     {
         yield return(commandProvider.CreateSchemaCommand(SchemaName));
     }
 }
Example #8
0
        public void given_correct_account_filter_command_when_determining_report_command_then_the_account_filter_is_added(params string[] args)
        {
            var commandProvider = new CommandProvider();
            var command         = commandProvider.GetCommand(args); // saturday

            Assert.IsInstanceOf(typeof(BuildMonthReportsCommand), command, "Type of command");
            Assert.AreEqual("nwb", command.AccountFilter, "Command account filter");
        }
        public void TestProcess()
        {
            var queryProvider = new CommandProvider();

            var nullResult = queryProvider.Process(null, null);
            Assert.AreEqual(nullResult.Code, CommandResultCode.Invalid);
            Assert.AreEqual(nullResult.ErrorMessage, "Invalid Command!");
        }
Example #10
0
        public async Task FindRelatedAsync(IDbConnection connection, CommandProvider <int> commandProvider, IUser user = null, IEnumerable <Claim> claims = null)
        {
            Team = await connection.FindAsync <Team>(TeamId);

            WorkItemTicket = await connection.FindWhereAsync <WorkItemTicket>(new { this.OrganizationId, WorkItemNumber = Number });

            Organization = await connection.FindAsync <Organization>(OrganizationId);
        }
Example #11
0
 public void FindRelated(IDbConnection connection, CommandProvider <int> commandProvider, IUser user = null, IEnumerable <Claim> claims = null)
 {
     Option        = commandProvider.Find <Option>(connection, OptionId);
     OptionType    = commandProvider.Find <OptionType>(connection, Option.TypeId);
     StorageColumn = OptionType.StorageColumn;
     OptionName    = Option.Name;
     TypeId        = Option.TypeId;
 }
Example #12
0
        public MessageHandler(TelegramBotClient client, MainProvider provider, CommandProvider commandProvider)
        {
            this.client          = client;
            this.provider        = provider;
            this.commandProvider = commandProvider;

            stopChat = new StopChat(client, provider);
        }
Example #13
0
        public void given_correct_month_command_and_date_input_when_determining_report_command_then_the_month_command_with_the_correct_first_period_date_is_returned()
        {
            var commandProvider = new CommandProvider();
            var command         = commandProvider.GetCommand(new[] { "-m", "20200229" }); // saturday

            Assert.IsInstanceOf(typeof(BuildMonthReportsCommand), command, "Type of command");
            Assert.AreEqual(new DateTime(2020, 2, 1), command.FromDay, "Command first date of period");
        }
Example #14
0
        public void given_no_arguments_when_determining_report_command_then_the_default_command_is_returned()
        {
            var commandProvider = new CommandProvider();
            var command         = commandProvider.GetCommand(null);

            Assert.IsInstanceOf(typeof(BuildWeekReportsCommand), command, "Type of command");
            Assert.IsTrue(DateTime.Today - command.FromDay < TimeSpan.FromDays(7), "Default command is for the current week");
        }
Example #15
0
 public void FindRelated(IDbConnection connection, CommandProvider <int> commandProvider, IUser user = null, IEnumerable <Claim> claims = null)
 {
     Organization = commandProvider.Find <Organization>(connection, OrganizationId);
     if (TeamId.HasValue)
     {
         Team = commandProvider.Find <Team>(connection, TeamId.Value);
     }
 }
Example #16
0
        public async Task FindRelatedAsync(IDbConnection connection, CommandProvider <int> commandProvider, IUser user = null, IEnumerable <Claim> claims = null)
        {
            Application = await commandProvider.FindAsync <Application>(connection, ApplicationId);

            Status = await commandProvider.FindAsync <InvoiceStatus>(connection, StatusId);

            Organization = await commandProvider.FindAsync <Organization>(connection, OrganizationId);
        }
Example #17
0
        public async Task FindRelatedAsync(IDbConnection connection, CommandProvider <int> commandProvider)
        {
            Application = await commandProvider.FindAsync <Application>(connection, ApplicationId);

            Status = await commandProvider.FindAsync <InvoiceStatus>(connection, StatusId);

            Organization = await commandProvider.FindAsync <Organization>(connection, OrganizationId);
        }
Example #18
0
        /// <summary>
        /// Used to show an SQL statement with actual values for debugging or logging to a file.
        /// </summary>
        /// <param name="pCommand">Command object</param>
        /// <param name="pProvider"></param>
        /// <param name="pQualifier">Defaults to SQL-Server</param>
        /// <returns>Command object command text with parameter values</returns>
        public static string ActualCommandText(this IDbCommand pCommand, CommandProvider pProvider = CommandProvider.SqlServer, string pQualifier = "@")
        {
            var sb = new StringBuilder(pCommand.CommandText);

            if (pProvider != CommandProvider.Oracle)
            {
                // test for at least one parameter without a name, if found stop here.
                var emptyParameterNames =
                    (
                        from T in pCommand.Parameters.Cast <IDataParameter>()
                        where string.IsNullOrWhiteSpace(T.ParameterName)
                        select T
                    ).FirstOrDefault();

                if (emptyParameterNames != null)
                {
                    return(pCommand.CommandText);
                }
            }
            else if (pProvider == CommandProvider.Oracle)
            {
                pQualifier = ":";
            }


            foreach (IDataParameter p in pCommand.Parameters)
            {
                if ((p.DbType == DbType.AnsiString) || (p.DbType == DbType.AnsiStringFixedLength) || (p.DbType == DbType.Date) || (p.DbType == DbType.DateTime) || (p.DbType == DbType.DateTime2) || (p.DbType == DbType.Guid) || (p.DbType == DbType.String) || (p.DbType == DbType.StringFixedLength) || (p.DbType == DbType.Time) || (p.DbType == DbType.Xml))
                {
                    if (p.ParameterName.Substring(0, 1) == pQualifier)
                    {
                        if (p.Value == null)
                        {
                            throw new Exception($"no value given for parameter '{p.ParameterName}'");
                        }

                        sb = sb.Replace(p.ParameterName, $"'{p.Value.ToString().Replace("'", "''")}'");
                    }
                    else
                    {
                        sb = sb.Replace(string.Concat(pQualifier, p.ParameterName), $"'{p.Value.ToString().Replace("'", "''")}'");
                    }
                }
                else
                {
                    /*
                     * Dummy up a INSERT Oracle statement where the RETURNING has no
                     * value for that parameter so return the parameter name instead
                     * rather than a value.
                     */
                    sb = pProvider == CommandProvider.Oracle ? sb.Replace(p.ParameterName, p.Value?.ToString() ?? p.ParameterName) :
                         sb.Replace(p.ParameterName, p.Value.ToString());
                }
            }

            return(sb.ToString());
        }
Example #19
0
        public static ObservableCollection <Command> CreateCommands(FrameModel frame)
        {
            if (frame.Device.IncludeSaveConfig)
            {
                return(CommandProvider.CreateCommands(frame));
            }

            return(LegacyCommandProvider.CreateCommands(frame));
        }
Example #20
0
        private static Engine GetEngineInstance()
        {
            IWriterProvider  writer          = new ConsoleWriterProvider();
            IReaderProvider  reader          = new ConsoleReaderProvider();
            ICommandProvider commandProvider = new CommandProvider();
            Engine           engine          = new Engine(reader, writer, commandProvider);

            return(engine);
        }
Example #21
0
        public async Task FindRelatedAsync(IDbConnection connection, CommandProvider <int> commandProvider, IUser user = null, IEnumerable <Claim> claims = null)
        {
            Organization = await commandProvider.FindAsync <Organization>(connection, OrganizationId);

            if (TeamId.HasValue)
            {
                Team = await commandProvider.FindAsync <Team>(connection, TeamId.Value);
            }
        }
Example #22
0
        public void FindRelated(IDbConnection connection, CommandProvider <int> commandProvider)
        {
            if (CurrentAppId.HasValue)
            {
                CurrentApp = commandProvider.Find <Application>(connection, CurrentAppId.Value);
            }

            UserProfile  = commandProvider.Find <UserProfile>(connection, UserId);
            Organization = commandProvider.Find <Organization>(connection, OrganizationId);
        }
        public IEnumerable <Action> Compare(IEnumerable <TableInfo> schemaTables, IEnumerable <ColumnInfo> schemaColumns)
        {
            List <Action> results = new List <Action>();

            if (CommandProvider.SupportsSchemas)
            {
                var createSchemas = GetNewSchemas(ModelTables, schemaTables);
                results.AddRange(createSchemas.Select(s => new CreateSchema(s)));
            }

            var createTables = GetNewTables(ModelTables, schemaTables);

            results.AddRange(createTables.Select(tbl => new CreateTable(tbl.ModelType)));

            // when looking for modified columns, don't include tables that were just created
            var existingModelColumns = ModelColumns.Where(col => !createTables.Contains(col.TableInfo));

            var schemaColumnsByTable = schemaColumns.ToLookup(row => row.TableInfo);
            var modelColumnsByTable  = existingModelColumns.ToLookup(row => row.TableInfo);
            var tablesToTypes        = ModelTypes.ToDictionary(t => CommandProvider.GetTableInfo(t));

            foreach (TableInfo tbl in schemaColumnsByTable)
            {
                if (AnyModifiedColumns(schemaColumnsByTable[tbl], modelColumnsByTable[tbl],
                                       out IEnumerable <ColumnInfo> added, out IEnumerable <ColumnInfo> modified, out IEnumerable <ColumnInfo> deleted))
                {
                    if (tbl.RowCount == 0)
                    {
                        // empty tables can be dropped and re-created
                        results.Add(new RebuildTable(tablesToTypes[tbl], added, modified, deleted));
                    }
                    else
                    {
                        // must modify columns directly
                        results.AddRange(added.Select(a => new AddColumn(a)));
                        results.AddRange(deleted.Select(d => new DropColumn(d)));
                        results.AddRange(modified.Select(m => new AlterColumn(m)));
                    }
                }
            }

            //var addColumns = await GetNewColumnsAsync(ModelTypes, createTables.Concat(rebuiltTables), connection);
            //results.AddRange(addColumns.Select(pi => new AddColumn(pi)));

            var dropTables = GetDeletedTables(ModelTables, schemaTables);

            results.AddRange(dropTables.Select(tbl => new DropTable(tbl)));

            var newForeignKeys = ModelColumns.Where(col => createTables.Contains(col.TableInfo) && col.IsForeignKey);

            results.AddRange(newForeignKeys.Select(col => new AddForeignKey(col.ForeignKeyInfo)));

            return(results);
        }
Example #24
0
        public async Task FindRelatedAsync(IDbConnection connection, CommandProvider <int> commandProvider)
        {
            if (CurrentAppId.HasValue)
            {
                CurrentApp = await commandProvider.FindAsync <Application>(connection, CurrentAppId.Value);
            }

            UserProfile = await commandProvider.FindAsync <UserProfile>(connection, UserId);

            Organization = await commandProvider.FindAsync <Organization>(connection, OrganizationId);
        }
Example #25
0
 /// <summary>
 /// Callback for <see cref="MenuCommand"/>.
 /// </summary>
 public override void Callback(object sender, EventArgs eventArgs)
 {
     try
     {
         CommandProvider.Route(Name);
     }
     catch (Exception exception)
     {
         MessageProvider.AddMessage(exception);
     }
 }
Example #26
0
        public override IEnumerable <string> SqlCommands <TKey>(CommandProvider <TKey> commandProvider, IDbConnection connection)
        {
            var fks = DependentForeignKeys ?? commandProvider.GetDependentForeignKeys(connection, TableInfo);

            foreach (var fk in fks)
            {
                yield return(commandProvider.DropForeignKeyCommand(fk));
            }

            yield return(commandProvider.DropTableCommand(TableInfo));
        }
Example #27
0
        static void Main(string[] args)
        {
            var reportingCommandProvider = new CommandProvider();

            var command = (dynamic)reportingCommandProvider.GetCommand(args);
            var timeLogRepositoryFactory = new ManualTimeLogger.Persistence.CsvFileRepositoryFactory(Properties.Settings.Default.TimeLogsBasePath);
            var reportRepositoryFactory  = new CsvFileRepositoryFactory(Properties.Settings.Default.ReportsBasePath, $"{command.AccountFilter ?? "all"}");

            var commandHandler = new CommandHandler(timeLogRepositoryFactory, reportRepositoryFactory);

            commandHandler.Handle(command);
        }
Example #28
0
        //TODO: Затащить это все в chocolatey
        //TODO: Добавить команду generate-dot-settings
        //TODO: Разделить логику и логирование
        //TODO: Добавить тесты
        //TODO: Перевести на DI (будет полезно для тестов)
        //TODO: Избавиться от всех try catch
        //TODO: Научить работать с ключем /p:PublishTrimmed=true
        private static int Main(string[] args)
        {
            if (NewVersionWasInstalled())
            {
                return(0);
            }

            var result = new CommandProvider().StartCommand(args)
                         .OnFail(ConsoleHelper.LogError);

            return(result.IsSuccess ? 0 : 1);
        }
        public static void Main()
        {
            AsynchronousSocketListener.StartListening();
            AsynchronousClient.StartClient();

            while (true)
            {
                string input = Console.ReadLine();

                CommandProvider.RunCommand(input.Split(' ')[0], input);
            }
        }
        public MessageHandler(TelegramBotClient client, MainProvider provider, CommandProvider commandProvider, AdminHandler adminHandler)
        {
            this.client          = client;
            this.provider        = provider;
            this.commandProvider = commandProvider;

            this.adminHandler = adminHandler;

            authSystem   = new AuthenticateSystem(client, provider);
            chatCommands = new ChatCommands(client, provider);
            addCash      = new AddCash(client, provider);
        }
Example #31
0
 internal static void Initialize(CommandSection section)
 {
     _providers = new CommandProviderCollection();
     _provider  = ProviderUtil.InstantiateProviders <CommandProvider, CommandProviderCollection>(
         section.Providers, section.DefaultProvider, _providers);
     if (_provider == null)
     {
         throw new ConfigurationErrorsException(
                   SR.ConfigDefaultLogProviderNotFound,
                   section.ElementInformation.Properties["defaultProvider"].Source,
                   section.ElementInformation.Properties["defaultProvider"].LineNumber);
     }
 }
Example #32
0
        private static void Main(string[] args)
        {
            var stringBuilder = new StringBuilder();

            var addShortWord = new AddWordCommand(stringBuilder, "short | ");
            var addLongWord = new AddWordCommand(stringBuilder, "veryLongCamelCaseWord | ");

            var commandProvider = new CommandProvider<AddWordCommand>();
            commandProvider.PerformCommand(addShortWord);
            commandProvider.PerformCommand(addLongWord);
            Console.WriteLine("Builder now is " + stringBuilder);
            commandProvider.PerformCommand(addShortWord);
            commandProvider.PerformCommand(addLongWord);
            commandProvider.PerformCommand(addLongWord);
            Console.WriteLine("Builder now is " + stringBuilder);
            commandProvider.UndoCommand();
            commandProvider.UndoCommand();
            Console.WriteLine("Builder now is " + stringBuilder);
            Console.ReadKey();
        }