public void SetupServiceBus(string[] assemblyPaths, CommandDefinition cmdDef, Dictionary<string, object> connectionSettings) { _subscriptionQueueService = connectionSettings.GetValue("subscriptionQueueService") as string; if (_bus == null) { if (CommandContentFormat == "JSON") { if (_subscriptionQueueService.IsValid()) { _bus = ServiceBusFactory.New(sbc => { sbc.UseMsmq(); sbc.UseMsmq(x => x.UseSubscriptionService(_subscriptionQueueService)); sbc.ReceiveFrom("msmq://localhost/ServiceBusMQ"); sbc.UseJsonSerializer(); sbc.UseControlBus(); }); } else { _bus = ServiceBusFactory.New(sbc => { sbc.UseMsmq(); //sbc.UseMsmq(x => x.UseSubscriptionService(subscriptionServiceUriString)); sbc.ReceiveFrom("msmq://localhost/ServiceBusMQ"); sbc.UseJsonSerializer(); sbc.UseControlBus(); }); } } else { if (_subscriptionQueueService != string.Empty) { _bus = ServiceBusFactory.New(sbc => { sbc.UseMsmq(); sbc.UseMsmq(x => x.UseSubscriptionService(_subscriptionQueueService)); sbc.ReceiveFrom("msmq://localhost/ServiceBusMQ"); sbc.UseControlBus(); }); } else { _bus = ServiceBusFactory.New(sbc => { sbc.UseMsmq(); //sbc.UseMsmq(x => x.UseSubscriptionService(subscriptionServiceUriString)); sbc.ReceiveFrom("msmq://localhost/ServiceBusMQ"); sbc.UseControlBus(); }); } } Thread.Sleep(TimeSpan.FromSeconds(10)); } }
internal static ICommand Create(CommandDefinition cmdDefinition) { ICommand cmd = null; switch (cmdDefinition.Type) { case CommandDefinitionType.Data: cmd = new Command<DataTable>(cmdDefinition); break; default: cmd = new Command<FileStream>(cmdDefinition); break; } return cmd; }
public Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition commandDef) { List<Type> arr = new List<Type>(); List<string> nonExistingPaths = new List<string>(); foreach( var path in asmPaths ) { if( Directory.Exists(path) ) { foreach( var dll in Directory.GetFiles(path, "*.dll") ) { if( IGNORE_DLL.Any(a => dll.EndsWith(a)) ) continue; try { var asm = Assembly.LoadFrom(dll); foreach( Type t in asm.GetTypes() ) { if( commandDef.IsCommand(t) ) arr.Add(t); } } catch { } } } else nonExistingPaths.Add(path); } if( nonExistingPaths.Count > 0 ) OnError("The paths '{0}' doesn't exist, could not search for commands.".With(nonExistingPaths.Concat())); return arr.ToArray(); }
public static Task <T> QueryFirstOrDefaultAsync <T>(this IDbContext context, CommandDefinition command) { return(context.Connection.QueryFirstOrDefaultAsync <T>(CreateCommandDefinition(context, command))); }
private void CreateCommandDefinitions() { // Constants commandDefinitions[BitcoinScript.OP_FALSE] = new CommandDefinition(false, (script, command) => dataStack.Add(new byte[0])); for (byte op = BitcoinScript.OP_PUSHDATA_LEN_1; op <= BitcoinScript.OP_PUSHDATA_LEN_75; op++) { commandDefinitions[op] = new CommandDefinition(false, PushData); } commandDefinitions[BitcoinScript.OP_PUSHDATA1] = new CommandDefinition(false, PushData1); commandDefinitions[BitcoinScript.OP_PUSHDATA2] = new CommandDefinition(false, PushData2); commandDefinitions[BitcoinScript.OP_PUSHDATA4] = new CommandDefinition(false, PushData4); commandDefinitions[BitcoinScript.OP_1NEGATE] = new CommandDefinition(false, (script, command) => dataStack.Add(new byte[] {0x81})); commandDefinitions[BitcoinScript.OP_TRUE] = new CommandDefinition(false, (script, command) => dataStack.Add(new byte[] {1})); for (byte op = BitcoinScript.OP_2; op <= BitcoinScript.OP_16; op++) { byte val = (byte) (op - BitcoinScript.OP_2 + 2); commandDefinitions[op] = new CommandDefinition(false, (script, command) => dataStack.Add(new byte[] {val})); } // Flow control commandDefinitions[BitcoinScript.OP_NOP] = new CommandDefinition(false, (script, command) => { }); commandDefinitions[BitcoinScript.OP_IF] = new CommandDefinition(true, ExecuteIf); commandDefinitions[BitcoinScript.OP_NOTIF] = new CommandDefinition(true, ExecuteIf); commandDefinitions[BitcoinScript.OP_ELSE] = new CommandDefinition(true, ExecuteElse); commandDefinitions[BitcoinScript.OP_ENDIF] = new CommandDefinition(true, ExecuteEndIf); commandDefinitions[BitcoinScript.OP_VERIFY] = new CommandDefinition(false, ExecuteVerify); commandDefinitions[BitcoinScript.OP_RETURN] = new CommandDefinition(false, ExecuteReturn); // Stack commandDefinitions[BitcoinScript.OP_TOALTSTACK] = new CommandDefinition(false, ExecuteToAltStack); commandDefinitions[BitcoinScript.OP_FROMALTSTACK] = new CommandDefinition(false, ExecuteFromAltStack); commandDefinitions[BitcoinScript.OP_2DROP] = new CommandDefinition(false, Execute2Drop); commandDefinitions[BitcoinScript.OP_2DUP] = new CommandDefinition(false, Execute2Dup); commandDefinitions[BitcoinScript.OP_3DUP] = new CommandDefinition(false, Execute3Dup); commandDefinitions[BitcoinScript.OP_2OVER] = new CommandDefinition(false, Execute2Over); commandDefinitions[BitcoinScript.OP_2ROT] = new CommandDefinition(false, Execute2Rot); commandDefinitions[BitcoinScript.OP_2SWAP] = new CommandDefinition(false, Execute2Swap); commandDefinitions[BitcoinScript.OP_IFDUP] = new CommandDefinition(false, ExecuteIfDup); commandDefinitions[BitcoinScript.OP_DEPTH] = new CommandDefinition(false, ExecuteDepth); commandDefinitions[BitcoinScript.OP_DROP] = new CommandDefinition(false, ExecuteDrop); commandDefinitions[BitcoinScript.OP_DUP] = new CommandDefinition(false, ExecuteDup); commandDefinitions[BitcoinScript.OP_NIP] = new CommandDefinition(false, ExecuteNip); commandDefinitions[BitcoinScript.OP_OVER] = new CommandDefinition(false, ExecuteOver); commandDefinitions[BitcoinScript.OP_PICK] = new CommandDefinition(false, ExecutePick); commandDefinitions[BitcoinScript.OP_ROLL] = new CommandDefinition(false, ExecuteRoll); commandDefinitions[BitcoinScript.OP_ROT] = new CommandDefinition(false, ExecuteRot); commandDefinitions[BitcoinScript.OP_SWAP] = new CommandDefinition(false, ExecuteSwap); commandDefinitions[BitcoinScript.OP_TUCK] = new CommandDefinition(false, ExecuteTuck); // Bitwise Logic commandDefinitions[BitcoinScript.OP_INVERT] = new CommandDefinition(true, ExecuteDisabled); commandDefinitions[BitcoinScript.OP_AND] = new CommandDefinition(true, ExecuteDisabled); commandDefinitions[BitcoinScript.OP_OR] = new CommandDefinition(true, ExecuteDisabled); commandDefinitions[BitcoinScript.OP_XOR] = new CommandDefinition(true, ExecuteDisabled); commandDefinitions[BitcoinScript.OP_EQUAL] = new CommandDefinition(false, ExecuteEqual); commandDefinitions[BitcoinScript.OP_EQUALVERIFY] = new CommandDefinition(false, ExecuteEqualVerify); // Crypto commandDefinitions[BitcoinScript.OP_RIPEMD160] = new CommandDefinition(false, ExecuteRipeMd160); commandDefinitions[BitcoinScript.OP_SHA1] = new CommandDefinition(false, ExecuteSha1); commandDefinitions[BitcoinScript.OP_SHA256] = new CommandDefinition(false, ExecuteSha256); commandDefinitions[BitcoinScript.OP_HASH160] = new CommandDefinition(false, ExecuteHash160); commandDefinitions[BitcoinScript.OP_HASH256] = new CommandDefinition(false, ExecuteHash256); commandDefinitions[BitcoinScript.OP_CODESEPARATOR] = new CommandDefinition(false, ExecuteCodeSeparator); commandDefinitions[BitcoinScript.OP_CHECKSIG] = new CommandDefinition(false, ExecuteCheckSig); commandDefinitions[BitcoinScript.OP_CHECKSIGVERIFY] = new CommandDefinition(false, ExecuteCheckSigVerify); commandDefinitions[BitcoinScript.OP_CHECKMULTISIG] = new CommandDefinition(false, ExecuteCheckMultiSig); commandDefinitions[BitcoinScript.OP_CHECKMULTISIGVERIFY] = new CommandDefinition(false, ExecuteCheckMultiSigVerify); }
public static SqlMapper.GridReader QueryMultiple(this IDbContext context, CommandDefinition command) { return(context.Connection.QueryMultiple(CreateCommandDefinition(context, command))); }
public static int Execute(this IDbContext context, CommandDefinition command) { return(context.Connection.Execute(CreateCommandDefinition(context, command))); }
public void AssertNoCacheWorksForQueryMultiple() { int a = 123, b = 456; var cmdDef = new CommandDefinition(@"select @a; select @b;", new { a, b }, commandType: CommandType.Text, flags: CommandFlags.NoCache); int c, d; SqlMapper.PurgeQueryCache(); int before = SqlMapper.GetCachedSQLCount(); using (var multi = marsConnection.QueryMultiple(cmdDef)) { c = multi.Read<int>().Single(); d = multi.Read<int>().Single(); } int after = SqlMapper.GetCachedSQLCount(); before.IsEqualTo(0); after.IsEqualTo(0); c.IsEqualTo(123); d.IsEqualTo(456); }
public static void Save(CommandDefinition cmd) { Connection().Execute(cmd); }
public HelpCommands(CommandIconService commandIconService) { AboutCommand = new CommandDefinition( "About", commandIconService.GetCompletionKindImage("About"), ReactiveCommand.Create(() => IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel()))); CustomerSupportCommand = new CommandDefinition( "Customer Support", commandIconService.GetCompletionKindImage("CustomerSupport"), ReactiveCommand.CreateFromTask(async() => { try { await IoHelpers.OpenBrowserAsync("https://www.reddit.com/r/WasabiWallet/"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel()); } })); ReportBugCommand = new CommandDefinition( "Report Bug", commandIconService.GetCompletionKindImage("ReportBug"), ReactiveCommand.CreateFromTask(async() => { try { await IoHelpers.OpenBrowserAsync("https://github.com/zkSNACKs/WalletWasabi/issues"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel()); } })); DocsCommand = new CommandDefinition( "Documentation", commandIconService.GetCompletionKindImage("Documentation"), ReactiveCommand.CreateFromTask(async() => { try { await IoHelpers.OpenBrowserAsync("https://docs.wasabiwallet.io/"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel()); } })); LegalDocumentsCommand = new CommandDefinition( "Legal Documents", commandIconService.GetCompletionKindImage("LegalDocuments"), ReactiveCommand.Create(() => IoC.Get <IShell>().AddOrSelectDocument(() => new LegalDocumentsViewModel()))); Observable .Merge(AboutCommand.GetReactiveCommand().ThrownExceptions) .Merge(CustomerSupportCommand.GetReactiveCommand().ThrownExceptions) .Merge(ReportBugCommand.GetReactiveCommand().ThrownExceptions) .Merge(DocsCommand.GetReactiveCommand().ThrownExceptions) .Merge(LegalDocumentsCommand.GetReactiveCommand().ThrownExceptions) .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => { Logger.LogError(ex); NotificationHelpers.Error(ex.ToUserFriendlyString()); }); }
public static IDataReader ExecuteReader(RDBMSProvider rdbmsProvider, string connectionString, CommandDefinition command, CommandBehavior commandBehavior) { IDbConnection connection = null; try { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("Connection string cannot be null, empty or white-space.", nameof(connectionString)); } connection = CreateConnection(rdbmsProvider, connectionString); connection.Open(); return(connection.ExecuteReader(command, commandBehavior)); } catch { throw; } finally { connection.Dispose(); } }
public CommandToolBarItem(ToolBarItemDefinition toolBarItem, CommandDefinition commandDefinition) { _toolBarItem = toolBarItem; _command = commandDefinition.Command; _iconPath = commandDefinition.IconPath; }
/// <summary> /// Executes a query, returning the data typed as <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type of results to return.</typeparam> /// <param name="transaction">The transaction to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <returns> /// A sequence of data of <typeparamref name="T"/>; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive). /// </returns> public static IEnumerable <T> Query <T>(this IDbTransaction transaction, CommandDefinition command) { return(InternalGetConnection.GetConnection(transaction).Query <T>(command)); }
protected T GetOne <T>(string storedProcedureName, DynamicParameters parameters) { CommandDefinition command = dbManager.GetStoredProcedureCommand(storedProcedureName, parameters, 600); return(dbManager.GetOne <T>(command)); }
// ISendCommand public Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition commandDef, bool suppressErrors) { List <Type> arr = new List <Type>(); List <string> nonExistingPaths = new List <string>(); foreach (var path in asmPaths) { if (Directory.Exists(path)) { foreach (var dll in Directory.GetFiles(path, "*.dll")) { if (IGNORE_DLL.Any(a => dll.EndsWith(a))) { continue; } try { var asm = Assembly.LoadFrom(dll); //var asm = Assembly.ReflectionOnlyLoadFrom(dll); foreach (Type t in asm.GetTypes()) { if (commandDef.IsCommand(t)) { arr.Add(t); } } } catch (ReflectionTypeLoadException fte) { if (suppressErrors) { continue; } StringBuilder sb = new StringBuilder(); if (fte.LoaderExceptions != null) { if (fte.LoaderExceptions.All(a => a.Message.EndsWith("does not have an implementation."))) { continue; } string lastMsg = null; foreach (var ex in fte.LoaderExceptions) { if (ex.Message != lastMsg) { sb.AppendFormat(" - {0}\n\n", lastMsg = ex.Message); } } sb.Append("Try adding these libraries to your Assembly Folder"); } OnWarning("Could not search for Commands in Assembly '{0}'".With(Path.GetFileName(dll)), sb.ToString()); } catch { } } } else { nonExistingPaths.Add(path); } } if (nonExistingPaths.Count > 0) { OnError("The paths '{0}' doesn't exist, could not search for commands.".With(nonExistingPaths.Concat())); } return(arr.ToArray()); }
public static IEnumerable <T> Query <T>(RDBMSProvider rdbmsProvider, string connectionString, CommandDefinition command) { IDbConnection connection = null; try { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("Connection string cannot be null, empty or white-space.", nameof(connectionString)); } connection = CreateConnection(rdbmsProvider, connectionString); connection.Open(); return(connection.Query <T>(command)); } catch { throw; } finally { connection.Dispose(); } }
/// <summary> /// Registers a command and the delegate to call for it. /// </summary> /// <param name="name"></param> /// <param name="handler"></param> /// <param name="flags"></param> /// <param name="description"></param> /// <param name="argCompletion"></param> public void AddCommand(string name, string description, CommandFlags flags, EventHandler<CommandEventArgs> handler, EventHandler<CommandEventArgs> completionHandler) { if(_commands.ContainsKey(name) == true) { idConsole.WriteLine("idCmdSystem.AddCommand: {0} already defined", name); } else { CommandDefinition cmd = new CommandDefinition(); cmd.Name = name; cmd.Description = description; cmd.Handler = handler; cmd.CompletionHandler = completionHandler; cmd.Flags = flags; _commands.Add(name, cmd); } }
public HelpCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global) { Global = global.Global; AboutCommand = new CommandDefinition( "About", commandIconService.GetCompletionKindImage("About"), ReactiveCommand.Create(() => { IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel(Global)); })); CustomerSupportCommand = new CommandDefinition( "Customer Support", commandIconService.GetCompletionKindImage("CustomerSupport"), ReactiveCommand.Create(() => { try { IoHelpers.OpenBrowser("https://www.reddit.com/r/WasabiWallet/"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel(Global)); } })); ReportBugCommand = new CommandDefinition( "Report Bug", commandIconService.GetCompletionKindImage("ReportBug"), ReactiveCommand.Create(() => { try { IoHelpers.OpenBrowser("https://github.com/zkSNACKs/WalletWasabi/issues"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel(Global)); } })); DocsCommand = new CommandDefinition( "Documentation", commandIconService.GetCompletionKindImage("Documentation"), ReactiveCommand.Create(() => { try { IoHelpers.OpenBrowser("https://docs.wasabiwallet.io/"); } catch (Exception ex) { Logger.LogWarning(ex); IoC.Get <IShell>().AddOrSelectDocument(() => new AboutViewModel(Global)); } })); PrivacyPolicyCommand = new CommandDefinition( "Privacy Policy", commandIconService.GetCompletionKindImage("PrivacyPolicy"), ReactiveCommand.Create(() => { IoC.Get <IShell>().AddOrSelectDocument(() => new PrivacyPolicyViewModel(Global)); })); TermsAndConditionsCommand = new CommandDefinition( "Terms and Conditions", commandIconService.GetCompletionKindImage("TermsAndConditions"), ReactiveCommand.Create(() => { IoC.Get <IShell>().AddOrSelectDocument(() => new TermsAndConditionsViewModel(Global)); })); LegalIssuesCommand = new CommandDefinition( "Legal Issues", commandIconService.GetCompletionKindImage("LegalIssues"), ReactiveCommand.Create(() => { IoC.Get <IShell>().AddOrSelectDocument(() => new LegalIssuesViewModel(Global)); })); }
public abstract void SetupServiceBus(string[] assemblyPaths, CommandDefinition cmdDef);
public static async Task<(ulong Total, IEnumerable<StakePool> StakePools)> ListStakePools(this DbConnection dbConnection, CancellationToken cancellationToken, uint? epochNo = null, uint offset = 0, uint limit = 100) { if (epochNo == null) { var epoch = await dbConnection.GetCurrentEpoch(cancellationToken); epochNo = epoch.Number; } const string SearchStakePoolsQueryString = @"SELECT pool_update.hash_id PoolId, COUNT(*) OVER () AS TotalStakePools FROM public.pool_update LEFT JOIN public.pool_retire ON pool_update.hash_id = pool_retire.hash_id WHERE pool_update.active_epoch_no <= @EpochNo AND (pool_retire.retiring_epoch IS NULL OR pool_retire.retiring_epoch >= @EpochNo) GROUP BY pool_update.hash_id ORDER BY pool_update.hash_id ASC LIMIT @Limit OFFSET @Offset"; const string StakePoolUpdateDetails = @"SELECT pool_hash.id PoolId, pool_hash.view AS PoolAddress, pool_update.pledge AS Pledge, pool_update.active_epoch_no AS ActiveSinceEpochNumber, pool_update.margin AS Margin, pool_update.fixed_cost AS FixedCost, pool_metadata_ref.url AS MetadataUrl FROM public.pool_hash INNER JOIN public.pool_update ON pool_hash.id = pool_update.hash_id LEFT JOIN public.pool_metadata_ref ON pool_update.registered_tx_id = pool_metadata_ref.registered_tx_id WHERE pool_hash.id = @PoolId"; const string StakeQueryString = @" SELECT SUM(amount) TotalStake FROM public.epoch_stake WHERE epoch_stake.pool_id = @PoolId AND epoch_no <= @EpochNo "; var searchCommand = new CommandDefinition(SearchStakePoolsQueryString, new { EpochNo = (int)epochNo, Limit = (int)limit, Offset = (int)offset }, commandType: System.Data.CommandType.Text, cancellationToken: cancellationToken); var stakePoolsSearch = await dbConnection.QueryAsync<SearchStakePoolResult>(searchCommand).ConfigureAwait(false); var stakePools = stakePoolsSearch.Select(pool => new StakePool { PoolId = pool.PoolId }).ToArray(); foreach (var stakePool in stakePools) { var updatesCommand = new CommandDefinition(StakePoolUpdateDetails, new { PoolId = stakePool.PoolId }, commandType: System.Data.CommandType.Text, cancellationToken: cancellationToken); var stakePoolUpdates = await dbConnection.QueryAsync<StakePoolMetadataUpdates>(updatesCommand).ConfigureAwait(false); if (stakePoolUpdates.Any() == false) throw new InvalidOperationException($"There should be atleast an update for the pool id {stakePool.PoolId}"); foreach (var poolUpdate in stakePoolUpdates.Where(upd => upd.ActiveSinceEpochNumber <= epochNo).OrderBy(upd => upd.ActiveSinceEpochNumber)) { stakePool.PoolAddress = poolUpdate.PoolAddress; if (stakePool.ActiveSinceEpochNumber == default) stakePool.ActiveSinceEpochNumber = (ulong)poolUpdate.ActiveSinceEpochNumber; stakePool.Pledge = (ulong)poolUpdate.Pledge; stakePool.Margin = poolUpdate.Margin; stakePool.FixedCost = (ulong)poolUpdate.FixedCost; stakePool.MetadataUrl = poolUpdate.MetadataUrl ?? stakePool.MetadataUrl; } var delegationCommand = new CommandDefinition(StakeQueryString, new { PoolId = stakePool.PoolId, EpochNo = (int)epochNo }, commandType: System.Data.CommandType.Text, cancellationToken: cancellationToken); var delegation = await dbConnection.QuerySingleOrDefaultAsync<ulong>(delegationCommand); stakePool.Delegation = delegation; }; return ((ulong)(stakePoolsSearch.FirstOrDefault()?.TotalStakePools ?? 0), stakePools); }
public IDataReader ExecuteReader(CommandDefinition command) { throw new NotImplementedException(); }
public async Task <CommandDefinition> Save(CommandDefinition command, CancellationToken cancellationToken = default(CancellationToken)) { return(await _commandDefinitionRepository.SaveOrUpdateAsync(command, cancellationToken)); }
public virtual void Init(string serverName, string[] watchCommandQueues, string[] watchEventQueues, string[] watchMessageQueues, string[] watchErrorQueues, CommandDefinition commandDef) { _serverName = serverName; _watchCommandQueues = watchCommandQueues; _watchEventQueues = watchEventQueues; _watchMessageQueues = watchMessageQueues; _watchErrorQueues = watchErrorQueues; _commandDef = commandDef; LoadQueues(); }
private Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition cmdDef, bool suppressErrors) { var srv = CurrentServer; return(_sys.GetAvailableCommands(srv.ServiceBus, srv.ServiceBusVersion, srv.ServiceBusQueueType, asmPaths, cmdDef, suppressErrors)); }
public static T QuerySingleOrDefault <T>(this IDbContext context, CommandDefinition command) { return(context.Connection.QuerySingleOrDefault <T>(CreateCommandDefinition(context, command))); }
private void UpdateSendCommandInfo(bool animate = true) { StringBuilder sb = new StringBuilder(); try { if (asmPaths.ItemsCount > 0) { CommandDefinition cmdDef = new CommandDefinition(); if (tbCmdInherits.Text.IsValid()) { cmdDef.InheritsType = tbCmdInherits.Text; } var cmdNamespace = tbNamespace.RetrieveValue <string>(); if (cmdNamespace.IsValid()) { cmdDef.NamespaceContains = cmdNamespace; } var mw = App.Current.MainWindow as MainWindow; if (!ServiceBusFactory.CanSendCommand(CurrentServer.ServiceBus, CurrentServer.ServiceBusVersion, CurrentServer.ServiceBusQueueType)) { sb.Append("Service Bus Adapter doesn't support Sending Commands"); lbCmdsFound.Content = string.Empty; return; } var cmds = GetAvailableCommands(asmPaths.GetItems(), cmdDef, !animate); // !animate = on dialog startup lbCmdsFound.Content = "{0} Commands Found".With(cmds.Length); if (cmds.Length == 0) { sb.Append("No commands found"); if (cmdDef.InheritsType.IsValid()) { sb.Append(" that inherits " + cmdDef.InheritsType.Substring(0, cmdDef.InheritsType.IndexOf(',')).CutBeginning(40)); } if (cmdDef.NamespaceContains.IsValid()) { if (cmdDef.InheritsType.IsValid()) { sb.Append(" or"); } else { sb.Append(" that"); } sb.AppendFormat(" contains '{0}' in Namespace", cmdDef.NamespaceContains); } sb.Append(", make sure your Command Definition is correct"); } } else { sb.Append("You need to add at least one assembly path containing commands libraries to be able to Send Commands"); lbCmdsFound.Content = string.Empty; } } finally { if (sb.Length > 0) { lbSendCommandInfo.Text = sb.ToString(); } UpdateInfoBox(sb.Length > 0, animate, ROW_SENDCMD_INFO, ConfigWindow.SendCommandInfoHeightProperty); } }
public static Task <dynamic> QuerySingleOrDefaultAsync(this IDbContext context, CommandDefinition command) { return(context.Connection.QuerySingleOrDefaultAsync(CreateCommandDefinition(context, command))); }
public async Task AddToRoleAsync(ApplicationUser user, string roleName, CancellationToken cancellationToken) { using (var connection = _connectionFactory.Create()) { if (connection.State != ConnectionState.Open) { await connection.OpenAsync(cancellationToken); } using (var transaction = await connection.BeginTransactionAsync(cancellationToken)) { try { var selectRoleCmd = new CommandDefinition ( commandText: @"SELECT [Id] FROM [ApplicationRole] WHERE [NormalizedName] = @NormalizedName", parameters: new { NormalizedName = roleName.ToUpper() }, cancellationToken: cancellationToken ); var roleId = await connection.ExecuteScalarAsync <int?>(selectRoleCmd); if (!roleId.HasValue) { var insertRoleCmd = new CommandDefinition ( commandText: @"INSERT INTO [ApplicationRole] ([Name], [NormalizedName]) VALUES (@Name, @NormalizedName)", parameters: new { Name = roleName, NormalizedName = roleName.ToUpper() }, cancellationToken: cancellationToken ); await connection.ExecuteAsync(insertRoleCmd); roleId = await connection.ExecuteScalarAsync <int?>(selectRoleCmd); } var insertCmd = new CommandDefinition ( commandText: @"IF NOT EXISTS( SELECT 1 FROM [ApplicationUserRole] WHERE [UserId] = @UserId AND [RoleId] = @RoleId ) INSERT INTO [ApplicationUserRole] ([UserId], [RoleId]) VALUES(@UserId, @RoleId)", parameters: new { UserId = user.Id, RoleId = roleId }, cancellationToken: cancellationToken ); await connection.ExecuteAsync(insertCmd); await transaction.CommitAsync(cancellationToken); } catch (Exception ex) { await transaction.RollbackAsync(cancellationToken); throw ex; } } } }
public static Task <IEnumerable <T> > QueryAsync <T>(this IDbContext context, CommandDefinition command) { return(context.Connection.QueryAsync <T>(CreateCommandDefinition(context, command))); }
public async Task <IdentityResult> CreateAsync(ApplicationUser user, CancellationToken cancellationToken) { using (var connection = _connectionFactory.Create()) { if (connection.State != ConnectionState.Open) { await connection.OpenAsync(cancellationToken); } using (var transaction = await connection.BeginTransactionAsync(cancellationToken)) { try { var insertCmd = new CommandDefinition ( commandText: @"INSERT INTO [ApplicationUser] ([UserName], [NormalizedUserName], [Email], [NormalizedEmail], [EmailConfirmed], [PasswordHash], [PhoneNumber], [PhoneNumberConfirmed], [TwoFactorEnabled]) VALUES (@UserName, @NormalizedUserName, @Email, @NormalizedEmail, @EmailConfirmed, @PasswordHash, @PhoneNumber, @PhoneNumberConfirmed, @TwoFactorEnabled)", parameters: user, cancellationToken: cancellationToken ); await connection.ExecuteAsync(insertCmd); var selectCmd = new CommandDefinition ( commandText: @"SELECT [Id] FROM [ApplicationUser] WHERE [NormalizedUserName] = @NormalizedUserName AND [NormalizedEmail] = @NormalizedEmail", parameters: user, cancellationToken: cancellationToken ); var newId = await connection.ExecuteScalarAsync <int?>(selectCmd); if (newId.HasValue && newId.Value > 0) { user.Id = newId.Value; await transaction.CommitAsync(cancellationToken); return(IdentityResult.Success); } else { await transaction.RollbackAsync(cancellationToken); return(IdentityResult.Failed(new IdentityError() { Code = "User_Lookup_Error", Description = "Failed to lookup newly added user." })); } } catch (Exception ex) { await transaction.RollbackAsync(cancellationToken); throw ex; } } } }
public static Task <object> QuerySingleAsync(this IDbContext context, Type type, CommandDefinition command) { return(context.Connection.QuerySingleAsync(type, CreateCommandDefinition(context, command))); }
public async Task <GameId> SaveNewSimulationAsync( NewSimulation newSimulation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); GameId gameId; using (var connection = await _connectionFactory.CreateAndOpenAsync(cancellationToken)) using (var transaction = connection.BeginTransaction()) { try { int surrogateGameId = default; int firstPlayerId = default; { var commandText = @" INSERT INTO game (board_type, num_sequences_to_win, seed, version) VALUES (@boardType, @numSequencesToWin, @seed, @version) RETURNING id, game_id;"; var parameters = new { boardType = (int)newSimulation.BoardType, numSequencesToWin = newSimulation.WinCondition, seed = newSimulation.Seed, version = 1 }; var command = new CommandDefinition( commandText, parameters, transaction, cancellationToken: cancellationToken ); var result = await connection.QuerySingleAsync <insert_into_game>(command); surrogateGameId = result.id; gameId = result.game_id; } for (int i = 0; i < newSimulation.Players.Count; i++) { var commandText = @" INSERT INTO game_player (game_id, player_id, player_type) VALUES (@gameId, @playerId, @playerType::player_type) RETURNING id;"; var player = newSimulation.Players[i]; var parameters = new { gameId = surrogateGameId, playerId = player.BotType.ToString(), playerType = PlayerType.Bot.ToString().ToLowerInvariant(), }; var command = new CommandDefinition( commandText, parameters, transaction, cancellationToken: cancellationToken ); var result = await connection.QuerySingleAsync <int>(command); if (newSimulation.FirstPlayerIndex == i) { firstPlayerId = result; } } { var commandText = @" UPDATE game SET first_player_id = @firstPlayerId WHERE id = @gameId;"; var parameters = new { firstPlayerId, gameId = surrogateGameId }; var command = new CommandDefinition( commandText, parameters, transaction, cancellationToken: cancellationToken ); await connection.ExecuteAsync(command); } { var commandText = @" INSERT INTO simulation (game_id, created_by) VALUES (@gameId, @createdBy);"; var parameters = new { gameId = surrogateGameId, createdBy = newSimulation.CreatedBy }; var command = new CommandDefinition( commandText, parameters, transaction, cancellationToken: cancellationToken ); await connection.ExecuteAsync(command); } await transaction.CommitAsync(cancellationToken); } catch { await transaction.RollbackAsync(cancellationToken); throw; } } return(gameId); }
public ServerConfig3() { MonitorInterval = DEFAULT_MONITOR_INTERVAL; CommandDefinition = new CommandDefinition(); }
private Task HelpFor(CommandDefinition command) { return HelpFor(Console, command); }
public static void Add(string name, CommandDefinition def) { CommandDefinition.Add(name, def); }
public override void SetupServiceBus(string[] assemblyPaths, CommandDefinition cmdDef) { _commandDef = cmdDef; List<Assembly> asms = new List<Assembly>(); foreach( string path in assemblyPaths ) { foreach( string file in Directory.GetFiles(path, "*.dll") ) { try { asms.Add(Assembly.LoadFrom(file)); } catch { } } } _bus = Configure.With(asms) .DefineEndpointName("SBMQM_NSB_JSON") .DefaultBuilder() //.MsmqSubscriptionStorage() .DefiningCommandsAs(t => _commandDef.IsCommand(t)) .JsonSerializer() .MsmqTransport() .UnicastBus() .SendOnly(); }
public CommandMenuItem(string name, CommandDefinition commandDefinition) : base(name) { _commandService = IoC.Get <ICommandService>(); _command = _commandService.GetCommand(commandDefinition); _command.PropertyChanged += (s, e) => { NotifyOfPropertyChange(e.PropertyName); }; }
public IEnumerable <T> Query <T>(CommandDefinition command) { throw new NotImplementedException(); }
public virtual async Task HelpFor(IConsole console, CommandDefinition command) { await console.WriteHelpLine("nucmd {0} - {1}", String.IsNullOrEmpty(command.Group) ? command.Name : (command.Group + " " + command.Name), command.Description); await console.WriteHelp(ArgUsage.GetStyledUsage(command.Type).ToString()); }
public void CallCommand(CommandDefinition def, object[] arguments) { def.Function.DynamicInvoke(arguments); }
public Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition cmdDef, bool suppressErrors) { List<Type> arr = new List<Type>(); List<string> nonExistingPaths = new List<string>(); foreach (var path in asmPaths) { if (Directory.Exists(path)) { foreach (var dll in Directory.GetFiles(path, "*.dll")) { if (IGNORE_DLL.Any(a => dll.EndsWith(a))) continue; try { var asm = Assembly.LoadFrom(dll); foreach (Type t in asm.GetTypes()) { if (cmdDef.IsCommand(t)) arr.Add(t); } } catch (ReflectionTypeLoadException fte) { if (suppressErrors) continue; StringBuilder sb = new StringBuilder(); if (fte.LoaderExceptions != null) { if (fte.LoaderExceptions.All(a => a.Message.EndsWith("does not have an implementation."))) continue; string lastMsg = null; foreach (var ex in fte.LoaderExceptions) { if (ex.Message != lastMsg) sb.AppendFormat(" - {0}\n\n", lastMsg = ex.Message); } } OnWarning("Could not search for Commands in Assembly '{0}'".With(Path.GetFileName(dll)), sb.ToString()); } catch { } } } else nonExistingPaths.Add(path); } if (nonExistingPaths.Count > 0) OnError("The paths '{0}' doesn't exist, could not search for commands.".With(nonExistingPaths.Concat())); return arr.ToArray(); }
internal IDataReader GetDataReader(CommandDefinition command) { return(this.Connection.ExecuteReader(command, CommandBehavior.CloseConnection)); }
protected override void FillDefaulValues() { if( Id == null ) Id = Guid.NewGuid().ToString(); if( VersionCheck == null ) VersionCheck = new VersionCheck(); if( Servers == null ) { Servers = new List<ServerConfig2>(); Servers.Add(ServerConfig2.Default); MonitorServer = Servers[0].Name; } // Convert MSMQ plain to XML, as we now support more then one content serializer foreach( var srv in this.Servers ) { if( srv.MessageBus == "NServiceBus" ) { if( srv.MessageBusQueueType == "MSMQ (XML)" ) { srv.MessageBusQueueType = "MSMQ"; CommandContentType = "XML"; } else if( srv.MessageBusQueueType == "MSMQ (JSON)" ) { srv.MessageBusQueueType = "MSMQ"; CommandContentType = "JSON"; } } } if( CommandDefinition == null ) { CommandDefinition = new CommandDefinition(); // Re-evaluate after suppot for more then NServiceBus is implemented if( this.Servers.Count == 0 || this.Servers.First().MessageBus == "NServiceBus" ) CommandDefinition.InheritsType = "NServiceBus.ICommand, NServiceBus"; } if( !CommandContentType.IsValid() ) CommandContentType = "XML"; }
public async Task <T> ExecuteSqlWithParameterAsync <T>(SqlConnection connection, SqlTransaction transaction, DynamicParameters parameters, string sql, CancellationToken cancellationToken) { var commandDefinition = new CommandDefinition(sql, parameters, commandTimeout: 600, transaction: transaction, cancellationToken: cancellationToken); return(await connection.QuerySingleAsync <T>(commandDefinition)); }
public async Task ExecuteStoredProcedure(string sprocName, DynamicParameters parameters, SqlConnection connection, SqlTransaction transaction, CancellationToken cancellationToken) { var commandDefinition = new CommandDefinition(sprocName, parameters, commandType: CommandType.StoredProcedure, transaction: transaction, commandTimeout: 600, cancellationToken: cancellationToken); await connection.QueryAsync(commandDefinition); }
public abstract Type[] GetAvailableCommands(string[] asmPaths, CommandDefinition commandDef);