public async Task <long> GetEventsAsync(string actorName, long indexStart, long indexEnd, Action <object> callback) { using var connection = new SqliteConnection(ConnectionString); await connection.OpenAsync(); using var selectCommand = CreateCommand( connection, "SELECT EventIndex, EventData FROM Events WHERE ActorName = $ActorName AND EventIndex >= $IndexStart AND EventIndex <= $IndexEnd ORDER BY EventIndex ASC", ("$ActorName", actorName), ("$IndexStart", indexStart), ("$IndexEnd", indexEnd) ); var indexes = new List <long>(); using var reader = await selectCommand.ExecuteReaderAsync(); while (await reader.ReadAsync()) { indexes.Add(Convert.ToInt64(reader["EventIndex"])); callback(JsonConvert.DeserializeObject <object>(reader["EventData"].ToString(), AutoTypeSettings)); } return(indexes.Any() ? indexes.LastOrDefault() : -1); }
public async Task <(object Snapshot, long Index)> GetSnapshotAsync(string actorName) { object snapshot = null; long index = 0; using var connection = new SqliteConnection(ConnectionString); await connection.OpenAsync(); using var selectCommand = CreateCommand( connection, "SELECT SnapshotIndex, SnapshotData FROM Snapshots WHERE ActorName = $ActorName ORDER BY SnapshotIndex DESC LIMIT 1", ("$ActorName", actorName) ); using var reader = await selectCommand.ExecuteReaderAsync(); while (await reader.ReadAsync()) { snapshot = JsonConvert.DeserializeObject <object>(reader["SnapshotData"].ToString(), AutoTypeSettings); index = Convert.ToInt64(reader["SnapshotIndex"]); } return(snapshot, index); }
public async Task DeleteSnapshotsAsync(string actorName, long inclusiveToIndex) { using var connection = new SqliteConnection(ConnectionString); await connection.OpenAsync(); using var deleteCommand = CreateCommand( connection, "DELETE FROM Snapshots WHERE ActorName = $actorName AND SnapshotIndex <= $inclusiveToIndex", ("$actorName", actorName), ("$inclusiveToIndex", inclusiveToIndex) ); await deleteCommand.ExecuteNonQueryAsync(); }
public IExecutable ManageCommand(string[] inputArgs) { IExecutable command = null; string commandType = inputArgs[0]; switch (commandType) { case "create": command = new CreateCommand(this.Engine, inputArgs[1], int.Parse(inputArgs[2]), int.Parse(inputArgs[3]), (BehaviorTypes)Enum.Parse(typeof(BehaviorTypes), inputArgs[4]), (AttackTypes)Enum.Parse(typeof(AttackTypes), inputArgs[5])); break; case "attack": command = new AttackCommand(this.Engine, inputArgs[1], inputArgs[2]); break; case "pass": command = new PassCommand(); break; case "status": command = new StatusCommand(this.Engine); break; case "drop": command = new DropCommand(); break; } return command; }
public override void MouseClicked(MouseEventArgs e) { Point clickPos = Mouse.GetPosition(MainWindow.window.levelCanvas); Primitive prim; switch(shapeStr) { case "square": { prim = new PrimitiveRect(pointer, clickPos); pointer.AddPrimitive(prim); CreateCommand createCommand = new CreateCommand(prim); pointer.commands.Add(createCommand); pointer.ChangeTool(new ResizeTool(pointer, prim, clickPos, true, false, true, false, true)); break; } default: { break; } } }
private static bool TryParseCommand(string[] args, ref int index, out CreateCommand func) { func = null; if (index >= args.Length) { Console.WriteLine("Need a command to run"); return false; } var name = args[index]; switch (name) { case "verify": func = (c, s) => new VerifyCommand(c, s); break; case "consumes": func = (c, s) => new ConsumesCommand(RepoData.Create(c, s)); break; case "change": func = (c, s) => new ChangeCommand(RepoData.Create(c, s)); break; case "produces": func = (c, s) => new ProducesCommand(c, s); break; default: Console.Write($"Command {name} is not recognized"); return false; } index++; return true; }
private static bool TryParseCommandLine(string[] args, out ParsedArgs parsedArgs, out CreateCommand func) { func = null; parsedArgs = new ParsedArgs(); // Setup the default values parsedArgs.SourcesPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); var index = 0; if (!TryParseCommon(args, ref index, parsedArgs)) { return false; } if (string.IsNullOrEmpty(parsedArgs.RepoDataPath)) throw new ArgumentException("The -repoDataPath switch is required."); if (!TryParseCommand(args, ref index, out func)) { return false; } parsedArgs.RemainingArgs = index >= args.Length ? Array.Empty<string>() : args.Skip(index).ToArray(); return true; }
public ICommand CreateCommand(string commandName, IEngine engine) { ICommand command = null; Commands name; bool isValidCommandName = System.Enum.TryParse(commandName, out name); if (!isValidCommandName) { throw new ArgumentException("Invalid command name!"); } switch (name) { case Commands.Add: command = new AddCommand(engine); break; case Commands.Create: command = new CreateCommand(engine); break; case Commands.Remove: command = new RemoveCommand(engine); break; case Commands.Print: command = new PrintCommand(engine); break; } return(command); }
public OfferViewModel(Offer offer = null) { OfferDomainObject = offer; CreateCommand = new CreateCommand <Offer>(); DeleteCommand = new DeleteCommand <Offer>(); UpdateCommand = new UpdateCommand <Offer>(); }
public async Task TestEnvVars() { const string Image = "hello-world:latest"; const string Name = "test-env"; string sharedAccessKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("deviceKey")); string fakeConnectionString = $"Hostname=fakeiothub;Deviceid=test;SharedAccessKey={sharedAccessKey}"; try { using (var cts = new CancellationTokenSource(Timeout)) { await Client.CleanupContainerAsync(Name, Image); string createOptions = @"{""Env"": [ ""k1=v1"", ""k2=v2""]}"; var config = new DockerConfig(Image, createOptions); var loggingConfig = new DockerLoggingConfig("json-file"); var module = new DockerModule(Name, "1.0", ModuleStatus.Running, global::Microsoft.Azure.Devices.Edge.Agent.Core.RestartPolicy.OnUnhealthy, config, null, null); IConfigurationRoot configRoot = new ConfigurationBuilder().AddInMemoryCollection( new Dictionary <string, string> { { "EdgeDeviceConnectionString", fakeConnectionString } }).Build(); var deploymentConfigModules = new Dictionary <string, IModule> { [Name] = module }; var systemModules = new SystemModules(null, null); var deploymentConfigInfo = new DeploymentConfigInfo(1, new DeploymentConfig("1.0", new DockerRuntimeInfo("docker", new DockerRuntimeConfig("1.25", string.Empty)), systemModules, deploymentConfigModules)); var configSource = new Mock <IConfigSource>(); configSource.Setup(cs => cs.Configuration).Returns(configRoot); configSource.Setup(cs => cs.GetDeploymentConfigInfoAsync()).ReturnsAsync(deploymentConfigInfo); var credential = new ConnectionStringCredentials("fake"); var identity = new Mock <IModuleIdentity>(); identity.Setup(id => id.Credentials).Returns(credential); ICommand create = await CreateCommand.BuildAsync(Client, module, identity.Object, loggingConfig, configSource.Object, false); await Client.PullImageAsync(Image, cts.Token); // create module using command await create.ExecuteAsync(cts.Token); // check that the environment variables are being returned RuntimeInfoProvider runtimeInfoProvider = await RuntimeInfoProvider.CreateAsync(Client); IEnumerable <ModuleRuntimeInfo> modules = await runtimeInfoProvider.GetModules(cts.Token); var returnedModule = modules.First(m => m.Name == Name) as ModuleRuntimeInfo <DockerReportedConfig>; Assert.NotNull(returnedModule); } } finally { await Client.CleanupContainerAsync(Name, Image); await Client.CleanupContainerAsync("test-filters-external", Image); } }
public async Task <IActionResult> OnPostAsync([FromBody] PlayerCreateDto dto) { if (!ModelState.IsValid) { return(await Task.FromResult(new JsonResult(new { Status = false, ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First() }))); } var userId = _accountContext.UserId; var command = new CreateCommand(dto.Name, dto.Gender, userId, dto.Str, dto.Con, dto.Dex, dto.Int); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content)); return(await Task.FromResult(new JsonResult(new { status = false, errorMessage }))); } return(await Task.FromResult(new JsonResult(new { status = true }))); }
public async Task <FileItemDto> Handle(CreateCommand <FileItemCreateRequest, FileItemDto, FileItem, Guid> request, CancellationToken cancellationToken) { var entity = _mapper.Map <FileItem>(request.Source); entity.CreationTime = DateTime.Now; HybridFileInfo fileInfo; do { entity.Path = PathHelper.NormalizePath(PathGenerator.GeneratePath(entity, _options)); try { fileInfo = await _fileManager.CreateFileFromStreamAsync(entity.Path, request.Source.FileStream); } catch (FileHasExistedException) { throw; } } while (fileInfo == null); await _repository.AddAsync(entity); await _domainEventBus.PublishAsync(new CreatedEvent <FileItem>(entity)); return(_mapper.Map <FileItemDto>(entity)); }
public void ProjectCreate_Execute_WithTemplateReturnsProviderNotInstalled() { _templateWriter.Setup(t => t.Read(It.IsAny <string>())).Returns( @"name: Project 2 models: - name: Product jobs: - name: Default tasks: - name: Generate type: Generate provider: AspNetCoreMvc2" ); var command = new CreateCommand(_console, LoggerMock.GetLogger <CreateCommand>().Object, _consoleReader.Object, _projectService.Object, _providerService.Object, _externalServiceService.Object, _templateWriter.Object) { Name = "Project 2", Client = "Company", Template = "Test" }; var resultMessage = command.Execute(); Assert.Equal("Please register the required providers first by using \"provider register\" command.", resultMessage); }
/// <summary> /// Создание и вызов нужной команды /// </summary> /// <param name="command">название команды</param> /// <returns>Команда</returns> private ICommand CallCommand(string command) { ICommand newCommand = null; switch (command) { case "create": newCommand = new CreateCommand(productCatalog, currentArgs); break; case "list": newCommand = new ListCommand(productCatalog, currentArgs); break; case "delete": newCommand = new DeleteCommand(productCatalog, currentArgs); break; case "add-count": newCommand = new AddCountCommand(productCatalog, currentArgs); break; case "sub-count": newCommand = new SubstractCountCommand(productCatalog, currentArgs); break; case "get-item": newCommand = new GetItemCommand(productCatalog, currentArgs); break; } return(newCommand); }
public void ShouldFailWithUnknownCommand() { var createCommand = new CreateCommand(); var ex = Assert.ThrowsAny <CommandParsingException>(() => createCommand.Execute("test")); Assert.Contains("Unrecognized command or argument 'test'", ex.Message); }
public async Task <Result <Exception, Guid> > Handle(CreateCommand request, CancellationToken cancellationToken) { var entity = _mapper.Map <Scheduling>(request); foreach (var serviceProvidedId in request.ProvidedServices) { var providedServiceCallback = await _providedServiceRepository.GetByIdAsync(serviceProvidedId); if (providedServiceCallback.IsSuccess) { entity.ProvidedServices.Add(providedServiceCallback.Success); } } var employeeCallback = await _employeeRepository.GetByIdAsync(request.EmployeeId); if (employeeCallback.IsFailure) { return(new Exception()); } var entityCreated = await _repository.CreateAsync(entity); if (entityCreated.IsFailure) { return(entityCreated.Failure); } return(entityCreated.Success.Id); }
public override int Run(string[] remainingArguments) { _logger = new Logger(Verbose); var createCommand = new CreateCommand { ConnectionString = ConnectionString, DbName = DbName, Pass = Pass, ScriptDir = ScriptDir, Server = Server, User = User, Logger = _logger, Overwrite = Overwrite }; try { createCommand.Execute(DatabaseFilesPath); } catch (BatchSqlFileException ex) { _logger.Log(TraceLevel.Info, $"{Environment.NewLine}Create completed with the following errors:"); foreach (var e in ex.Exceptions) { _logger.Log(TraceLevel.Info, $"- {e.FileName.Replace("/", "\\")} (Line {e.LineNumber}):"); _logger.Log(TraceLevel.Error, $" {e.Message}"); } return(-1); } catch (SqlFileException ex) { _logger.Log(TraceLevel.Info, $@"{Environment.NewLine}An unexpected SQL error occurred while executing scripts, and the process wasn't completed. {ex.FileName.Replace("/", "\\")} (Line {ex.LineNumber}):"); _logger.Log(TraceLevel.Error, ex.ToString()); return(-1); } catch (Exception ex) { throw new ConsoleHelpAsException(ex.ToString()); } return(0); }
private void NextAction(object o) { TransitionerIndex++; PreviousCommand.RaiseCanExecuteChanged(); NextCommand.RaiseCanExecuteChanged(); CreateCommand.RaiseCanExecuteChanged(); }
public UserViewModel(User user = null) { UserDomainObject = user; CreateCommand = new CreateCommand <User>(); DeleteCommand = new DeleteCommand <User>(); UpdateCommand = new UpdateCommand <User>(); }
private static bool TryParseCommandLine(string[] args, out ParsedArgs parsedArgs, out CreateCommand func) { func = null; parsedArgs = new ParsedArgs(); // Setup the default values var binariesPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(AppContext.BaseDirectory)))); var index = 0; if (!TryParseCommon(args, ref index, parsedArgs)) { return false; } if (!TryParseCommand(args, ref index, out func)) { return false; } parsedArgs.SourcesDirectory = parsedArgs.SourcesDirectory ?? GetDirectoryName(AppContext.BaseDirectory, 5); parsedArgs.GenerateDirectory = parsedArgs.GenerateDirectory ?? parsedArgs.SourcesDirectory; parsedArgs.RepoUtilDataPath = parsedArgs.RepoUtilDataPath ?? Path.Combine(parsedArgs.SourcesDirectory, @"build\config\RepoUtilData.json"); parsedArgs.RemainingArgs = index >= args.Length ? Array.Empty<string>() : args.Skip(index).ToArray(); return true; }
private void SetCommands() { var help = new HelpCommand(); var helpCreate = new HelpCreateCommand(); var helpGet = new HelpGetCommand(); var helpDelete = new HelpDeleteCommand(); var helpAdd = new HelpAddCommand(); var helpRemove = new HelpRemoveCommand(); var helpArrange = new HelpArrangeCommand(); SetCommand("!help", help); SetCommand("!help create", helpCreate); SetCommand("!help get", helpGet); SetCommand("!help delete", helpDelete); SetCommand("!help add", helpAdd); SetCommand("!help remove", helpRemove); SetCommand("!help arrange", helpArrange); var rotationGet = new GetCommand(); var rotationCreate = new CreateCommand(); var rotationDelete = new DeleteCommand(); var rotationAdd = new AddPlayersCommand(); var rotationRemove = new RemovePlayersCommand(); var rotationArrange = new ArrangePlayersCommand(); SetCommand("!rotation", rotationGet); SetCommand("!rotation get", rotationGet); SetCommand("!rotation create", rotationCreate); SetCommand("!rotation delete", rotationDelete); SetCommand("!rotation add", rotationAdd); SetCommand("!rotation remove", rotationRemove); SetCommand("!rotation arrange", rotationArrange); }
protected override void OnStartup(StartupEventArgs e) { PriceService priceService = new PriceService(); int currentMinute = 10; CreateCommand <BuyViewModel> createCalculatePriceCommand; CreateCommand <BuyViewModel> createBuyCommand; if (currentMinute % 2 == 1) { createCalculatePriceCommand = (vm) => new CalculatePriceCommand(vm, priceService); createBuyCommand = (vm) => new BuyCommand(vm, priceService); } else { CreateCommand <BuyViewModel> createStoreClosedCommand = (vm) => new StoreClosedCommand(vm); createCalculatePriceCommand = createStoreClosedCommand; createBuyCommand = createStoreClosedCommand; } BuyViewModel initialViewModel = new BuyViewModel(createCalculatePriceCommand, createBuyCommand); MainWindow = new MainWindow() { DataContext = initialViewModel }; MainWindow.Show(); base.OnStartup(e); }
private void TryParseCreateCommand(SparqlUpdateParserContext context) { bool silent = false; //May possibly have a SILENT Keyword IToken next = context.Tokens.Dequeue(); if (next.TokenType == Token.SILENT) { silent = true; next = context.Tokens.Dequeue(); } //Followed by a mandatory GRAPH Keyword if (next.TokenType != Token.GRAPH) { throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a GRAPH Keyword as part of the CREATE command", next); } //Then MUST have a URI Uri u = this.TryParseGraphRef(context); CreateCommand cmd = new CreateCommand(u, silent); context.CommandSet.AddCommand(cmd); }
public async Task <ResponseResult> Handle(CreateCommand request, CancellationToken cancellationToken) { _repository.IncludeInTrasation(_unitOfWork); var many = new Many(request.One, request.ManyProperty01); AddNotifications(many); _repository.Add(many); var toOneResponse = await _mediator.Send(new ToOneHandlers.CreateCommand { Many = many, Property01 = request.ManyProperty01 }); var selfOneResponse = await _mediator.Send(new SelfOneHandlers.CreateCommand { Many = many, Property01 = request.ManyProperty01 }); AddNotifications(selfOneResponse); AddNotifications(toOneResponse); return(new ResponseResult(many, this)); }
public PipelineViewModel(Pipeline pipeline = null) { PipelineDomainObject = pipeline; CreateCommand = new CreateCommand <Pipeline>(); DeleteCommand = new DeleteCommand <Pipeline>(); UpdateCommand = new UpdateCommand <Pipeline>(); }
public async Task InitializeDataAsync() { Accounts.Clear(); Accounts.AddRange(await _accountService.GetAsync()); SelectedAccount = Accounts.FirstOrDefault(); CreateCommand.RaiseCanExecuteChanged(); }
public NewTodoItemPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService) : base(navigationService) { _pageDialogService = pageDialogService; Title = "New Todo Item"; CreateCommand = new[] { Name.Select(x => string.IsNullOrEmpty(x)) }.CombineLatestValuesAreAllFalse() .ObserveOn(SynchronizationContext.Current) .ToAsyncReactiveCommand(); _ = CreateCommand.Subscribe(async() => { var item = new TodoItem { Name = Name.Value, Notes = Notes.Value, }; _ = CrossCloudFirestore.Current .Instance .Collection(TodoItem.CollectionPath) .AddAsync(item) .ContinueWith(t => { System.Diagnostics.Debug.WriteLine(t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); await navigationService.GoBackAsync(useModalNavigation: true); }); CancelCommand = new ReactiveCommand(); CancelCommand.Subscribe(() => NavigationService.GoBackAsync(useModalNavigation: true)); }
public static CustomField2 Execute(CorrigoService service, CorrigoEntity entity, CustomFieldDescriptor customFieldDescriptor) { string label = "IFS-1119"; string href = "https://jira.qa.corrigo.com:55445/browse/IFS-1119"; string urlValue = $"<a href=\"{href}\">{label}</a>"; var customField = new CustomField2 { Descriptor = new CustomFieldDescriptor { Id = customFieldDescriptor.Id }, ObjectId = entity.Id, ObjectTypeId = customFieldDescriptor.ActorTypeId, Value = urlValue }; var command = new CreateCommand { Entity = customField }; var response = service.Execute(command) as OperationCommandResponse; customField.Id = response?.EntitySpecifier?.Id ?? 0; return(customField); }
public async Task <MovimentoProvisao> Obter(Guid premioId, Guid coberturaId, short tipoProvisaoId, short tipoMovimentoId, int numeroParcela) { return(await CreateCommand.QueryOneAsync <MovimentoProvisao> (@"SELECT M.Id, M.ProvisaoCoberturaId, M.EventoId, M.PremioId, M.DataMovimento AS DataMovimentacao, M.QuantidadeContribuicoes, M.Fator, M.PercentualCarregamento, M.ValorBeneficioCorrigido, M.ValorJuros, M.ValorAtualizacao, M.ValorSobrevivencia, M.ValorProvisao, M.Desvio, M.ValorFIF FROM MovimentoProvisaoPremio M INNER JOIN ProvisaoCobertura P ON P.Id = M.ProvisaoCoberturaId INNER JOIN Premio PR ON PR.Id = M.PremioId WHERE P.CoberturaContratadaId = @CoberturaId AND P.TipoProvisaoId = @TipoProvisaoId AND M.PremioId = @PremioId AND PR.TipoMovimentoId = @TipoMovimento AND PR.Numero = @Numero", new { @PremioId = premioId, @CoberturaId = coberturaId, @TipoProvisaoId = tipoProvisaoId, @TipoMovimento = tipoMovimentoId, @Numero = numeroParcela })); }
public void Add(LeaveMessageModel model) { leaveMessage leaveMessage = new leaveMessage(model.Content, model.ContractEmail, false); CreateCommand createCommand = new CreateCommand(leaveMessage); _eventBus.Publish(createCommand); }
/// <summary> /// Create a new group and move the items into the group /// </summary> private void MoveToNewGroup() { // Create the group var state = new ItemState( _projectManager.GetNextGroupID(), "Group", item.transform.parent.name, Utility.GetNeighbourID(item.transform) ); var createCommand = new CreateCommand(true, state); _commandGroup = new CommandGroup(); _undoService.AddCommand(_commandGroup); _commandGroup.AddToGroup(createCommand); createCommand.Redo(); // Move the items _dragItem = Utility.FindChild(hierarchyView.transform, state.ID).GetComponent <HierarchyItemController>(); _insertion = true; _selectedItems = hierarchyViewController.GetSelectedItems(); InsertItems(); // Scroll to First selected Game object var groupItem = gameObject.transform.parent.parent; hierarchyViewController.ScrollToItem(groupItem.GetComponent <RectTransform>()); groupItem.GetComponent <HierarchyItemController>().RenameItem(true, _commandGroup); }
public override AObject MouseUp(object sender, MouseEventArgs e, Panel panel1, LinkedList <AObject> listObject) { connectorObject.to = e.Location; connectorObject.Deselect(); connectorObject.Draw(); connectorObject.first = checkObject(connectorObject.from, listObject); connectorObject.last = checkObject(connectorObject.to, listObject); if (connectorObject.first == null || connectorObject.last == null || connectorObject.to == connectorObject.from) { panel1.Invalidate(); panel1.Refresh(); return(null); } connectorObject.first.attach(this.connectorObject); connectorObject.last.attach(this.connectorObject); connectorObject.from = new Point((connectorObject.first.from.X + connectorObject.first.to.X) / 2, (connectorObject.first.from.Y + connectorObject.first.to.Y) / 2); connectorObject.to = new Point((connectorObject.last.from.X + connectorObject.last.to.X) / 2, (connectorObject.last.from.Y + connectorObject.last.to.Y) / 2); CreateCommand createCommand = new CreateCommand(connectorObject); createCommand.ParentForm = ParentForm; ParentForm.Add_Command(createCommand); panel1.Invalidate(); //panel1.Refresh(); return(connectorObject); }
public IExecutable ManageCommand(string[] inputArgs) { IExecutable command = null; string commandType = inputArgs[0]; switch (commandType) { case "create": command = new CreateCommand(this.Engine, inputArgs[1], int.Parse(inputArgs[2]), int.Parse(inputArgs[3]), (BehaviorTypes)Enum.Parse(typeof(BehaviorTypes), inputArgs[4]), (AttackTypes)Enum.Parse(typeof(AttackTypes), inputArgs[5])); break; case "attack": command = new AttackCommand(this.Engine, inputArgs[1], inputArgs[2]); break; case "pass": command = new PassCommand(); break; case "status": command = new StatusCommand(this.Engine); break; case "drop": command = new DropCommand(); break; } return(command); }
public void ProjectCreate_Execute_WithTemplateReturnsExternalServiceRequired() { _templateWriter.Setup(t => t.Read(It.IsAny <string>())).Returns( @"name: Project 2 models: - name: Product jobs: - name: Default tasks: - name: Generate type: Generate provider: AspNetCoreMvc - name: Push type: Generate provider: GitHubRepositoryProvider configs: Branch: master" ); var command = new CreateCommand(_console, LoggerMock.GetLogger <CreateCommand>().Object, _consoleReader.Object, _projectService.Object, _providerService.Object, _externalServiceService.Object, _templateWriter.Object) { Name = "Project 2", Client = "Company", Template = "Test" }; var resultMessage = command.Execute(); Assert.Equal("Please add the required external services first by using \"service add\" command.", resultMessage); }
public CreateCommandResult Execute(CreateCommand input) { var team = new Team(input.Name, input.Description, input.CreateSharePointSite, input.CreateTeamsChannel); foreach (var administrator in input.Administrators) { team.AddAdministrador(administrator.Name, administrator.EmailAddress); } _dataService.TeamsRepository.Create(team); _dataService.Persist(); _busPublisher.Publish("teams", new ReadTeamModel() { Name = input.Name, Description = input.Description, CreateSharePointSite = input.CreateSharePointSite, CreateTeamsChannel = input.CreateTeamsChannel }).GetAwaiter(); return(new CreateCommandResult() { Id = team.Id }); }
public void ShouldCreateFile() { // When var command = new CreateCommand (FilePath); command.Execute (); // Then Assert.IsTrue (File.Exists (FilePath)); }
public void ShouldThrowExceptionIFileAlreadyExists() { // Given File.Create (FilePath).Close (); // When var command = new CreateCommand (FilePath); command.Execute (); }
public void TestMethod1() { var bus = new InMemoryMessageBus(); var lHandler = new CreateCommandHandlers(); CreateCommand lCommand = new CreateCommand(Guid.NewGuid()); bus.RegisterHandler<CreateCommand>(lHandler.Handle); bus.Send(lCommand); Assert.IsTrue(lHandler.HandledIds.Contains(lCommand.Id)); }
public void ShouldRollbackFileCreation() { // Given var command = new CreateCommand (FilePath); command.Execute (); // When command.Rollback (); // Then Assert.IsFalse (File.Exists (FilePath)); }
public void CreateEntity_ShouldCreateEntity() { // arrange var ev = new D2DEvent(); var stub = new FakeRepository(new Dictionary<Type, IEnumerable<IEntity>>()); var createCommand = new CreateCommand<D2DEvent> {Entity = ev}; // act createCommand.Execute(stub); //assert Assert.AreEqual(1, stub.AddCalls.Count()); Assert.AreEqual(ev, stub.AddCalls.First()); }
public void Run() { IExecutable command = null; string line = reader.ReadLine(); while (line != "drop") { string[] tokens = line.Split(); switch (tokens[0]) { case "create": command = new CreateCommand( db, tokens[1], int.Parse(tokens[2]), int.Parse(tokens[3]), tokens[4], tokens[5]); break; case "pass": command = new PassCommand(db); break; case "status": command = new StatusCommand(db); break; case "attack": default: throw new NotImplementedException("Uncnoun command."); } try { this.writer.Print(command.Execute()); } catch (Exception e) { this.writer.Print(e.Message); } finally { line = reader.ReadLine(); } } }
public void Handle(CreateCommand pCommand) { HandledIds.Add(pCommand.Id); }
public virtual void Execute(CreateCommand command) { if (this.Created) { throw new InvalidOperationException(string.Format("The Aggregate {0} has already been created.", this.GetType().Name)); } this.AggregateId = command.AggregateId; this.NewEvent(new CreatedEvent()); }