public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; string VariableStart = ""; if ( Arguments.Length > 1 ) { VariableStart = ( (string) Arguments[1].GetArgument() ).ToLower(); } IDictionary EnvironmentVariables = Environment.GetEnvironmentVariables(); SortedList AlphaList = new SortedList( EnvironmentVariables ); foreach ( DictionaryEntry Entry in AlphaList ) { string VariableName = (string) Entry.Key; VariableName = VariableName.ToLower(); if ( VariableName.StartsWith( VariableStart ) ) { string VariableValue = (string) Entry.Value; TermUtil.WriteText( _Terminal, VariableName + "=" + VariableValue + Environment.NewLine ); } } return 0; }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { if ( Arguments.Length < 2 ) { throw new CommandException(); } System.Uri targetUri = new System.Uri( (string) Arguments[1].GetArgument() ); _Terminal.WriteTo( new StringBuilder( "Creating request\n" ), OutputType.StandardOutput ); WebRequest searchRequest = WebRequest.Create( targetUri ); _Terminal.WriteTo( new StringBuilder( "Getting request\n" ), OutputType.StandardOutput ); WebResponse searchResult = searchRequest.GetResponse(); Stream searchStream = searchResult.GetResponseStream(); ICommandArgument[] showArguments = new ICommandArgument[2]; showArguments[0] = Arguments[0]; showArguments[1] = new FileInputArgument( searchStream ); ShowpageCommand showCommand = new ShowpageCommand( _CommandProcessor, _Terminal ); return showCommand.PerformCommand( showArguments, out CommandResult ); }
/// <summary> /// Pass in the result of the command, which will handle calling the completed /// delegate. Just a cleaner shorthand. /// </summary> /// <param name="result">The result of the executed command.</param> public void OnResult(ICommandResult result) { var handler = Completed; if (handler != null) { handler(result); } }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; if ( Arguments.Length < 2 ) { throw new CommandException(); } Stream sourceStream = null; if ( Arguments[1].GetArgument() is string ) { sourceStream = (Stream) new FileStream( (string) Arguments[1].GetArgument(), FileMode.Open, FileAccess.Read ); } else { sourceStream = (Stream) Arguments[1].GetArgument(); } string resultString = GetHtml( sourceStream ); _Terminal.WriteTo( new StringBuilder( resultString ), ConsoleProcessRedirection.OutputType.StandardOutput ); TextCommandResult result = new TextCommandResult( new StringBuilder( resultString ) ); CommandResult = result; return 0; }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; _CommandProcessor.Close(); return 0; }
/// <summary> /// Converts a command result into a new more specialized generic event. /// </summary> /// <param name="result"></param> /// <param name="eventType"></param> /// <returns></returns> public static GenericEvent ConvertToGenericEvent(ICommandResult result, GenericEventType eventType) { return new GenericEvent() { GenericEventType = eventType, Message = result.Message, Stamp = result.Stamp, Scope = result.Scope, Then = result.Then, Now = result.Now }; }
public override int PerformCommand( ICommandArgument [] Arguments, out ICommandResult CommandResult ) { CommandResult = null; if ( Arguments.Length > 1 ) { Directory.SetCurrentDirectory( (string) Arguments[1].GetArgument() ); } return 0; }
public void AddResult(ICommandResult result) { //TODO: Botar um visitor? var unitMoves = result as AUnitMoved; if (unitMoves != null) { m_lockInput = true; StartCoroutine (MoveUnit (unitMoves.From,unitMoves.To)); } }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; System.UriBuilder searchBinding = new System.UriBuilder(); searchBinding.Scheme = "http"; searchBinding.Host = searchServer; searchBinding.Path = searchRoot; string searchQuery = searchQueryPrefix; for ( int currentArgument = 1; currentArgument < Arguments.Length; currentArgument++ ) { if ( currentArgument > 1 ) { searchQuery += "%20"; } searchQuery += Arguments[currentArgument].GetArgument(); } searchBinding.Query = searchQuery; _Terminal.WriteTo( new StringBuilder( searchBinding.ToString() + "\n\n" ), ConsoleProcessRedirection.OutputType.StandardOutput ); PageCommand pageRetriever = new PageCommand( _CommandProcessor, new NullTerminal() ); ICommandArgument[] showArguments = new ICommandArgument[2]; showArguments[0] = Arguments[0]; showArguments[1] = new CommandArgument( searchBinding.ToString() ); pageRetriever.PerformCommand( showArguments, out CommandResult ); string resultString = ( (StringBuilder) CommandResult.GetArgument() ).ToString(); string[] links = FindLinks( resultString ); foreach ( string link in links ) { _Terminal.WriteTo( new StringBuilder( link + "\n\n" ), ConsoleProcessRedirection.OutputType.StandardOutput ); } return 0; }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; Assembly ThisAssembly = Assembly.GetCallingAssembly(); string AppTitle = "Shango"; string AppCompany = "Afrosoft"; Version AppVersion = new Version("0.1.0.10"); object[] Attributes = ThisAssembly.GetCustomAttributes( false ); foreach ( object Attr in Attributes ) { if ( Attr is AssemblyTitleAttribute ) { AppTitle = ( ( AssemblyTitleAttribute ) Attr ).Title; } if ( Attr is AssemblyCompanyAttribute ) { AppCompany = ( ( AssemblyCompanyAttribute ) Attr ).Company; } if ( Attr is AssemblyName ) { AppVersion = ( ( AssemblyName ) Attr ).Version; } } string AppDescription = AppCompany + " " + AppTitle; AppDescription += " [Version " + AppVersion.Major + "." + AppVersion.Minor + "." + AppVersion.Revision + "." + AppVersion.Build + "]"; TermUtil.WriteText( _Terminal, AppDescription + Environment.NewLine ); return 0; }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; string CommandName = (string) Arguments[0].GetArgument(); string CommandArguments = null; if ( Arguments.Length > 1 ) { CommandArguments = (string) Arguments[1].GetArgument(); } for ( int Argument = 2; Argument < Arguments.Length; Argument++ ) { CommandArguments += " " + Arguments[Argument].GetArgument(); } _Process = new RedirectedProcess( _Terminal, this ); _Process.Start( CommandName, CommandArguments ); return 0; }
private void btnConnect_Click(object sender, EventArgs e) { galaxy = galaxies[galaxyList.SelectedItem.ToString()]; if (checkBox1.Checked) { galaxy.Login(textBox1.Text, textBox2.Text); } else { galaxy.Login("", ""); } cmdResult = galaxy.CommandResult; if (!cmdResult.Successful) { MessageBox.Show("Failed to login, have you set your authentication correctly?"); _loggedIn = false; } else { _loggedIn = true; GetAllObjects(); objectView.Columns.Add("original", "Original"); objectView.Columns.Add("renamed", "Re-named"); objectView.Columns.Add("checkedout", "Checked Out"); objectView.Columns.Add("template", "Template"); foreach (var item in myObjects) { objectView.Rows.Add(item.objectName, item.objectRename, item.checkedOut, item.template); } //objectView.DataSource = myObjects; //objectView.Refresh(); } }
public bool AddPrimitive(IAttribute attribute, Primitive prim) { try { ICommandResult result = null; if (IsTemplate) { var template = (ITemplate)GRAccessObject; switch (prim) { case Primitive.scalingextension: _log.Debug($"Adding scaling extension primitice to object {Name} attributes {attribute.Name}"); template.AddExtensionPrimitive("scalingextension", attribute.Name); result = Galaxy.CommandResult; break; } } else { var instance = (IInstance)GRAccessObject; switch (prim) { case Primitive.scalingextension: _log.Debug($"Adding scaling extension primitice to object {Name} attributes {attribute.Name}"); instance.AddExtensionPrimitive("scalingextension", attribute.Name); result = Galaxy.CommandResult; break; } } return(result?.Successful ?? false); } catch (Exception ex) { _log.Error(ex); return(false); } }
public ItemsViewModel( IGeolocatorService geolocator, ILocalNotification localNotification, ICommandResult <List <Item> > loadItemsCommand, ICommandResult <Item> deleteCommand) { this.loadItemsCommand = loadItemsCommand; this.deleteCommand = deleteCommand; this.cancellationTokenSource = new CancellationTokenSource(); this.deleteCommand.Executed += (sender, e) => { var itemFromList = this.Items.First(i => i.Id == this.deleteCommand.Result.Id); this.Items.Remove(itemFromList); }; this.Items = new ObservableCollection <ItemViewModel> (); this.loadItemsCommand.Executed += (sender, e) => { this.IsRefreshing = false; this.Items.Clear(); var placeApi = new GooglePlacesApi(); foreach (var item in this.loadItemsCommand.Result) { var itemViewModel = new ItemViewModel( item, new FindClosestPlacesCommand(placeApi, geolocator, new CategoriesService(), this.cancellationTokenSource.Token), localNotification, deleteCommand, new CategoriesService(), new ApplicationState()); this.Items.Add(itemViewModel); itemViewModel.LoadClosestPlace.Execute(item); } }; }
public IActionResult Post(string commandId, [FromBody] ICommandResult commandResult) { if (!Guid.TryParse(commandId, out Guid commandIdParsed)) { return(new NotFoundResult()); } if (commandResult is null) { return(new BadRequestResult()); } if (commandResult.CommandId != commandIdParsed) { return(new BadRequestResult()); } if (OrchestratorService.Instance.AddCommandResult(commandResult)) { return(new OkResult()); } return(new ConflictResult()); }
public async Task <ICommandResult> Handle(AuthenticateCommand command) { ICommandResult result = null; try { var user = await _userRepository.Authenticate(command.Username, command.Password); if (user != null) { result = new AuthenticateUserResult() { User = new UserDTO(user.Id, user.Username), Token = GetToken(user) }; } } catch (Exception ex) { AddNotification("AuthenticateCommand", ex.Message); } return(result); }
private IView LocateView(ICommandResult result) { Type resultType = result.GetType(); if (resultType == typeof(UserRegistered)) { return(new UserRegisteredView(result as UserRegistered)); } if (resultType == typeof(LoginFailed)) { return(new LoginFailedView(result as LoginFailed)); } if (resultType == typeof(UserLoggedIn)) { return(new UserLoggedInView(result as UserLoggedIn)); } if (resultType == typeof(DepositResult)) { return(new DepositView(result as DepositResult)); } if (resultType == typeof(UserLoggedOut)) { return(new UserLoggedOutView(result as UserLoggedOut)); } if (resultType == typeof(PurchaseResult)) { return(LocatePurchaseView((result as PurchaseResult)?.Report)); } return(new EmptyView()); }
static void Main(string[] args) { Console.WriteLine($"NETTRASH.OrangeData.Nebula Console Util v{Assembly.GetExecutingAssembly().GetName().Version.ToString()}\n"); Arguments prms = new Arguments(args); if (prms.Valid) { ICommand cmd = prms.GetCommand(); if (cmd != null) { ICommandResult result = cmd.Execute(); Console.WriteLine($"Executed: {(result.Success ? "Success" : "Fail")} {result.Message}"); Console.WriteLine($"\n{cmd.Log}"); } else { Console.WriteLine("Invalid command"); } } else { Console.WriteLine($"Invalid arguments\n{prms.Message}\n{prms.GetUseString()}\n"); } }
public async Task ShouldReturnErrorWhenChannelNotFound() { Guid userId = Guid.NewGuid(); var fakeChannelRepository = new Mock <IChannelRepository>(); fakeChannelRepository .Setup(fake => fake.GetById(It.IsAny <Guid>())) .Returns(Task.FromResult <GetChannelByIdQueryResult>(null)); var fakeUserRepository = new Mock <IUserRepository>(); fakeUserRepository .Setup(fake => fake.GetById(It.IsAny <Guid>())) .ReturnsAsync(new GetUserByIdQueryResult { Id = userId, Username = "******" }); var command = new JoinChannelCommand { UserId = userId, ChannelId = Guid.NewGuid() }; var handler = new JoinChannelHandler(fakeChannelRepository.Object, fakeUserRepository.Object); ICommandResult result = await handler.HandleAsync(command); result.Success.Should().BeFalse(); result.Errors.Should().HaveCountGreaterThan(0); handler.Invalid.Should().BeTrue(); command.Valid.Should().BeTrue(); fakeUserRepository.Verify(fake => fake.GetById(It.Is <Guid>(id => id == command.UserId)), Times.Once()); fakeChannelRepository.Verify(fake => fake.GetById(It.Is <Guid>(id => id == command.ChannelId)), Times.Once()); }
protected static void AssertExecutedCommandAgainstSentencesList(ICommandResult args, TextCommandModel primaryCommand, List<String> sentences) { Assert.AreEqual(primaryCommand, args.Now.TextCommands.First(), String.Format("Has not used the '{0}' command", primaryCommand.PluginCommand)); Assert.AreEqual(sentences.Count, args.Now.TextCommandMatches.First().Quotes != null ? args.Now.TextCommandMatches.First().Quotes.Count : 0, "Incorrect numbers of sentences returned"); foreach (String sentence in sentences) { Assert.IsTrue(args.Now.TextCommandMatches.First().Quotes.Contains(sentence) == true, String.Format("Could not find sentence '{0}'", sentence)); } }
protected override async Task <ICommandResult> ExecuteSelectCommandAsync(SqlModelCommand <T> dataCommand, IDbCommand command) { if (TableMapFromDatabase) { dataCommand.GetTableMap(); } dataCommand.BuildSqlCommand(); dataCommand.BuildSqlParameters(command); command.CommandText = dataCommand.SqlCommandText; var items = new List <T>(); ICommandResult result = null; try { int rowsIndex = 0; var sqlCommand = command as SqlCommand; OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select)); using (SqlDataReader r = await sqlCommand.ExecuteReaderAsync()) { Type objectType = typeof(T); if (objectType == typeof(DataTable)) { result = new DataTableCommandResult(); var dt = new DataTable(dataCommand.TableName); dt.Load(r); ((DataTableCommandResult)result).Data = dt; result.RecordsAffected = dt.Rows.Count; return(result); } result = new ModelCommandResult <T>(); var tablename = dataCommand.GetTableAttribute(); while (await r.ReadAsync()) { bool userDataManager = false; var newObject = (T)Activator.CreateInstance(objectType); var dataManager = newObject as IObjectDataManager; if (dataManager != null) { userDataManager = true; } if (dataCommand.TableMap != null) { if (dataCommand.TableName != objectType.Name) { if (tablename == dataCommand.TableName) { if (dataManager != null) { userDataManager = true; } else { userDataManager = false; } } } } if (userDataManager) { dataManager.SetData(r); } else { //TODO Change code to use Reflection.Emit int counter = r.FieldCount; for (int i = 0; i < counter; i++) { var name = r.GetName(i); try { var fieldType = r.GetFieldType(i); var value = r.GetValue(i); if (dataCommand.TableMap != null) { var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name); if (column != null) { if (!string.IsNullOrEmpty(column.PropertyName)) { var prop = objectType.GetProperty(column.PropertyName); if (prop != null) { if (value != DBNull.Value) { prop.SetValue(newObject, value, null); } } } else { TrySetValue(dataCommand, newObject, objectType, name, value); } } else { TrySetValue(dataCommand, newObject, objectType, name, value); } } else { var prop = objectType.GetProperty(name); if (prop != null) { if (value != DBNull.Value) { prop.SetValue(newObject, value, null); } } } } catch (Exception ex) { result.AddError(LogType.Error, string.Format("{1} {0} ", name, dataCommand.TableName), ex); } } } items.Add(newObject); rowsIndex++; } } result.RecordsAffected = rowsIndex; } catch (Exception exception) { result.AddError(LogType.Error, dataCommand.TableName + " " + typeof(T).FullName, exception); } ((ModelCommandResult <T>)result).Data = items; result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText, result.RecordsAffected)); //TODO change class to use base type dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> { Result = (ModelCommandResult <T>)result }); dataCommand.ResetCommand(); result.DataCommand = dataCommand; return(result); }
private static async Task ProcessOutputAsync(IDurableOrchestrationContext functionContext, Provider provider, IProviderCommand command, ICommandResult commandResult) { if (command.ProjectId.HasValue && commandResult is ICommandResult <ProviderOutput> providerOutputResult) { var project = await functionContext .GetProjectAsync(command.ProjectId.Value) .ConfigureAwait(true); using (await functionContext.LockAsync(project).ConfigureAwait(true)) { project = await functionContext .GetProjectAsync(command.ProjectId.Value) .ConfigureAwait(true); var providerReference = project.Type.Providers .SingleOrDefault(pr => pr.Id == provider.Id); if (providerReference != null) { var commandType = command.GetType().Name; var resultProperties = providerOutputResult?.Result?.Properties ?? new Dictionary <string, string>(); if (!providerReference.Metadata.TryAdd(commandType, resultProperties)) { providerReference.Metadata[commandType] = (providerReference.Metadata[commandType] ?? new Dictionary <string, string>()).Override(resultProperties); } project = await functionContext .SetProjectAsync(project) .ConfigureAwait(true); } } } }
private List <Message> GetMessagesTypedError(ICommandResult commandResult) => commandResult?.Messages?.Where(m => m.MessageType != MessageType.None)?.ToList();
private ActionResult GetCorrectlyResult(ICommandResult commandResult) { return(BadRequest(commandResult)); }
protected static void AssertExecutedCommandAgainstTemporalValue(ICommandResult args, TextCommandModel primaryCommand, TimeSpan? period = null, DateTime? delay = null, FuzzyDateTimePattern interval = null) { Assert.AreEqual(primaryCommand, args.Now.TextCommands.First(), String.Format("Has not used the '{0}' command", primaryCommand.PluginCommand)); TextCommandMatchModel match = args.Now.TextCommandMatches.First(); Assert.IsNotNull(match); if (period.HasValue == true) { Assert.IsNotNull(match.Period); Assert.AreEqual(Math.Ceiling(period.Value.TotalSeconds), Math.Ceiling(match.Period.Value.TotalSeconds)); } else { Assert.IsNull(match.Period); } if (delay.HasValue == true) { Assert.IsNotNull(match.Delay); // Note that the delay is generated then passed through to the test, which then needs // to create a DateTime. We allow a little give here of a second or so for execution times. // If it's longer than that then we should be optimizing anyway. // Whatever is passed into this function is generated after the command has been run. Assert.IsTrue(delay.Value - match.Delay.Value < new TimeSpan(TimeSpan.TicksPerSecond * 1)); // Assert.AreEqual(delay.Value, args.After.TextCommandMatches.First().Delay.Value); } else { Assert.IsNull(match.Delay); } if (interval != null) { Assert.IsNotNull(match.Interval); Assert.AreEqual(interval.ToString(), match.Interval.ToString()); } else { Assert.IsNull(match.Interval); } }
/// <summary> /// Serializes the result of the issued command back into the http response for the user. /// </summary> /// <param name="contentType">The content type to serialize the response to</param> /// <param name="response">The existing response packet to be modified with additional data/changes</param> /// <param name="result">The result of the command issued in the request</param> /// <returns>The existing response packet, modified with the result of the command execution.</returns> public static CommandServerPacket CompleteResponsePacket(String contentType, CommandServerPacket response, ICommandResult result) { switch (contentType) { case Mime.ApplicationJavascript: case Mime.TextCss: case Mime.TextHtml: response.Headers.Add(HttpRequestHeader.ContentType, contentType); response.Content = result.Now.Content != null ? result.Now.Content.FirstOrDefault() : ""; response.StatusCode = HttpStatusCode.OK; break; default: response.Headers.Add(HttpRequestHeader.ContentType, Mime.ApplicationJson); using (StringWriter writer = new StringWriter()) { Core.Shared.Serialization.JsonSerialization.Minimal.Serialize(writer, result); response.Content = writer.ToString(); } response.StatusCode = HttpStatusCode.OK; break; } return response; }
private static void AssertPairsAreValid(string expectedMessageRegExp, ICommandResult actual) { MatchCollection matches = Regex.Matches(actual.HumanReadable, expectedMessageRegExp); CollectionAssert.AreEquivalent(JiraConfig.Instance.PairingUsers.Select(userName => FirstUsableName(userName)), DevNamesFrom(matches[0].Groups)); }
private static IContext PipedContextFor(IPlugin plugin, IUser user, string commandLine, ICommandResult result) { var passedArguments = CommandParameters(commandLine); return result.PipeThrough(passedArguments, pipedArgs => new Context(user, plugin, pipedArgs)); }
private static ICommandResult ProcessCommand(IUser user, IPlugin plugin, string commandLine, ICommandResult previousResullt) { try { return SafeProcessCommand(user, plugin, commandLine, previousResullt); } catch(Exception ex) { return CommandResult.Exception(ex); } }
private static ICommandResult SafeProcessCommand(IUser user, IPlugin plugin, string commandLine, ICommandResult previousResullt) { var ctx = PipedContextFor(plugin, user, commandLine, previousResullt); return plugin.ExecuteCommand(GetCommandName(commandLine), ctx); }
public WalkVisitor(Point target) { m_target = target; Result = new EmptyResult(); }
public AplicativoController(IAplicativoRepository aplicativoRepository, IMediatorHandler mediatorHandler, IDesenvolvedorRepository desenvolvedorRepository, ICommandResult commandResult) { _aplicativoRepository = aplicativoRepository; _mediatorHandler = mediatorHandler; _commandResult = commandResult; }
protected static void AssertExecutedCommand(ICommandResult args, TextCommandModel primaryCommand) { Assert.AreEqual(primaryCommand, args.Now.TextCommands.First(), String.Format("Has not used the '{0}' command", primaryCommand.PluginCommand)); }
private bool HasMessageTypedError(ICommandResult commandResult) => GetMessagesTypedError(commandResult)?.Any() ?? false;
/// <summary> /// Validates the results of an executed arithmetic command /// </summary> /// <param name="args">The generated event from the already executed command.</param> /// <param name="primaryCommand">The command to check against - the returning primary command must be this</param> /// <param name="value">The value of the arithmetic return. There must be only one value returned.</param> protected static void AssertExecutedCommandAgainstNumericValue(ICommandResult args, TextCommandModel primaryCommand, float value) { Assert.AreEqual(primaryCommand, args.Now.TextCommands.First(), String.Format("Has not used the '{0}' command", primaryCommand.PluginCommand)); Assert.AreEqual(1, args.Now.TextCommandMatches.First().Numeric.Count, "Not exactly one numeric value returned"); Assert.AreEqual(value, args.Now.TextCommandMatches.First().Numeric.FirstOrDefault()); }
/// <summary> /// Validates the results of an executed player/maps combination command /// </summary> /// <param name="args">The generated event from the already executed command.</param> /// <param name="primaryCommand">The command to check against - the returning primary command must be this</param> /// <param name="players">The list of players that must be in the resulting matched players (nothing more, nothing less)</param> /// <param name="maps">The list of maps that must be in the resulting matched maps (nothing more, nothing less)</param> protected static void AssertExecutedCommandAgainstPlayerListMapList(ICommandResult args, TextCommandModel primaryCommand, ICollection<PlayerModel> players, ICollection<MapModel> maps) { Assert.AreEqual(primaryCommand, args.Now.TextCommands.First(), String.Format("Has not used the '{0}' command", primaryCommand.PluginCommand)); Assert.AreEqual(players.Count, args.Now.TextCommandMatches.First().Players != null ? args.Now.TextCommandMatches.First().Players.Count : 0, "Incorrect numbers of players returned"); Assert.AreEqual(maps.Count, args.Now.TextCommandMatches.First().Maps != null ? args.Now.TextCommandMatches.First().Maps.Count : 0, "Incorrect numbers of maps returned"); foreach (PlayerModel player in players) { Assert.IsTrue(args.Now.TextCommandMatches.First().Players.Contains(player) == true, String.Format("Could not find player '{0}'", player.Name)); } foreach (MapModel map in maps) { Assert.IsTrue(args.Now.TextCommandMatches.First().Maps.Contains(map) == true, String.Format("Could not find map '{0}'", map.Name)); } }
/// <summary> /// Execute scan /// </summary> /// <param name="project">Upload project folder</param> /// <param name="scanData"></param> /// <param name="scanId"></param> /// <returns></returns> private ProjectScanStatuses ExecuteScan(Project project, ref CxWSQueryVulnerabilityData[] scanData, ref long scanId) { Logger.Create().Debug("DoScan in"); bool bCancel = false; bool backgroundMode = _scan.LoginResult.AuthenticationData.IsRunScanInBackground == SimpleDecision.Yes; if (_dispatcher == null) { _dispatcher = ServiceLocators.ServiceLocator.GetDispatcher(); } if (_dispatcher != null) { IScanView view = null; var waitEnd = new ManualResetEvent(false); //if was selected "always run in background" checkbox - hide dialog if (!backgroundMode) { ICommandResult commandResult = _dispatcher.Dispatch(_scan); view = ((ScanPresenter)commandResult).View; } _scan.ScanView = view; BackgroundWorkerHelper bg = new BackgroundWorkerHelper(_scan.LoginResult.AuthenticationData.ReconnectInterval * 1000, _scan.LoginResult.AuthenticationData.ReconnectCount); CxWebServiceClient client = new CxWebServiceClient(_scan.LoginResult.AuthenticationData); client.ServiceClient.Timeout = 1800000; bool isIISStoped = false; bool isScanningEror = false; //User click cancel while info dialog was showed if (!bCancel) { ShowScanProgressBar(); ConfigurationResult configuration = _configurationHelper.GetConfigurationList(_scan.LoginResult.SessionId, bg, client); if (configuration == null) { _cancelPressed = true; } if (!configuration.IsSuccesfull) { LoginHelper.DoLogout(); if (client != null) { client.Close(); } if (view != null) { view.CloseView(); } _scan.InProcess = false; return(ProjectScanStatuses.CanceledByUser); } //User click cancel while info dialog was showed if (!bCancel) { byte[] zippedProject = ZipProject(_scan, project, bg); if (!_scan.IsCancelPressed && zippedProject != null) { if (configuration.Configurations.Count > 0) { RunScanResult runScanResult = null; if (!CommonData.IsProjectBound) { if (_uploadSettings.IsPublic) { _scan.IsPublic = SetScanPrivacy(); } runScanResult = RunScan(bg, client, configuration, zippedProject); } else { if (_scan.UploadSettings.IsPublic) { _scan.IsPublic = SetScanPrivacy(); } runScanResult = RunBoundedProjectScan(_scan, bg, client, zippedProject); } if (runScanResult == null || !runScanResult.IsSuccesfull) { bCancel = true; isIISStoped = true; isScanningEror = true; } // Continue if project uploaded succesfull and cancel button while process wasn't pressed if (runScanResult != null && runScanResult.IsSuccesfull) { _scan.RunScanResult = runScanResult; //perform scan work in separated thread to improve UI responsibility System.Threading.ThreadPool.QueueUserWorkItem(delegate(object stateInfo) { try { // Wait while scan operation complete while (true) { StatusScanResult statusScan = UpdateScanStatus(ref bCancel, backgroundMode, view, bg, client, ref isIISStoped); // if scan complete with sucess or failure or cancel button was pressed // operation complete bCancel = bCancel ? bCancel : _scan.WaitForCancel(); if (isIISStoped || bCancel || (statusScan != null && statusScan.RunStatus == CurrentStatusEnum.Finished) || (statusScan != null && statusScan.RunStatus == CurrentStatusEnum.Failed)) { break; } } waitEnd.Set(); } catch (Exception err) { Logger.Create().Error(err.ToString()); // show error waitEnd.Set(); isIISStoped = true; Logger.Create().Debug(err); } if (_scan.ScanView == null || _scan.ScanView.Visibility == false) { var scanStatusBar = new ScanStatusBar(false, "", 0, 0, true); CommonActionsInstance.getInstance().UpdateScanProgress(scanStatusBar); //ObserversManager.Instance.Publish(typeof (ScanStatusBar), scanStatusBar); } }); while (!waitEnd.WaitOne(0, false)) { Application.DoEvents(); Thread.Sleep(10); } } } #region [Scan completed. Open perspective] if (!bCancel && !isIISStoped) { ShowScanData(ref scanData, ref scanId, client); } else { #region [Stop scan in cancel pressed] if (_scan.RunScanResult != null && !isIISStoped) { bg.DoWorkFunc = delegate { if (!isIISStoped) { client.ServiceClient.CancelScan(_scan.LoginResult.SessionId, _scan.RunScanResult.ScanId); } }; bg.DoWork("Stop scan..."); } #endregion } #endregion client.Close(); } else { client.Close(); bCancel = true; } } else { } } else { } if (!backgroundMode && view != null) { view.CloseView(); } if (isIISStoped) { if (isScanningEror) { return(ProjectScanStatuses.Error); } else { return(ProjectScanStatuses.CanceledByUser); } } if (!bCancel) { return(ProjectScanStatuses.Success); } else { if (isScanningEror) { return(ProjectScanStatuses.Error); } else { return(ProjectScanStatuses.CanceledByUser); } } } return(ProjectScanStatuses.CanceledByUser); }
public async Task <TResult> SendCommandResult <TResult>(ICommandResult <TResult> command) { return(await _mediator.Send(command)); }
public static T As <T>(this ICommandResult commandResult) { return((T)commandResult); }
static bool IsDeleteCommandResult(ICommandResult result) => result is OrchestratorProjectDeleteCommandResult || result is OrchestratorProjectUserDeleteCommandResult || result is OrchestratorProviderDeleteCommandResult || result is OrchestratorTeamCloudUserDeleteCommandResult;
public OrchestratorCommandResultMessage(ICommandResult commandResult, Dictionary <Provider, ICommandResult> providerCommandResults) { CommandResult = commandResult; ProviderCommandResults = providerCommandResults; }
public void AddResult(ICommandResult result) { results.Add(result); }
private static async Task <ICommandResult> SwitchCommandAsync(IDurableOrchestrationContext functionContext, ProviderDocument provider, IProviderCommand command, ICommandResult commandResult, ILogger log) { try { await functionContext .AuditAsync(command, commandResult, provider) .ConfigureAwait(true); functionContext.SetCustomStatus($"Switching command", log); var project = await functionContext .GetProjectAsync(command.ProjectId, allowUnsafe : true) .ConfigureAwait(true); functionContext.ContinueAsNew(( new ProviderProjectUpdateCommand ( command.BaseApi, command.User as Model.Data.User, project.PopulateExternalModel(), command.CommandId), provider ) ); } catch (Exception exc) { functionContext.SetCustomStatus($"Switching command failed: {exc.Message}", log, exc); commandResult ??= command.CreateResult(); commandResult.Errors.Add(exc); } return(commandResult); }
protected override ICommandResult ExecuteSelectCommand(SqlModelCommand <T> dataCommand, IDbCommand command) { if (TableMapFromDatabase) { var map = dataCommand.GetTableMap(); if (dataCommand.SelectAll == false) { if (!string.IsNullOrEmpty(map)) { var columns = dataCommand.GetColumnAttributes(); foreach (var columnMap in columns) { bool addColumn = true; if (dataCommand.TableMap == null) { addColumn = false; } var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == columnMap.ColumnName); if (column == null) { addColumn = false; } if (addColumn) { dataCommand.Column(columnMap.ColumnName); } } dataCommand.SelectAll = false; } } } dataCommand.BuildSqlCommand(); dataCommand.BuildSqlParameters(command); command.CommandText = dataCommand.SqlCommandText; var items = new List <T>(); ICommandResult result = null; try { int rowsIndex = 0; OnBeforeCommandExecute(this, new ModelCommandBeforeExecuteEventArgs(dataCommand, command, DataCommandType.Select)); using (SqlDataReader r = command.ExecuteReader() as SqlDataReader) { Type objectType = typeof(T); if (objectType == typeof(DataTable)) { result = new DataTableCommandResult(); var dt = new DataTable(dataCommand.TableName); dt.Load(r); ((DataTableCommandResult)result).Data = dt; result.RecordsAffected = dt.Rows.Count; foreach (var item in dataCommand.TableMap.ColumnMaps) { if (item.ColumnName != item.PropertyName) { foreach (System.Data.DataColumn column in dt.Columns) { if (item.ColumnName == column.ColumnName) { if (!string.IsNullOrEmpty(item.PropertyName)) { if (item.IsMapped) { column.ColumnName = item.PropertyName; } } } } } } return(result); } result = new ModelCommandResult <T>(); var tablename = dataCommand.GetTableAttribute(); var accessor = TypeAccessor.Create(objectType); ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes); TrinityActivator.ObjectActivator <T> createdActivator = TrinityActivator.GetActivator <T>(ctor); while (r.Read()) { bool userDataManager = false; //https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/ var newObject = createdActivator(); //var newObject = (T)Activator.CreateInstance(objectType); var dataManager = newObject as IObjectDataManager; if (dataCommand.TableMap != null) { if (dataCommand.TableName != objectType.Name) { if (tablename == dataCommand.TableName) { if (dataManager != null) { userDataManager = true; } else { userDataManager = false; } } } else { if (dataManager != null) { userDataManager = true; } } } if (userDataManager) { dataManager.SetData(r); } else { //TODO Change code to use Reflection.Emit int counter = r.FieldCount; for (int i = 0; i < counter; i++) { var name = r.GetName(i); try { var fieldType = r.GetFieldType(i); var value = r.GetValue(i); if (dataCommand.TableMap != null) { var column = dataCommand.TableMap.ColumnMaps.FirstOrDefault(m => m.ColumnName == name); if (column != null) { if (!string.IsNullOrEmpty(column.PropertyName)) { try { if (value != DBNull.Value) { accessor[newObject, column.PropertyName] = value; } } catch (Exception e) { try { if (value != DBNull.Value) { var prop = objectType.GetProperty(column.PropertyName); accessor[newObject, column.PropertyName] = value.ConvertValue(prop); } } catch (Exception exception) { var prop = objectType.GetProperty(column.PropertyName); if (prop != null) { if (value != DBNull.Value) { try { prop.SetValue(newObject, value, null); } catch (Exception) { prop.SetValue(newObject, value.ConvertValue(prop), null); } } } } } } else { try { if (value != DBNull.Value) { accessor[newObject, name] = value; } } catch (Exception e) { TrySetValue(dataCommand, newObject, objectType, name, value); } } } else { try { if (value != DBNull.Value) { accessor[newObject, name] = value; } } catch (Exception e) { TrySetValue(dataCommand, newObject, objectType, name, value); } } } else { var prop = objectType.GetProperty(name); if (prop != null) { if (value != DBNull.Value) { prop.SetValue(newObject, value, null); } } } } catch (Exception ex) { result.AddError(LogType.Error, string.Format("{1} {0} ", name, dataCommand.TableName), ex); } } } items.Add(newObject); rowsIndex++; } } result.RecordsAffected = rowsIndex; } catch (Exception exception) { result.AddError(LogType.Error, $"{dataCommand.TableName} {dataCommand.SqlCommandText} {typeof(T).FullName}", exception); } ((ModelCommandResult <T>)result).Data = items; result.AddMessage(string.Format("{0} executed with {1} rows affected", dataCommand.SqlCommandText, result.RecordsAffected)); //TODO change class to use base type dataCommand.OnCommandExecuted(new ModelCommandExecutedEventArgs <T> { Result = (ModelCommandResult <T>)result }); dataCommand.ResetCommand(); result.DataCommand = dataCommand; return(result); }
private static async Task <ICommandResult> ProcessCommandAsync(IDurableOrchestrationContext functionContext, ProviderDocument provider, IProviderCommand command, ICommandResult commandResult, ILogger log) { var commandMessage = default(ICommandMessage); var commandCallback = default(string); try { functionContext.SetCustomStatus($"Acquire callback url", log); commandCallback = await functionContext .CallActivityWithRetryAsync <string>(nameof(CallbackUrlGetActivity), (functionContext.InstanceId, command)) .ConfigureAwait(true); commandMessage = new ProviderCommandMessage(command, commandCallback); if (!(command is ProviderRegisterCommand || provider.Registered.HasValue)) { log.LogInformation($"Register provider {provider.Id} for command {command.CommandId}"); await functionContext .RegisterProviderAsync(provider, true) .ConfigureAwait(true); } if (!string.IsNullOrEmpty(command.ProjectId) && provider.PrincipalId.HasValue) { log.LogInformation($"Enable provider {provider.Id} for command {command.CommandId}"); await functionContext .CallActivityWithRetryAsync(nameof(ProjectResourcesAccessActivity), (command.ProjectId, provider.PrincipalId.Value)) .ConfigureAwait(true); } functionContext.SetCustomStatus($"Augmenting command", log); command = await AugmentCommandAsync(functionContext, provider, command) .ConfigureAwait(true); await functionContext .AuditAsync(command, commandResult, provider) .ConfigureAwait(true); try { functionContext.SetCustomStatus($"Sending command", log); commandResult = await functionContext .CallActivityWithRetryAsync <ICommandResult>(nameof(CommandSendActivity), (provider, commandMessage)) .ConfigureAwait(true); } catch (RetryCanceledException) { commandResult = await functionContext .CallActivityWithRetryAsync <ICommandResult>(nameof(CommandResultFetchActivity), (provider, commandMessage)) .ConfigureAwait(true); } finally { await functionContext .AuditAsync(command, commandResult, provider) .ConfigureAwait(true); } if (commandResult.RuntimeStatus.IsActive()) { var commandTimeout = (commandResult.Timeout > TimeSpan.Zero && commandResult.Timeout < CommandResult.MaximumTimeout) ? commandResult.Timeout // use the timeout reported back by the provider : CommandResult.MaximumTimeout; // use the defined maximum timeout functionContext.SetCustomStatus($"Waiting for command result", log); commandResult = await functionContext .WaitForExternalEvent <ICommandResult>(command.CommandId.ToString(), commandTimeout, null) .ConfigureAwait(true); if (commandResult is null) { // provider ran into a timeout // lets give our provider a last // chance to return a command result commandResult = await functionContext .CallActivityWithRetryAsync <ICommandResult>(nameof(CommandResultFetchActivity), (provider, commandMessage)) .ConfigureAwait(true); if (commandResult.RuntimeStatus.IsActive()) { // the last change result still doesn't report a final runtime status // escalate the timeout by throwing an appropriate exception throw new TimeoutException($"Provider '{provider.Id}' ran into timeout ({commandTimeout})"); } } } } catch (Exception exc) { functionContext.SetCustomStatus($"Sending command failed: {exc.Message}", log, exc); commandResult ??= command.CreateResult(); commandResult.Errors.Add(exc.AsSerializable()); } finally { await functionContext .AuditAsync(command, commandResult, provider) .ConfigureAwait(true); await ProcessOutputAsync(functionContext, provider, command, commandResult) .ConfigureAwait(true); } return(commandResult); }
protected List<string> ShortCommandList(ICommandResult e) { return this.Commands.Select(x => x.Commands.FirstOrDefault()).ToList(); }
public override void WalkCommand (IBoardWalkCommand command) { var index = command.PossiblePoints.IndexOf (m_target); if(index >= 0) Result = command.Exec (index); }
public void AddResult(ICommandResult result) { this.results.Add(result); }
public abstract int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult );