public override int ExecuteNonQuery() { int result = 0; var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null); _profiler.NonQueryExecuting(InternalCommand, context); _stopwatch.Restart(); try { result = InternalCommand.ExecuteNonQuery(); AffectedRows = result; } catch (Exception e) { context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e); _profiler.NonQueryExecuting(InternalCommand, context); throw; } finally { _stopwatch.Stop(); context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, result, _stopwatch.ElapsedMilliseconds, null); _profiler.NonQueryExecuted(InternalCommand, context); } return(result); }
/// <summary> /// Asynchronously execute sql command and await call to function /// </summary> /// <param name="cancellationToken">a cancellation token</param> /// <returns>number of rows affected</returns> public override async System.Threading.Tasks.Task <int> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { SqlDataReader reader = null; try { reader = await InternalCommand.ExecuteReaderAsync(cancellationToken); } catch (SqlException ex) { throw new CommandException(InternalCommand, ex); } _RecordsAffected = reader.RecordsAffected; try { while (!cancellationToken.IsCancellationRequested && await reader.ReadAsync() && _ReadFunc != null && await _ReadFunc(reader)) { ; } } finally { await reader.CloseAsync(); } if (_OnComplete != null) { _OnComplete(this, EventArgs.Empty); } return(_RecordsAffected); }
/// <summary> /// Execute sql command and call function /// </summary> /// <returns>number of records affected</returns> public override int Execute() { SqlDataReader reader = null; try { reader = InternalCommand.ExecuteReader(); } catch (SqlException ex) { throw new CommandException(InternalCommand, ex); } _RecordsAffected = reader.RecordsAffected; try { while (reader.Read() && _ReadFunc != null && _ReadFunc(reader).Result) { ; } } finally { reader.Close(); } if (_OnComplete != null) { _OnComplete(this, EventArgs.Empty); } return(_RecordsAffected); }
/// <summary> /// Connect shell /// </summary> private void ConnectOneShell() { try { //初始化ShellCmder _shellCmder = new ShellCmder(_host, _shellData); //初始化内部命令 _internalCommand = new InternalCommand(_consoleBoxCmder, _shellCmder); //获取系统信息 var info = _shellCmder.GetSysInfo(); var str = string.Format("{0}: {1}\n{2}: {3}", _host.Ui.GetTranslatedText("StrPlatform", "Platform"), info.Platform, _host.Ui.GetTranslatedText("StrCurrentUser", "CurrentUser"), info.CurrentUser); //设置系统平台 _isWin = info.DirSeparators == @"\"; //设置当前目录 _currentDir = info.ShellDir; //cmder的系统平台 _consoleBoxCmder.IsWin = _isWin; //设置提示信息 _consoleBoxCmder.Prompt = _currentDir; _consoleBoxCmder.PrintCommandResult(str); _host.Ui.ShowMsgInStatusBar("Connect success"); } catch (Exception ex) { _consoleBoxCmder.PrintCommandResult(ex.Message); _host.Ui.ShowMsgInStatusBar("Connect failed"); } }
/// <summary> /// Get value of first column in first row from the result set. /// </summary> /// <typeparam name="TResult">Supplied type to be usedin conversion.</typeparam> /// <param name="query">Query to execute.</param> /// <param name="type">Type of command</param> /// <param name="parameters">Parameters to be used with the query.</param> /// <returns>The aquired value after conversion.</returns> public TResult GetScalar <TResult>(string query, CommandType type, params CommandParameter[] parameters) { using (var internalCmd = new InternalCommand(_unitofWork, _conFactory)) { return(internalCmd.ExecScalarCommand <TResult>(query, type, parameters)); } }
public bool Save(string query, CommandType type, T model) { using (var internalCmd = new InternalCommand(_conFactory)) { return(internalCmd.ExecCommand(query, type, model)); } }
/// <summary> /// Connect shell /// </summary> private void ConnectOneShell() { try { //初始化ShellCmder _shellCmder = new ShellCmder(_host,_shellData); //初始化内部命令 _internalCommand = new InternalCommand(_consoleBoxCmder, _shellCmder); //获取系统信息 var info = _shellCmder.GetSysInfo(); var str = string.Format("{0}: {1}\n{2}: {3}", _host.Ui.GetTranslatedText("StrPlatform", "Platform"), info.Platform, _host.Ui.GetTranslatedText("StrCurrentUser", "CurrentUser"), info.CurrentUser); //设置系统平台 _isWin = info.DirSeparators == @"\"; //设置当前目录 _currentDir = info.ShellDir; //cmder的系统平台 _consoleBoxCmder.IsWin = _isWin; //设置提示信息 _consoleBoxCmder.Prompt = _currentDir; _consoleBoxCmder.PrintCommandResult(str); } catch(Exception ex) { _consoleBoxCmder.PrintCommandResult(ex.Message); } }
public bool Delete(string query, CommandType type, params CommandParameter[] parameters) { using (var internalCmd = new InternalCommand(_conFactory)) { return(internalCmd.ExecCommand(query, type, parameters)); } }
/// <summary> /// Constructs the parameter binder with the specified type metadata. The binder is only valid /// for a single instance of a bindable runtime-defined parameter collection and only for the duration of a command. /// </summary> /// /// <param name="target"> /// The target runtime-defined parameter collection that the parameter values will be bound to. /// </param> /// /// <param name="command"> /// An instance of the command so that attributes can access the context. /// </param> /// /// <param name="commandLineParameters"> /// The Command line parameter collection to update... /// </param> /// internal RuntimeDefinedParameterBinder( RuntimeDefinedParameterDictionary target, InternalCommand command, CommandLineParameters commandLineParameters) : base(target, command.MyInvocation, command.Context, command) { // NTRAID#Windows Out Of Band Releases-927103-2006/01/25-JonN foreach (var pair in target) { string key = pair.Key; RuntimeDefinedParameter pp = pair.Value; string ppName = (null == pp) ? null : pp.Name; if (null == pp || key != ppName) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, command.MyInvocation, null, ppName, null, null, ParameterBinderStrings.RuntimeDefinedParameterNameMismatch, "RuntimeDefinedParameterNameMismatch", key); throw bindingException; } } this.CommandLineParameters = commandLineParameters; }
/// <summary> /// Returns a CmdletParameterBinderController for the specified command /// </summary> /// <param name="command"> /// The cmdlet to bind parameters to. /// </param> /// <returns> /// A new instance of a CmdletParameterBinderController. /// </returns> /// <exception cref="ArgumentException"> /// if <paramref name="command"/> is not a Cmdlet. /// </exception> internal ParameterBinderController NewParameterBinderController(InternalCommand command) { Cmdlet cmdlet = command as Cmdlet; if (cmdlet == null) { throw PSTraceSource.NewArgumentException("command"); } ParameterBinderBase parameterBinder; IScriptCommandInfo scriptCommandInfo = CommandInfo as IScriptCommandInfo; if (scriptCommandInfo != null) { parameterBinder = new ScriptParameterBinder(scriptCommandInfo.ScriptBlock, cmdlet.MyInvocation, this._context, cmdlet, CommandScope); } else { parameterBinder = new ReflectionParameterBinder(cmdlet, cmdlet); } _cmdletParameterBinderController = new CmdletParameterBinderController(cmdlet, CommandInfo.CommandMetadata, parameterBinder); return(_cmdletParameterBinderController); }
public override object ExecuteScalar() { object result = null; var context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, null); _profiler.ScalarExecuting(InternalCommand, context); _stopwatch.Restart(); try { result = InternalCommand.ExecuteScalar(); } catch (Exception e) { context = NHProfilerContextProvider.GetLoggedDbCommand(InternalCommand, e); _profiler.ScalarExecuting(InternalCommand, context); throw; } finally { _stopwatch.Stop(); context = NHProfilerContextProvider.GetLoggedResult(InternalCommand, null, result, _stopwatch.ElapsedMilliseconds, null); _profiler.ScalarExecuted(InternalCommand, context); } return(result); }
internal RuntimeDefinedParameterBinder( RuntimeDefinedParameterDictionary target, InternalCommand command, CommandLineParameters commandLineParameters) : base((object)target, command.MyInvocation, command.Context, command) { using (RuntimeDefinedParameterBinder.tracer.TraceConstructor((object)this)) { foreach (string key in target.Keys) { RuntimeDefinedParameter definedParameter = target[key]; string parameterName = definedParameter == null ? (string)null : definedParameter.Name; if (definedParameter == null || key != parameterName) { ParameterBindingException bindingException = new ParameterBindingException(ErrorCategory.InvalidArgument, command.MyInvocation, (Token)null, parameterName, (Type)null, (Type)null, "ParameterBinderStrings", "RuntimeDefinedParameterNameMismatch", new object[1] { (object)key }); RuntimeDefinedParameterBinder.tracer.TraceException((Exception)bindingException); throw bindingException; } } this.CommandLineParameters = commandLineParameters; } }
public void Begin(InternalCommand command) { if (command == null || command.MyInvocation == null) { throw new ArgumentNullException(nameof(command)); } this.Begin(command.MyInvocation.ExpectingInput, command.commandRuntime); }
internal InvocationInfo(InternalCommand command) : this(command.CommandInfo, command.CallingToken) { if (command == null) { return; } this.commandOrigin = command.CommandOrigin; }
internal ParameterBinderBase(System.Management.Automation.InvocationInfo invocationInfo, System.Management.Automation.ExecutionContext context, InternalCommand command) { this.RecordBoundParameters = true; bindingTracer.ShowHeaders = false; this.command = command; this.invocationInfo = invocationInfo; this.context = context; this.engine = context.EngineIntrinsics; }
internal ScriptParameterBinder( ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command) : base(invocationInfo, context, command) { this.script = script != null ? script : throw ScriptParameterBinder.tracer.NewArgumentNullException(nameof(script)); }
protected override void Dispose(bool disposing) { if (disposing && InternalCommand != null) { InternalCommand.Dispose(); } InternalCommand = null; base.Dispose(disposing); }
public IEnumerable <CommandResult> GetData(string query, CommandType type, params CommandParameter[] parameters) { using (var internalCmd = new InternalCommand(_unitofWork, _conFactory)) { foreach (var result in internalCmd.ExecMapperCommand(query, type, parameters)) { yield return(result); } } }
public ProfiledDbCommand Clone() { var tail = InternalCommand as ICloneable; if (tail == null) { throw new NotSupportedException("Underlying " + InternalCommand.GetType().Name + " is not cloneable"); } return(new ProfiledDbCommand((DbCommand)tail.Clone(), _connection, _profiler)); }
private void EnqueueCommand(InternalCommand command) { if (!running) { return; } commandQueue.Enqueue(command); syncEvent.Set(); }
internal override void Prepare(params CommandParameterInternal[] parameters) { InternalCommand command = this.Command; this.ParameterBinderController.BackupDefaultParameters(); foreach (CommandParameterInternal parameter in parameters) { this.arguments.Add(parameter); } this.commandRuntime.ClearOutputAndErrorPipes(); }
internal ProviderIntrinsics(Cmdlet cmdlet) { using (ProviderIntrinsics.tracer.TraceConstructor((object)this)) { this.cmdlet = cmdlet != null ? (InternalCommand)cmdlet : throw ProviderIntrinsics.tracer.NewArgumentNullException(nameof(cmdlet)); this.item = new ItemCmdletProviderIntrinsics(cmdlet); this.childItem = new ChildItemCmdletProviderIntrinsics(cmdlet); this.content = new ContentCmdletProviderIntrinsics(cmdlet); this.property = new PropertyCmdletProviderIntrinsics(cmdlet); this.securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); } }
internal ScriptParameterBinderController( ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, bool useLocalScope) : base(invocationInfo, context, (ParameterBinderBase) new ScriptParameterBinder(script, invocationInfo, context, command), command) { this.useLocalScope = useLocalScope; this.script = script; this.AddUnboundParameters(this.BindableParameters.ReplaceMetadata(script.ParameterMetadata)); }
/// <summary> /// Constructs a ScriptParameterBinder with the specified context. /// </summary> /// <param name="script"> /// The script block representing the code being run /// </param> /// <param name="invocationInfo"> /// The invocation information about the code that is being run. /// </param> /// <param name="context"> /// The context under which the shell function is executing. /// </param> /// <param name="command"> /// The command instance that represents the script in a pipeline. May be null. /// </param> /// <param name="localScope"> /// If binding in a new local scope, the scope to set variables in. If dotting, the value is null. /// </param> internal ScriptParameterBinder( ScriptBlock script, InvocationInfo invocationInfo, ExecutionContext context, InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, command) { Diagnostics.Assert(script != null, "caller to verify script is not null."); this.Script = script; this.LocalScope = localScope; }
internal override ParameterBinderController NewParameterBinderController( InternalCommand command) { if (!(command is Cmdlet cmdlet)) { throw CommandProcessor.tracer.NewArgumentException(nameof(command)); } ParameterBinderBase parameterBinder = !(this.CommandInfo is IScriptCommandInfo commandInfo) ? (ParameterBinderBase) new ReflectionParameterBinder((object)cmdlet, cmdlet) : (ParameterBinderBase) new ScriptParameterBinder(commandInfo.ScriptBlock, cmdlet.MyInvocation, this.context, (InternalCommand)cmdlet); this.cmdletParameterBinderController = new CmdletParameterBinderController(cmdlet, this.CommandInfo.CommandMetadata, parameterBinder); return((ParameterBinderController)this.cmdletParameterBinderController); }
internal ParameterBinderController NewParameterBinderController(InternalCommand command) { if (this.isMiniShell) { this.nativeParameterBinderController = new MinishellParameterBinderController(this.nativeCommand); } else { this.nativeParameterBinderController = new NativeCommandParameterBinderController(this.nativeCommand); } return(this.nativeParameterBinderController); }
internal void EnterNestedPrompt(InternalCommand callingCommand) { LocalRunspace localRunspace = (LocalRunspace)null; try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException ex) { } if (localRunspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if (currentlyRunningPipeline != null && currentlyRunningPipeline == localRunspace.PulsePipeline) { throw new InvalidOperationException(); } } if (this.nestedPromptCount < 0) { throw InternalHost.tracer.NewInvalidOperationException("InternalHostStrings", "EnterExitNestedPromptOutOfSync"); } ++this.nestedPromptCount; this.executionContext.SetVariable("global:NestedPromptLevel", (object)this.nestedPromptCount); InternalHost.PromptContextData promptContextData = new InternalHost.PromptContextData(); promptContextData.SavedContextData = this.executionContext.SaveContextData(); promptContextData.SavedCurrentlyExecutingCommandVarValue = this.executionContext.GetVariable("CurrentlyExecutingCommand"); promptContextData.SavedPSBoundParametersVarValue = this.executionContext.GetVariable("PSBoundParameters"); promptContextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; if (callingCommand != null) { PSObject psObject = PSObject.AsPSObject((object)callingCommand); psObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("CommandInfo", (object)callingCommand.CommandInfo)); psObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("StackTrace", (object)new StackTrace())); this.executionContext.SetVariable("CurrentlyExecutingCommand", (object)psObject); } this.contextStack.Push(promptContextData); this.executionContext.StepScript = false; this.executionContext.PSDebug = 0; this.executionContext.ResetShellFunctionErrorOutputPipe(); this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { this.externalHostRef.Value.EnterNestedPrompt(); } catch { this.ExitNestedPromptHelper(); throw; } }
internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } this.cmdlet = cmdlet; this.item = new ItemCmdletProviderIntrinsics(cmdlet); this.childItem = new ChildItemCmdletProviderIntrinsics(cmdlet); this.content = new ContentCmdletProviderIntrinsics(cmdlet); this.property = new PropertyCmdletProviderIntrinsics(cmdlet); this.securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); }
private void ProcessCommand(InternalCommand command) { // logger.Debug("ProcessInternalCommand(...)"); if (!running) { return; } if (command == null) { return; } }
internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw new NullReferenceException("Cmdlet can't be null."); } _cmdlet = cmdlet; ChildItem = new ChildItemCmdletProviderIntrinsics(cmdlet); Content = new ContentCmdletProviderIntrinsics(cmdlet); Item = new ItemCmdletProviderIntrinsics(cmdlet); Property = new PropertyCmdletProviderIntrinsics(cmdlet); SecurityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); }
public void Execute(object parameter) { if (Action != null) { Action(); } if (Click != null) { Click(this, EventArgs.Empty); } if (InternalCommand != null && InternalCommand.CanExecute(parameter)) { InternalCommand.Execute(parameter); } }
/// <summary> /// Internal proxy for EnterNestedPrompt /// </summary> /// <param name="callingCommand"></param> /// internal void EnterNestedPrompt(InternalCommand callingCommand) { // Ensure we are in control of the pipeline LocalRunspace localRunspace = null; // This needs to be in a try / catch, since the LocalRunspace cast // tries to verify that the host supports interactive sessions. // Tests hosts do not. try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException) { } if (localRunspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline != null) && (currentlyRunningPipeline == localRunspace.PulsePipeline)) throw new InvalidOperationException(); } // NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it // should include setting a bit that indicates that the initialization is complete, and code should be // added here to throw an exception if this function is called before that bit is set. if (NestedPromptCount < 0) { Dbg.Assert(false, "nested prompt counter should never be negative."); throw PSTraceSource.NewInvalidOperationException( InternalHostStrings.EnterExitNestedPromptOutOfSync); } // Increment our nesting counter. When we set the value of the variable, we will replace any existing variable // of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or // 2) is a squatter, and we have claim to clobber it. ++NestedPromptCount; Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount); // On entering a subshell, save and reset values of certain bits of session state PromptContextData contextData = new PromptContextData(); contextData.SavedContextData = Context.SaveContextData(); contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath); contextData.SavedPSBoundParametersVarValue = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath); contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; contextData.LanguageMode = Context.LanguageMode; PSPropertyInfo commandInfoProperty = null; PSPropertyInfo stackTraceProperty = null; object oldCommandInfo = null; object oldStackTrace = null; if (callingCommand != null) { Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match"); // Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want // to expose more and more debug info. We could just populate more and more local variables but that is probably // a lousy approach as it pollutes the namespace. A better way to do it is to add NOTES to the variable value // object. PSObject newValue = PSObject.AsPSObject(callingCommand); commandInfoProperty = newValue.Properties["CommandInfo"]; if (commandInfoProperty == null) { newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo)); } else { oldCommandInfo = commandInfoProperty.Value; commandInfoProperty.Value = callingCommand.CommandInfo; } #if !CORECLR //TODO:CORECLR StackTrace not in CoreCLR stackTraceProperty = newValue.Properties["StackTrace"]; if (stackTraceProperty == null) { newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace())); } else { oldStackTrace = stackTraceProperty.Value; stackTraceProperty.Value = new System.Diagnostics.StackTrace(); } #endif Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); } _contextStack.Push(contextData); Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count"); Context.PSDebugTraceStep = false; Context.PSDebugTraceLevel = 0; Context.ResetShellFunctionErrorOutputPipe(); // Lock down the language in the nested prompt if (Context.HasRunspaceEverUsedConstrainedLanguageMode) { Context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { _externalHostRef.Value.EnterNestedPrompt(); } catch { // So where things really go south is this path; which is possible for hosts (like our ConsoleHost) // that don't return from EnterNestedPrompt immediately. // EnterNestedPrompt() starts // ExitNestedPrompt() called // EnterNestedPrompt throws ExitNestedPromptHelper(); throw; } finally { if (commandInfoProperty != null) { commandInfoProperty.Value = oldCommandInfo; } if (stackTraceProperty != null) { stackTraceProperty.Value = oldStackTrace; } } Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); }