/// <summary> /// Implements the <see cref="IInterceptCommand"/> method for O/R mapper command logging. /// </summary> /// <param name="transactionId">The transaction ID.</param> /// <param name="entityType">The entity type.</param> /// <param name="commandInfo">The command info.</param> /// <param name="dbCommand">The database command parameters.</param> public void InterceptCommand(Guid transactionId, Type entityType, CommandInfo commandInfo, IDbCommand dbCommand) { if (LogProvider.Logger.IsDebugEnabled) { LogProvider.Logger.Debug(ParseCommand(commandInfo, dbCommand)); } }
/// <summary> /// Parses the command information provided on construction /// to a human-readable format. /// </summary> /// <returns></returns> public static string ParseCommand(CommandInfo commandInfo, IDbCommand dbCommand) { StringBuilder message = new StringBuilder(); message.Append(commandInfo.ToString()); if (dbCommand != null) { message.Append(": ").Append(dbCommand.CommandText.TrimEnd(lineEnds)); for (int index = 0; index < dbCommand.Parameters.Count; index++) { IDbDataParameter parameter = dbCommand.Parameters[index] as IDbDataParameter; if (parameter != null) { message.Append(parameter.ParameterName).Append(" = ").Append(parameter.Value).Append(", "); } } if (dbCommand.Parameters.Count > 0) { message.Length -= 2; } } return message.ToString(); }
/// <summary> /// ����һ������ /// </summary> public int Add(Model.contents.article_attribute_field model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into " + databaseprefix + "article_attribute_field("); strSql.Append("name,title,control_type,data_type,data_length,data_place,item_option,default_value,is_required,is_password,is_html,editor_type,valid_tip_msg,valid_error_msg,valid_pattern,sort_id,is_sys)"); strSql.Append(" values ("); strSql.Append("@name,@title,@control_type,@data_type,@data_length,@data_place,@item_option,@default_value,@is_required,@is_password,@is_html,@editor_type,@valid_tip_msg,@valid_error_msg,@valid_pattern,@sort_id,@is_sys)"); strSql.Append(";set @ReturnValue= @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@name", SqlDbType.NVarChar,100), new SqlParameter("@title", SqlDbType.NVarChar,100), new SqlParameter("@control_type", SqlDbType.NVarChar,50), new SqlParameter("@data_type", SqlDbType.NVarChar,50), new SqlParameter("@data_length", SqlDbType.Int,4), new SqlParameter("@data_place", SqlDbType.TinyInt,1), new SqlParameter("@item_option", SqlDbType.NText), new SqlParameter("@default_value", SqlDbType.NText), new SqlParameter("@is_required", SqlDbType.TinyInt,1), new SqlParameter("@is_password", SqlDbType.TinyInt,1), new SqlParameter("@is_html", SqlDbType.TinyInt,1), new SqlParameter("@editor_type", SqlDbType.TinyInt,1), new SqlParameter("@valid_tip_msg", SqlDbType.NVarChar,255), new SqlParameter("@valid_error_msg", SqlDbType.NVarChar,255), new SqlParameter("@valid_pattern", SqlDbType.NVarChar,500), new SqlParameter("@sort_id", SqlDbType.Int,4), new SqlParameter("@is_sys", SqlDbType.TinyInt,1), new SqlParameter("@ReturnValue",SqlDbType.Int)}; parameters[0].Value = model.name; parameters[1].Value = model.title; parameters[2].Value = model.control_type; parameters[3].Value = model.data_type; parameters[4].Value = model.data_length; parameters[5].Value = model.data_place; parameters[6].Value = model.item_option; parameters[7].Value = model.default_value; parameters[8].Value = model.is_required; parameters[9].Value = model.is_password; parameters[10].Value = model.is_html; parameters[11].Value = model.editor_type; parameters[12].Value = model.valid_tip_msg; parameters[13].Value = model.valid_error_msg; parameters[14].Value = model.valid_pattern; parameters[15].Value = model.sort_id; parameters[16].Value = model.is_sys; parameters[17].Direction = ParameterDirection.Output; List<CommandInfo> sqllist = new List<CommandInfo>(); CommandInfo cmd = new CommandInfo(strSql.ToString(), parameters); sqllist.Add(cmd); //������չ�ֶα���һ�� StringBuilder strSql2 = new StringBuilder(); strSql2.Append("alter table " + databaseprefix + "article_attribute_value add " + model.name + " " + model.data_type); SqlParameter[] parameters2 = { }; cmd = new CommandInfo(strSql2.ToString(), parameters2); sqllist.Add(cmd); DbHelperSQL.ExecuteSqlTranWithIndentity(sqllist); return (int)parameters[17].Value; }
public CommandResult Process(CommandInfo info, Repository repository) { info.CheckArity(0); string key = info.Key; return new CommandResult(repository.GetValue(key)); }
/// <summary> /// Add a new element to the HashTable. /// </summary> /// <param name="commandInfo"><see cref="CommandInfo"/> to be added.</param> private void add(CommandInfo commandInfo) { int index = hashFunction(commandName: commandInfo.getName()); if (array[index] != null) { index = collisionHandler(index: index); } array[index] = commandInfo; }
public void CreateCommandWithoutParameters() { CommandInfo info = new CommandInfo("get", "users:1:name", null); Assert.AreEqual("get", info.Verb); Assert.AreEqual("users:1:name", info.Key); Assert.IsNull(info.Parameters); }
public void AsyncCommand(string cmd,string parameter) { var commandInfo = new CommandInfo { Command = cmd, Parameter = parameter}; var bw = new BackgroundWorker(); bw.DoWork += AsyncCommandWorker; bw.RunWorkerAsync(commandInfo); }
public void TestRefreshState() { var attacher = new Mock<IAttacher>(); CommandInfo ci = new CommandInfo(); ci.AttachTo(attacher.Object); ci.RefreshState(); attacher.Verify(a => a.RefreshState(), Times.Once()); }
public CommandResult Process(CommandInfo info, Repository repository) { info.CheckArity(1); string key = info.Key; object value = info.Parameters[0]; repository.SetValue(key, value); return ok; }
public void CreateCommandWithParameters() { CommandInfo info = new CommandInfo("set", "users:1:id", new object[] { 1ul }); Assert.AreEqual("set", info.Verb); Assert.AreEqual("users:1:id", info.Key); Assert.IsNotNull(info.Parameters); Assert.AreEqual(1, info.Parameters.Count); Assert.AreEqual(1ul, info.Parameters[0]); }
//PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.ClearCommand clearCommand= command.clearCommand; cmdInfo.FlagMap = new BitSet((byte)clearCommand.flag); cmdInfo.RequestId = clearCommand.requestId.ToString(); return cmdInfo; }
//PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.CountCommand countCommand = command.countCommand; cmdInfo.RequestId = countCommand.requestId.ToString(); return cmdInfo; }
/// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name = "command">The string that will make the command execute</param> /// <param name = "commandHelp">The message that will show the user how to use the command</param> /// <param name = "info">Any information about how the command works or what it does</param> /// <param name = "fn"></param> public void AddCommand(string command, string commandHelp, string infomessage, CommandDelegate fn) { CommandInfo info = new CommandInfo{ command = command, commandHelp = commandHelp, info = infomessage, fn = new List<CommandDelegate> {fn} }; tree.AddCommand(info); }
//PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); //HACK:notifMask Alachisoft.NCache.Common.Protobuf.RegisterNotifCommand registerNotifCommand = command.registerNotifCommand; cmdInfo.RegNotifs = registerNotifCommand.notifMask; cmdInfo.RequestId = registerNotifCommand.requestId.ToString(); cmdInfo.datafilter = registerNotifCommand.datafilter; cmdInfo.sequence = registerNotifCommand.sequence; return cmdInfo; }
//PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.GetRunningServersCommand getRunningServerCommand = command.getRunningServersCommand; cmdInfo.CacheId = getRunningServerCommand.cacheId; cmdInfo.IsDotNetClient = getRunningServerCommand.isDotnetClient; cmdInfo.RequestId = getRunningServerCommand.requestId.ToString(); return cmdInfo; }
private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.AddAttributeCommand addAttributeCommand = command.addAttributeCommand; cmdInfo.ExpHint = Alachisoft.NCache.Caching.Util.ProtobufHelper.GetExpirationHintObj(addAttributeCommand.absExpiration, 0, serializationContext); cmdInfo.Key = addAttributeCommand.key; cmdInfo.RequestId = addAttributeCommand.requestId.ToString(); return cmdInfo; }
public void TestExecute() { Mock<ICommand> testCommand = new Mock<ICommand>(); testCommand.Setup(c => c.CanExecute()).Returns(true); CommandInfo ci = new CommandInfo(); ci.Executor(testCommand.Object); ci.Execute(); testCommand.Verify(c => c.Execute(), Times.Once()); }
public void TestExecuteWhenCanExecuteIsFalse() { Mock<ICommand> testCommand = new Mock<ICommand>(); testCommand.Setup(c => c.CanExecute()).Returns(false); CommandInfo ci = new CommandInfo(); ci.Executor(testCommand.Object); ci.Execute(); testCommand.Verify(c => c.Execute(), Times.Never()); }
/// <summary> /// 增加一条数据 /// </summary> public int Add(Model.users.user_amount_log model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into " + databaseprefix + "user_amount_log("); strSql.Append("user_id,user_name,type,order_no,trade_no,payment_id,value,remark,status,add_time,complete_time)"); strSql.Append(" values ("); strSql.Append("@user_id,@user_name,@type,@order_no,@trade_no,@payment_id,@value,@remark,@status,@add_time,@complete_time)"); strSql.Append(";set @ReturnValue= @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@user_id", SqlDbType.Int,4), new SqlParameter("@user_name", SqlDbType.NVarChar,100), new SqlParameter("@type", SqlDbType.NVarChar,50), new SqlParameter("@order_no", SqlDbType.NVarChar,100), new SqlParameter("@trade_no", SqlDbType.NVarChar,100), new SqlParameter("@payment_id", SqlDbType.Int,4), new SqlParameter("@value", SqlDbType.Decimal,5), new SqlParameter("@remark", SqlDbType.NVarChar,500), new SqlParameter("@status", SqlDbType.TinyInt,1), new SqlParameter("@add_time", SqlDbType.DateTime), new SqlParameter("@complete_time", SqlDbType.DateTime), new SqlParameter("@ReturnValue",SqlDbType.Int)}; parameters[0].Value = model.user_id; parameters[1].Value = model.user_name; parameters[2].Value = model.type; parameters[3].Value = model.order_no; parameters[4].Value = model.trade_no; parameters[5].Value = model.payment_id; parameters[6].Value = model.value; parameters[7].Value = model.remark; parameters[8].Value = model.status; parameters[9].Value = model.add_time; parameters[10].Value = model.complete_time; parameters[11].Direction = ParameterDirection.Output; List<CommandInfo> sqllist = new List<CommandInfo>(); CommandInfo cmd = new CommandInfo(strSql.ToString(), parameters); sqllist.Add(cmd); if (model.status > 0) { StringBuilder strSql2 = new StringBuilder(); strSql2.Append("update " + databaseprefix + "users set amount=amount+" + model.value); strSql2.Append(" where id=@id"); SqlParameter[] parameters2 = { new SqlParameter("@id", SqlDbType.Int,4)}; parameters2[0].Value = model.user_id; cmd = new CommandInfo(strSql2.ToString(), parameters2); sqllist.Add(cmd); } DbHelperSQL.ExecuteSqlTranWithIndentity(sqllist); return (int)parameters[11].Value; }
/// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="command">The string that will make the command execute</param> /// <param name="commandHelp">The message that will show the user how to use the command</param> /// <param name="infomessage">Any information about how the command works or what it does</param> /// <param name="fn"></param> /// <param name="requiresAScene">Whether this command requires a scene to be fired</param> /// <param name="fireOnceForAllScenes">Whether this command will only be executed once if there is no current scene</param> public void AddCommand (string command, string commandHelp, string infomessage, CommandDelegate fn, bool requiresAScene, bool fireOnceForAllScenes) { CommandInfo info = new CommandInfo { command = command, commandHelp = commandHelp, info = infomessage, fireOnceForAllScenes = fireOnceForAllScenes, requiresAScene = requiresAScene, fn = new List<CommandDelegate> { fn } }; tree.AddCommand (info); }
public void InterceptCommand(Guid transactionId, Type entityType, CommandInfo commandInfo, IDbCommand dbCommand) { string message = transactionId.ToString() + " - " + commandInfo.ToString(); if (dbCommand != null) { message += ": " + dbCommand.CommandText; for (int index = 0; index < dbCommand.Parameters.Count; index++) { if (index == 0) message += "\r\n "; IDbDataParameter parameter = dbCommand.Parameters[index] as IDbDataParameter; message += parameter.ParameterName + " = " + parameter.Value + ", "; } } this.log.Info(message); }
//PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.UnRegisterKeyNotifCommand unRegisterKeyNotifCommand = command.unRegisterKeyNotifCommand; cmdInfo.Key = unRegisterKeyNotifCommand.key; cmdInfo.RemoveCallbackId = (short)unRegisterKeyNotifCommand.removeCallbackId; cmdInfo.RequestId = unRegisterKeyNotifCommand.requestId.ToString(); cmdInfo.UpdateCallbackId = (short)unRegisterKeyNotifCommand.updateCallbackId; return cmdInfo; }
private static void CommandEnableTableRevise(List<CommandInfo> commandStates) { var count = commandStates.Count; for (int i = 0; i < count; i++) { var name = commandStates[i].Command.Name; if (name != "待機" && name != "魔法" && name != "退却") { // HACK: より良い見分け方を commandStates[i] = new CommandInfo(commandStates[i].Command, false); } } }
public ICommandInfo GetCommandInfo(string commandName) { Argument.IsNotNull(() => commandName); if (!_commandInfo.ContainsKey(commandName)) { var inputGesture = _commandManager.GetInputGesture(commandName); _commandInfo[commandName] = new CommandInfo(commandName, inputGesture); } return _commandInfo[commandName]; }
public CalculatorBot(string token) : base("calculator", token) { var command = new CommandInfo("/start"); command.StaticAcceptMessage = "Ok you started the calculator"; Configuration.Commands.Add(command); Configuration.StaticUnknownCommandMessage = "Unknown command. Please try another command. Send /start to get a list of available comands."; var command2 = new CommandInfo("/newbrand"); command2.StaticAcceptMessage = "New brand is saved."; var parameter = new ParameterInfo() { Name = "Name", Type = ParameterTypes.Text, Optional = false, StaticPrompt = "Ok, enter new brand name." }; command2.Parameters.Add(parameter); Configuration.Commands.Add(command2); }
// Jeff Lanning ([email protected]): Added overload for OPath support public IDataReader GetDataReader(Type entityType, CommandInfo commandInfo, CompiledQuery query, object[] parameterValues) { IDbConnection conn = null; try { conn = ProviderFactory.GetConnection(this.connection, this.provider); IDbCommand cmd = CreateDbCommand(Guid.NewGuid(), entityType, commandInfo, conn, query, parameterValues); cmd.Connection.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch { if( conn != null ) conn.Close(); throw; } }
public IDataReader GetDataReader(Type entityType, CommandInfo commandInfo, out IDbCommand dbCommand, string sqlStatement, params Parameter[] parameters) { IDbConnection connection = null; try { connection = ProviderFactory.GetConnection(this.connection, this.provider); dbCommand = CreateDbCommand(Guid.NewGuid(), entityType, commandInfo, connection, sqlStatement, parameters); connection.Open(); // Must Close DataReader to Close Connection return dbCommand.ExecuteReader(CommandBehavior.CloseConnection); } catch { if (connection != null) { connection.Close(); } throw; } }
public int ExecuteCommand(Type entityType, CommandInfo commandInfo, string sqlStatement, params Parameter[] parameters) { int output = 0; // Success if any Rows are Affected using (IDbConnection connection = ProviderFactory.GetConnection(this.connection, this.provider)) { IDbCommand command = CreateDbCommand(Guid.NewGuid(), entityType, commandInfo, connection, sqlStatement, parameters); connection.Open(); // Connection will be Closed in all Cases output = command.ExecuteNonQuery(); this.SetOutputParameters(command, parameters); } return output; }
void IInitializable.Initialize() { if (CommandService == null) return; if (Deci4pTargetProvider.SdkInstalled) { var cmdInfo = new CommandInfo( CommandTag.VitaNeighborhood, null, null, "Edit Vita Target in Neighborhood".Localize(), "Edit Vita Target in Neighborhood".Localize()); cmdInfo.ShortcutsEditable = false; CommandService.RegisterCommand(cmdInfo, this); } foreach (var targetProvider in TargetProviders) { if (targetProvider.CanCreateNew) { string addCmdTag = GetAddNewCommandName(targetProvider.Name); CommandService.RegisterCommand( new CommandInfo( addCmdTag, null, null, addCmdTag, "Creates a new target".Localize()), this); m_addTargetsCmdTags.Add(addCmdTag); string remCmdTag = GetRemoveCommandName(targetProvider.Name); CommandService.RegisterCommand( new CommandInfo( remCmdTag, null, null, remCmdTag, "Remove selected target".Localize()), this); m_removeTargetsCmdTags.Add(remCmdTag); } } }
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var commandInfo = default(CommandInfo<object, object>); if (values != default(object[])) { commandInfo = new CommandInfo<object, object> { Input = values[0], Result = values[1] }; } return commandInfo; }
protected async void UpdateRemove(CommandInfo item) { await TestCommand(Commands.Remove, item); }
void UpdateSortSelectedLines(CommandInfo ci) { ci.Enabled = GetTextEditorData().IsMultiLineSelection; }
protected override void Update(CommandInfo info) { info.Enabled = IdeApp.Workbench.ActiveDocument?.Editor != null; }
/// <summary> /// 删除一条数据 /// </summary> public bool Delete(int id) { //获取用户旧数据 Model.users model = GetModel(id); if (model == null) { return(false); } List <CommandInfo> sqllist = new List <CommandInfo>(); //删除积分记录 StringBuilder strSql1 = new StringBuilder(); strSql1.Append("delete from " + databaseprefix + "user_point_log "); strSql1.Append(" where user_id=@id"); SqlParameter[] parameters1 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters1[0].Value = id; CommandInfo cmd = new CommandInfo(strSql1.ToString(), parameters1); sqllist.Add(cmd); //删除金额记录 StringBuilder strSql2 = new StringBuilder(); strSql2.Append("delete from " + databaseprefix + "user_amount_log "); strSql2.Append(" where user_id=@id"); SqlParameter[] parameters2 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters2[0].Value = id; cmd = new CommandInfo(strSql2.ToString(), parameters2); sqllist.Add(cmd); //删除附件购买记录 StringBuilder strSql3 = new StringBuilder(); strSql3.Append("delete from " + databaseprefix + "user_attach_log"); strSql3.Append(" where user_id=@id"); SqlParameter[] parameters3 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters3[0].Value = id; cmd = new CommandInfo(strSql3.ToString(), parameters3); sqllist.Add(cmd); //删除短消息 StringBuilder strSql4 = new StringBuilder(); strSql4.Append("delete from " + databaseprefix + "user_message "); strSql4.Append(" where post_user_name=@post_user_name or accept_user_name=@accept_user_name"); SqlParameter[] parameters4 = { new SqlParameter("@post_user_name", SqlDbType.NVarChar, 100), new SqlParameter("@accept_user_name", SqlDbType.NVarChar, 100) }; parameters4[0].Value = model.user_name; parameters4[1].Value = model.user_name; cmd = new CommandInfo(strSql4.ToString(), parameters4); sqllist.Add(cmd); //删除申请码 StringBuilder strSql5 = new StringBuilder(); strSql5.Append("delete from " + databaseprefix + "user_code "); strSql5.Append(" where user_id=@id"); SqlParameter[] parameters5 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters5[0].Value = id; cmd = new CommandInfo(strSql5.ToString(), parameters5); sqllist.Add(cmd); //删除登录日志 StringBuilder strSql6 = new StringBuilder(); strSql6.Append("delete from " + databaseprefix + "user_login_log "); strSql6.Append(" where user_id=@id"); SqlParameter[] parameters6 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters6[0].Value = id; cmd = new CommandInfo(strSql6.ToString(), parameters6); sqllist.Add(cmd); //删除OAuth授权用户信息 StringBuilder strSql8 = new StringBuilder(); strSql8.Append("delete from " + databaseprefix + "user_oauth "); strSql8.Append(" where user_id=@id"); SqlParameter[] parameters8 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters8[0].Value = id; cmd = new CommandInfo(strSql8.ToString(), parameters8); sqllist.Add(cmd); //删除用户充值表 StringBuilder strSql9 = new StringBuilder(); strSql9.Append("delete from " + databaseprefix + "user_recharge "); strSql9.Append(" where user_id=@id"); SqlParameter[] parameters9 = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters9[0].Value = id; cmd = new CommandInfo(strSql9.ToString(), parameters9); sqllist.Add(cmd); //删除用户主表 StringBuilder strSql = new StringBuilder(); strSql.Append("delete from " + databaseprefix + "users "); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int, 4) }; parameters[0].Value = id; cmd = new CommandInfo(strSql.ToString(), parameters); sqllist.Add(cmd); int rowsAffected = DbHelperSQL.ExecuteSqlTran(sqllist); if (rowsAffected > 0) { return(true); } else { return(false); } }
// Override the CheckPermissions method public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { try { var config = (IConfig)services.GetService(typeof(IConfig)); var roles = new List <string>(); if (context.Channel is ISocketPrivateChannel) { var guilds = await context.Client.GetGuildsAsync(); foreach (var guild in guilds) { var user = await guild.GetUserAsync(context.User.Id); roles.AddRange(guild.Roles.Where(x => user.RoleIds.Contains(x.Id)).Select(x => x.Name)); } } else { var user = await context.Guild.GetUserAsync(context.User.Id); roles.AddRange(context.Guild.Roles.Where(x => user.RoleIds.Contains(x.Id)).Select(x => x.Name)); } roles = roles.Distinct().ToList(); var froles = GetFeatureRoles(config, "commands", AccessControlName); if (!(froles?.Length > 0)) { return(PreconditionResult.FromError(CommandDisabledErrorString)); } if (!HasFeatureAccess(froles, roles.ToArray())) { return(PreconditionResult.FromError("The user does not have access to this command!")); } var croles = froles?.Intersect(roles).ToArray() ?? new string[] { }; var proles = GetFeatureRoles(config, "channels", context.Channel is ISocketPrivateChannel ? "private" : "public") ?? new string[] { }; return(proles.Intersect(croles).Any() ? PreconditionResult.FromSuccess() : PreconditionResult.FromError( $"The user must send this command in {(context.Channel is ISocketPrivateChannel ? "private" : "public")}!")); } catch (Exception ex) { Logging.LogException("Exception when checking command permissions", ex, GetType(), LogLevel.ERROR, ExceptionLevel.Unhandled); return(PreconditionResult.FromError($"Permission check failed with exception: {ex.Message}")); } }
protected async void UpdateLog(CommandInfo item) { await TestCommand(Commands.Log, item); }
/// <summary> /// Gets the attribute, if found, from the current command. /// </summary> /// <typeparam name="T">The attribute's type.</typeparam> /// <param name="command">>The current command.</param> /// <returns>The attribute if found, otherwise null.</returns> public static T GetAttribute <T>(this CommandInfo command) where T : Attribute { return(command.Attributes.Where(a => (a as T) != null).Select(a => a as T).FirstOrDefault()); }
/// <summary> /// Gets a list of matching commands /// </summary> /// <param name="pattern">Command pattern.</param> /// <param name="commandOrigin"></param> /// <param name="context"></param> /// <param name="rediscoverImportedModules"></param> /// <param name="moduleVersionRequired"></param> /// <returns></returns> internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) && ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)) ) ) { foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context)) { // Skip modules that have already been loaded so that we don't expose private commands. string moduleName = Path.GetFileNameWithoutExtension(modulePath); List <PSModuleInfo> modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true); PSModuleInfo tempModuleInfo = null; if (modules.Count != 0) { // 1. We continue to the next module path if we don't want to re-discover those imported modules // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, // then we don't do re-discovery if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers)) { continue; } if (modules.Count == 1) { PSModuleInfo psModule = modules[0]; tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null); tempModuleInfo.SetModuleBase(psModule.ModuleBase); foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name)) { CommandInfo current = null; switch (entry.Value.CommandType) { case CommandTypes.Alias: current = new AliasInfo(entry.Value.Name, definition: null, context); break; case CommandTypes.Function: current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Filter: current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Configuration: current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Cmdlet: current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context); break; default: Dbg.Assert(false, "cannot be hit"); break; } current.Module = tempModuleInfo; yield return(current); } } continue; } } string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath); IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context); if (exportedCommands == null) { continue; } tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null); if (InitialSessionState.IsEngineModule(moduleShortName)) { tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase); } //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved. if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath)); tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath)); } foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands) { string commandName = pair.Key; CommandTypes commandTypes = pair.Value; if (commandPattern.IsMatch(commandName)) { bool shouldExportCommand = true; // Verify that we don't already have it represented in the initial session state. if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName]) { string moduleCompareName = null; if (commandEntry.Module != null) { moduleCompareName = commandEntry.Module.Name; } else if (commandEntry.PSSnapIn != null) { moduleCompareName = commandEntry.PSSnapIn.Name; } if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase)) { if (commandEntry.Visibility == SessionStateEntryVisibility.Private) { shouldExportCommand = false; } } } } if (shouldExportCommand) { if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias) { yield return(new AliasInfo(commandName, null, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Function) == CommandTypes.Function) { yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration) { yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } } } } } } }
protected async void UpdateResolveConflicts(CommandInfo item) { await TestCommand(Commands.ResolveConflicts, item, false); }
protected void OnUpdateRunTest(CommandInfo info) { UnitTest test = GetSelectedTest(); info.Enabled = test != null && test.SourceCodeLocation != null; }
protected void OnUpdateSelectTestInTree(CommandInfo info) { UnitTest test = GetSelectedTest(); info.Enabled = test != null; }
protected void OnUpdateEditorCommand(CommandInfo info) { // ignore command if the editor has no focus info.Bypass = HasFocus == false; }
public void OnEditSolutionUpdate(CommandInfo info) { var solution = (Solution)CurrentNode.DataItem; info.Visible = info.Enabled = !string.IsNullOrEmpty(solution.FileName) && File.Exists(solution.FileName); }
public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo };
protected async void UpdateAdd(CommandInfo item) { await TestCommand(Commands.Add, item); }
protected async void UpdateUnignore(CommandInfo item) { await TestCommand(Commands.Unignore, item); }
protected async void UpdateStatus(CommandInfo item) { await TestCommand(Commands.Status, item); }
protected async void UpdateCreatePatch(CommandInfo item) { await TestCommand(Commands.CreatePatch, item); }
protected async void UpdateDiff(CommandInfo item) { await TestCommand(Commands.Diff, item); }
protected async void UpdateAnnotate(CommandInfo item) { await TestCommand(Commands.Annotate, item); }
/// <summary> /// Returns true if the current command contains the <typeparamref name="T"/> typed attribute, otherwise false. /// </summary> /// <typeparam name="T">The attribute's type.</typeparam> /// <param name="command">The current command.</param> /// <returns>True if the module has the attribute, otherwise false.</returns> public static bool HasAttribute <T>(this CommandInfo command) where T : Attribute { return(command.Attributes.Any(a => (a as T) != null)); }
protected async void UpdateUnlock(CommandInfo item) { await TestCommand(Commands.Unlock, item); }
public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.Channel is not SocketDMChannel) { return(Task.FromResult(PreconditionResult.FromError("This command is only available via DM"))); } return(Task.FromResult(PreconditionResult.FromSuccess())); }
protected async void UpdateRevert(CommandInfo item) { await TestCommand(Commands.Revert, item, false); }
protected override void Update(CommandInfo info) { info.Enabled = true; info.Visible = true; }
protected async void UpdatePublish(CommandInfo item) { await TestCommand(Commands.Publish, item); }
/** * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) * And returns all the deprecation attributes attached to it * * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, * We only process the Parameter beaking change attributes attached only params listed in this list (if present) **/ private static IEnumerable <GenericBreakingChangeAttribute> GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) { List <GenericBreakingChangeAttribute> attributeList = new List <GenericBreakingChangeAttribute>(); if (commandInfo.GetType() == typeof(CmdletInfo)) { var type = ((CmdletInfo)commandInfo).ImplementingType; attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>()); foreach (MethodInfo m in type.GetRuntimeMethods()) { attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>())); } foreach (FieldInfo f in type.GetRuntimeFields()) { attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>()); } foreach (PropertyInfo p in type.GetRuntimeProperties()) { attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast <GenericBreakingChangeAttribute>()); } } else if (commandInfo.GetType() == typeof(FunctionInfo)) { attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast <GenericBreakingChangeAttribute>()); foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) { attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast <GenericBreakingChangeAttribute>()); } } return(invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo))); }
public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.User.Id == Program.Host) { return(Task.FromResult(PreconditionResult.FromSuccess())); } else { return(Task.FromResult(PreconditionResult.FromError("Must be Host."))); } }
public async override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { Guild guild = Program.GuildDictionary[context.Guild.Id]; var guildOwnerId = context.Guild.OwnerId; var userId = context.User.Id; bool userFound; if (userId == guildOwnerId | guild.mods.Contains(userId) | guild.admins.Contains(userId) | guild.superAdmins.Contains(userId)) { return(PreconditionResult.FromSuccess()); } await guild.CheckGuildRoles(context, 1, out userFound); if (userFound) { return(PreconditionResult.FromSuccess()); } else { return(PreconditionResult.FromError("You need to be a mod to user this command")); } }
public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.User is SocketGuildUser) { if (context.Guild.OwnerId == context.User.Id || Program.CheckPermission(context.User.Id, Permission.Mod)) { return(Task.FromResult(PreconditionResult.FromSuccess())); } else { return(Task.FromResult(PreconditionResult.FromError("Must be Mod+."))); } } else { return(Task.FromResult(PreconditionResult.FromError("Must be used in a guild."))); } }