public TransactionController(PostCommand <Transaction> command, GetAllCommand <Transaction> getCommand, GetStringCommand <Transaction> getStringCommand) { this.postCommand = command; this.getAllCommand = getCommand; this.getStringCommand = getStringCommand; }
public void PostCommandWithNullValue() { var post = new PostCommand(Mock.Of <EntityMetadata>(x => x.StartAddress == 0x1000), null, this._dataDriver, new TaskCompletionSource <object>(), new CancellationToken()); Task.Factory.StartNew(() => post.ExecuteAsync()).Result.Should().NotBeNull(); }
public void DefaultPostCommandNotBeFaulted() { var post = new PostCommand(Mock.Of <EntityMetadata>(x => x.StartAddress == 0x1000), new Object(), this._dataDriver, new TaskCompletionSource <object>(), new CancellationToken()); Task.Factory.StartNew(() => post.ExecuteAsync()).IsFaulted.Should().Be(false); }
public void CancelPostCommandTaskShouldBeCanceled() { var post = new PostCommand(Mock.Of <EntityMetadata>(x => x.StartAddress == 0x1000), new Object(), this._dataDriver, new TaskCompletionSource <object>(), new CancellationToken(true)); Task.Factory.StartNew(() => post.ExecuteAsync()).Result.IsCanceled.Should().Be(true); }
public async Task PostCommand_WithEchoOn_OnlyPrintsRequestBodyOnce() { string baseAddress = "https://localhost/"; string path = "values/5"; string content = "Test Post Body"; ArrangeInputs(commandText: $"POST --content \"{content}\"", baseAddress: baseAddress, path: path, urlsWithResponse: new Dictionary <string, string>() { { "https://localhost/values/5", "" } }, out var shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences); httpState.EchoRequest = true; PostCommand postCommand = new PostCommand(fileSystem, preferences, new NullTelemetry()); await postCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); List <string> result = shellState.Output; int countOfOccurrences = result.Count(s => s?.Contains(content, StringComparison.Ordinal) == true); Assert.Equal(1, countOfOccurrences); }
public CustomerController(PostCommand <Customer> command, GetAllCommand <Customer> getCommand, PutCommand <Customer> putCommand) { this.postCommand = command; this.putCommand = putCommand; this.getAllCommand = getCommand; }
public virtual IResponse <TViewModel> Create(TViewModel model) { var command = new PostCommand <TViewModel>(model); var result = Dispatcher.Invoke(command); return(result); }
public async Task ExecuteAsync_MultiPartRouteWithBodyFromFile_VerifyResponse() { string filePath = "someFilePath.txt"; string fileContents = "This is a test response from a POST: \"Test Post Body From File\""; ArrangeInputs(commandText: $"POST --file " + filePath, baseAddress: _baseAddress, path: _testPath, urlsWithResponse: _urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences, readBodyFromFile: true, fileContents: fileContents); fileSystem.AddFile(filePath, "Test Post Body From File"); PostCommand postCommand = new PostCommand(fileSystem, preferences); await postCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); List <string> result = shellState.Output; Assert.Equal(2, result.Count); Assert.Contains("HTTP/1.1 200 OK", result); Assert.Contains(fileContents, result); }
public async Task ExecuteAsync_WithContentTypeHeader_NotDuplicated() { string expectedHeader = "Content-Type: application/test"; ArrangeInputs(commandText: "POST --header content-type:application/test --content \"Test Post Body\"", baseAddress: _baseAddress, path: _testPath, urlsWithResponse: _urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences); httpState.EchoRequest = true; PostCommand postCommand = new PostCommand(fileSystem, preferences); await postCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); List <string> result = shellState.Output; Assert.Equal(8, result.Count); Assert.Contains("HTTP/1.1 200 OK", result); Assert.Single(result.Where(s => string.Equals(s, expectedHeader, System.StringComparison.Ordinal))); }
public async void PostCommand_Execute() { // ARRANGE var refDate = DateTime.Now; var user = "******"; var arg = "this is a simple message!"; var arguments = new Dictionary <string, string> { { nameof(user), user }, { nameof(arg), arg } }; var storage = new Mock <IStorageProvider>(); var interaction = new Mock <IInteractionProvider>(); interaction.SetupGet(_ => _.IsDebugMode).Returns(true); var time = new Mock <ITimeProvider>(); time.SetupGet(_ => _.Now).Returns(refDate); var command = new PostCommand(storage.Object, interaction.Object, time.Object, arguments); // ACT await command.Execute(); // ASSERT storage.Verify(_ => _.AddMessageForUser(user, arg, refDate)); interaction.Verify(_ => _.Warn(It.IsAny <string>())); }
public OrderController(PostCommand <Order> command, GetAllCommand <Order> getAllCommand, DeleteCommand deleteCommand) { this.postCommand = command; this.getAllCommand = getAllCommand; this.deleteCommand = deleteCommand; }
public void AddAPostToAUserWhenExecuted() { var arguments = new List <string> { "alice", "->", "this", "is", "a", "test" }; var userRepository = new UserRepository(); userRepository.RegisterUser("alice"); var postCommand = new PostCommand() { Arguments = arguments, UserRepository = userRepository }; postCommand.Execute(); Assert.That(userRepository.GetUser("alice").Posts.Count == 1); Assert.That(userRepository.GetUser("alice").Posts[0].Body, Is.EqualTo("this is a test")); }
public async Task <ActionResult> Edit(PostCommand post, bool reserve = true, CancellationToken cancellationToken = default) { post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken); if (!ValidatePost(post, out var resultData)) { return(resultData); } Post p = await PostService.GetByIdAsync(post.Id); if (reserve && p.Status == Status.Published) { var context = BrowsingContext.New(Configuration.Default); var doc1 = await context.OpenAsync(req => req.Content(p.Content), cancellationToken); var doc2 = await context.OpenAsync(req => req.Content(post.Content), cancellationToken); if (doc1.Body.TextContent != doc2.Body.TextContent) { var history = p.Mapper <PostHistoryVersion>(); p.PostHistoryVersion.Add(history); } p.ModifyDate = DateTime.Now; var user = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo); p.Modifier = user.NickName; p.ModifierEmail = user.Email; } p.IP = ClientIP; Mapper.Map(post, p); if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); p.Seminar.Clear(); foreach (var s in tmp) { var seminar = await SeminarService.GetAsync(e => e.Title.Equals(s)); if (seminar != null) { p.Seminar.Add(seminar); } } } var js = new JiebaSegmenter(); (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s)); bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章修改失败!")); } return(ResultData(p.Mapper <PostDto>(), message: "文章修改成功!")); }
public void GivenAPostCommandWhenExecuteMethodIsCalledThenItCallsPostInTheCommandReceiver() { var command = new PostCommand(this.receiver, BobUserHandle, PostMessageText); command.Execute(); this.receiver.Received().Post(BobUserHandle, PostMessageText); }
public static Post CreateFrom(PostCommand postCommand) { return new Post { Date = DateTimeProvider.Now, User = postCommand.User, Message = postCommand.Message }; }
public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false) { post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes()); if (!ValidatePost(post, out var resultData)) { return(resultData); } post.Status = Status.Published; Post p = post.Mapper <Post>(); p.Modifier = p.Author; p.ModifierEmail = p.Email; p.IP = ClientIP; if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); foreach (var s in tmp) { var id = s.ToInt32(); Seminar seminar = await SeminarService.GetByIdAsync(id); p.Seminar.Add(new SeminarPost() { Post = p, PostId = p.Id, Seminar = seminar, SeminarId = seminar.Id }); } } if (schedule) { if (!timespan.HasValue || timespan.Value <= DateTime.Now) { return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } p.Status = Status.Schedule; p.PostDate = timespan.Value.ToUniversalTime(); p.ModifyDate = timespan.Value.ToUniversalTime(); HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p); return(ResultData(p.Mapper <PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!")); } PostService.AddEntity(p); bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章发表失败!")); } return(ResultData(null, true, "文章发表成功!")); }
public AccountController(PostCommand <Account> command, GetAllCommand <Account> getAllCommand, GetStringCommand <Account> getStringCommand, DeleteCommand deleteCommand, PutCommand <Account> putCommand) { this.postCommand = command; this.getAllCommand = getAllCommand; this.getStringCommand = getStringCommand; this.deleteCommand = deleteCommand; this.putCommand = putCommand; }
private bool ValidatePost(PostCommand post, out ActionResult resultData) { if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available)) { resultData = ResultData(null, false, "请选择一个分类"); return(false); } switch (post.LimitMode) { case RegionLimitMode.AllowRegion: case RegionLimitMode.ForbidRegion: if (string.IsNullOrEmpty(post.Regions)) { resultData = ResultData(null, false, "请输入限制的地区"); return(false); } post.Regions = post.Regions.Replace(",", "|").Replace(",", "|"); break; case RegionLimitMode.AllowRegionExceptForbidRegion: case RegionLimitMode.ForbidRegionExceptAllowRegion: if (string.IsNullOrEmpty(post.ExceptRegions)) { resultData = ResultData(null, false, "请输入排除的地区"); return(false); } post.ExceptRegions = post.ExceptRegions.Replace(",", "|").Replace(",", "|"); goto case RegionLimitMode.AllowRegion; } if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null")) { post.Label = null; } else if (post.Label.Trim().Length > 50) { post.Label = post.Label.Replace(",", ","); post.Label = post.Label.Trim().Substring(0, 50); } else { post.Label = post.Label.Replace(",", ","); } if (string.IsNullOrEmpty(post.ProtectContent?.RemoveHtmlTag()) || post.ProtectContent.Equals("null")) { post.ProtectContent = null; } resultData = null; return(true); }
public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false, CancellationToken cancellationToken = default) { post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken); if (!ValidatePost(post, out var resultData)) { return(resultData); } post.Status = Status.Published; Post p = post.Mapper <Post>(); p.Modifier = p.Author; p.ModifierEmail = p.Email; p.IP = ClientIP; p.Rss = p.LimitMode is null or RegionLimitMode.All; if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); foreach (var s in tmp) { var id = s.ToInt32(); Seminar seminar = await SeminarService.GetByIdAsync(id); p.Seminar.Add(seminar); } } if (schedule) { if (!timespan.HasValue || timespan.Value <= DateTime.Now) { return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!")); } p.Status = Status.Schedule; p.PostDate = timespan.Value.ToUniversalTime(); p.ModifyDate = timespan.Value.ToUniversalTime(); BackgroundJob.Enqueue <IHangfireBackJob>(job => job.PublishPost(p)); return(ResultData(p.Mapper <PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!")); } PostService.AddEntity(p); var js = new JiebaSegmenter(); (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s)); bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章发表失败!")); } return(ResultData(null, true, "文章发表成功!")); }
public async Task <ActionResult> Edit(PostCommand post, bool reserve = true) { post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes()); if (!ValidatePost(post, out var resultData)) { return(resultData); } Post p = await PostService.GetByIdAsync(post.Id); if (reserve && p.Status == Status.Published) { var history = p.Mapper <PostHistoryVersion>(); p.PostHistoryVersion.Add(history); p.ModifyDate = DateTime.Now; var user = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo); p.Modifier = user.NickName; p.ModifierEmail = user.Email; } p.IP = ClientIP; Mapper.Map(post, p); if (!string.IsNullOrEmpty(post.Seminars)) { var tmp = post.Seminars.Split(',').Distinct(); p.Seminar.Clear(); foreach (var s in tmp) { var seminar = await SeminarService.GetAsync(e => e.Title.Equals(s)); if (seminar != null) { p.Seminar.Add(new SeminarPost() { Post = p, Seminar = seminar, PostId = p.Id, SeminarId = seminar.Id }); } } } bool b = await SearchEngine.SaveChangesAsync() > 0; if (!b) { return(ResultData(null, false, "文章修改失败!")); } return(ResultData(p.Mapper <PostDto>(), message: "文章修改成功!")); }
public async Task <Dto> Handle(Command request, CancellationToken cancellationToken) { var userdata = new user_model { name = request.data.Attributes.name, username = request.data.Attributes.username, email = request.data.Attributes.email, password = request.data.Attributes.password, address = request.data.Attributes.address }; konteks.user.Add(userdata); await konteks.SaveChangesAsync(cancellationToken); var user = konteks.user.First(x => x.username == request.data.Attributes.username); var target = new TargetCommand() { Id = user.id, Email_destination = user.email }; var client = new HttpClient(); var command = new PostCommand() { Title = "hello world", Message = "you think this is hello world, but it was me dio", Type = "email", From = 2, Target = new List <TargetCommand>() { target } }; var attributes = new Data <PostCommand>() { Attributes = command }; var httpContent = new RequestData <PostCommand>() { data = attributes }; var jsonObj = JsonConvert.SerializeObject(httpContent); var content = new StringContent(jsonObj, Encoding.UTF8, "application/json"); await client.PostAsync("http://localhost:2000/notification", content); return(new Dto { message = "user posted", success = true }); }
//Sending queue when transaction_status is changed public void SendQueue() { var target = new TargetCommand { Id = 1, Email_destination = "*****@*****.**" }; PostCommand command = new PostCommand() { Title = "Payment Successfull", Message = "Your payment has been accepted", Type = "email", From = 1, Targets = new List <TargetCommand>() { target } }; var attributes = new Data <PostCommand>() { Attributes = command }; var httpContent = new CommandDTO <PostCommand>() { Data = attributes }; var mObj = JsonConvert.SerializeObject(httpContent); var factory = new ConnectionFactory() { HostName = "some-rabbit" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare("directExchange", "direct"); channel.QueueDeclare("notification", true, false, false, null); channel.QueueBind("notification", "directExchange", string.Empty); var body = Encoding.UTF8.GetBytes(mObj); channel.BasicPublish( exchange: "directExchange", routingKey: "", basicProperties: null, body: body ); Console.WriteLine("Data has been forwarded"); } }
public async Task <ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code, CancellationToken cancellationToken) { if (await RedisHelper.GetAsync("code:" + post.Email) != code) { return(ResultData(null, false, "验证码错误!")); } if (PostService.Any(p => p.Status == Status.Forbidden && p.Email == post.Email)) { return(ResultData(null, false, "由于您曾经恶意投稿,该邮箱已经被标记为黑名单,无法进行投稿,如有疑问,请联系网站管理员进行处理。")); } var match = Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex); if (match.Success) { LogManager.Info($"提交内容:{post.Title}/{post.Author}/{post.Content},敏感词:{match.Value}"); return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!")); } if (!CategoryService.Any(c => c.Id == post.CategoryId)) { return(ResultData(null, message: "请选择一个分类")); } post.Label = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ","); post.Status = Status.Pending; post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.HtmlSantinizerStandard().ClearImgAttributes(), cancellationToken); Post p = post.Mapper <Post>(); p.IP = ClientIP; p.Modifier = p.Author; p.ModifierEmail = p.Email; p.DisableCopy = true; p.Rss = true; p = PostService.AddEntitySaved(p); if (p == null) { return(ResultData(null, false, "文章发表失败!")); } await RedisHelper.ExpireAsync("code:" + p.Email, 1); var content = new Template(await new FileInfo(HostEnvironment.WebRootPath + "/template/publish.html").ShareReadWrite().ReadAllTextAsync(Encoding.UTF8)) .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme)) .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) .Set("title", p.Title).Render(); BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP)); return(ResultData(p.Mapper <PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!")); }
public void CreateFrom_GivenAPostCommand_RecognizesItCorrectly() { // arrange var user = Alice; var message = "I love the weather today"; var postCommand = $"{user} -> {message}"; // act var command = CommandFactory.CreateFrom(postCommand); // assert var expectedCommand = new PostCommand(user, message); command.Should().Be(expectedCommand); }
public async Task <IActionResult> Add([FromBody] PostCommand model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var data = model.ToData(); _catRepository.Add(data); await _uow.CommitAsync(); return(CreatedAtRoute("GetCategoriaById", new { data.Id }, data.ToVM())); }
public void ValidInput() { ITypeCommand postCommand = new PostCommand(); var args = new[] { "--posts", "10" }; try { postCommand.ValidCommandLine(args); } catch (Exception ex) { Assert.Fail("Expected no exception, but got: " + ex.Message); } }
public ICommand Build(string command) { string[] commandSplit = command?.Split(' '); ICommand createdCommand; switch (commandSplit[0]) { case "/help": case "/h": createdCommand = new HelpCommand(); break; case "/version": case "/v": createdCommand = new VersionCommand(); break; case "/clear": createdCommand = new ClearCommand(); break; case "/quit": case "/q": createdCommand = new QuitCommand(); break; case "/post": case "/p": createdCommand = new PostCommand(commandSplit); break; case "/retrieve": case "/r": createdCommand = new RetrieveCommand(commandSplit); break; case "/settings": createdCommand = new SettingsCommand(commandSplit); break; default: createdCommand = new DefaultCommand(); break; } return(createdCommand); }
public UserProfileViewModel(IDataService dataService) { PostCommand = new PostCommand(this); _dataService = dataService; //use user to get all projects CurrentProject = _dataService.GetProjectData(); //get current project details. string json = JsonConvert.SerializeObject(CurrentProject); TestJson = JValue.Parse(json).ToString(Formatting.Indented); //stop loading }
public void Process_UsernameAndMessage_PostsData() { //Arrange var commandText = "unknown -> command"; var postsRepository = new Mock <IPostsRepository>(); postsRepository.Setup(d => d.Post(It.IsAny <IWallData>())); var postCommand = new PostCommand(It.IsAny <string>(), commandText); //Act postCommand.Process(postsRepository.Object); //Assert postsRepository.Verify(d => d.Post(It.IsAny <IWallData>()), Times.Once()); }
public void Handle(ProjectionManagementMessage.Command.Post message) { var command = new PostCommand { Name = message.Name, RunAs = message.RunAs, CheckpointsEnabled = message.CheckpointsEnabled, TrackEmittedStreams = message.TrackEmittedStreams, EmitEnabled = message.EmitEnabled, EnableRunAs = message.EnableRunAs, Enabled = message.Enabled, HandlerType = message.HandlerType, Mode = message.Mode, Query = message.Query, }; _writer.PublishCommand("$post", command); }
public void ReturnAPayloadContainingAnErrorMessageOnUnsuccessfulExecution() { var emptyArgumentsList = new List <string>(); var userRepository = new UserRepository(); userRepository.RegisterUser("alice"); var postCommand = new PostCommand() { Arguments = emptyArgumentsList, UserRepository = userRepository }; var commandResult = postCommand.Execute(); Assert.That(commandResult.Payload[0].StartsWith("System.ArgumentOutOfRangeException")); }
public void SetCommandResultStatusToErrorOnUnsuccessfulExecution() { var emptyArgumentsList = new List <string>(); var userRepository = new UserRepository(); userRepository.RegisterUser("alice"); var postCommand = new PostCommand() { Arguments = emptyArgumentsList, UserRepository = userRepository }; var commandResult = postCommand.Execute(); Assert.That(commandResult.Status, Is.EqualTo(CommandResponseStatus.Error)); }
private void StorePost(PostCommand postCommand) { _postStore.StorePost(PostFactory.CreateFrom(postCommand)); }