public void AddUserMessage() { using (var uow = new CapriconContext()) { //retreive an existing user var userRepository = new UserRepository(uow); var existingUser = userRepository.GetAll().FirstOrDefault(); Assert.IsNotNull(existingUser); //retreive an existing message var messageRepository = new MessageRepository(uow); var existingMessage = messageRepository.GetAll().FirstOrDefault(); Assert.IsNotNull(existingMessage); //create new user messsage var newUserMessage = new UserMessage() { User = existingUser, Message = existingMessage }; //add the new user message to the repository var userMessageRepository = new UserMessageRepository(uow); userMessageRepository.Add(newUserMessage); try { uow.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } //retrieve saved object var uow1 = new CapriconContext(); var repository = new UserMessageRepository(uow1); var savedUserMessages = repository.GetAll().ToList(); Assert.AreEqual(savedUserMessages[0].User.FirstName, existingUser.FirstName = "james"); Assert.AreEqual(savedUserMessages[0].Message.MessageId, existingMessage.MessageId = 1); }; }
public static void DeleteOneUserProfile(int userProfileID) { var profile = new UserProfileRepository().GetById(userProfileID); // Delete all associated Messages var mRep = new MessageRepository(); var messages = mRep.All().Where(m => m.UserID == profile.UserID).ToList(); foreach (var m in messages) mRep.Delete(mRep.GetById(m.MessageID)); mRep.SaveChanges(); // Delete all associated Images var iRep = new ImageRepository(); var images = iRep.All().Where(i => i.UserID == profile.UserID).ToList(); foreach (var i in images) iRep.Delete(i.ImageID); iRep.SaveChanges(); // Delete all associated UserFriends var ufRep = new UserFriendRepository(); var userFriends = ufRep.All().Where(u => u.UserID == profile.UserID).ToList(); foreach (var u in userFriends) ufRep.Delete(u.UserFriendID); ufRep.SaveChanges(); var upRep = new UserProfileRepository(); upRep.Delete(upRep.GetById(profile.UserID)); upRep.SaveChanges(); // Finally delete user from Membership Membership.DeleteUser(Membership.GetUser(profile.aspUserID).UserName, true); }
public string ChangeStatus() { string result = ""; try { int id = 0; int.TryParse(Request["id"], out id); byte status = 0; byte.TryParse(Request["status"], out status); var repo = new MessageRepository(); var v = repo.GetByID(id); if (v != null) { v.RecordStatus = status; repo.SaveChanges(); } result = JsonResult(true, Resources.Messages.StatusChanged); } catch (Exception ex) { result = JsonResult(false, ex.Message); } return result; }
public MessageListViewModel( MessageRepository messageRepository, [NotNull] MessageWatcher messageWatcher, MimeMessageLoader mimeMessageLoader, IPublishEvent publishEvent, ILogger logger) { if (messageRepository == null) throw new ArgumentNullException(nameof(messageRepository)); if (messageWatcher == null) throw new ArgumentNullException(nameof(messageWatcher)); if (mimeMessageLoader == null) throw new ArgumentNullException(nameof(mimeMessageLoader)); if (publishEvent == null) throw new ArgumentNullException(nameof(publishEvent)); _messageRepository = messageRepository; _messageWatcher = messageWatcher; _mimeMessageLoader = mimeMessageLoader; _publishEvent = publishEvent; _logger = logger; SetupMessages(); RefreshMessageList(); }
public JsonResult GetWallMessages() { var messageRepository = new MessageRepository(); var messages = messageRepository.GetAllFilteredByAndOrderedBy( x => x.ParentMessage == null , x => - x.CreatedOn.Ticks); return new JsonResult() { Data = new { Messages = messages }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }
public ReceivedDataMessageHandler(MessageRepository messageRepository, IPublishEvent publishEvent, ILogger logger) { _messageRepository = messageRepository; _publishEvent = publishEvent; _logger = logger; }
public void SendUnlikeToServer(int messageId) { var messageRepository = new MessageRepository(); messageRepository.Unlike(messageId, Context.User.Identity.Name, (author) => { Clients.updateUnlike(messageId, new { Id = author.Id, Name = author.Name }); }); }
public void AddPayment() { using (CapriconContext context = new CapriconContext()) { var messageRepository = new MessageRepository(context); var existingMessage = messageRepository.GetAll().LastOrDefault(); Assert.IsNotNull(existingMessage); var newPayment = new Payment() { PaymentDate = DateTime.Now, Amount = 750, Message = existingMessage }; var paymentRep = new PaymentRepository(context); paymentRep.Add(newPayment); try { context.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } //retrieve saved object var context1 = new CapriconContext(); var repository = new PaymentRepository(context1); var savedPayments = repository.GetAll().ToList(); Assert.AreEqual(savedPayments.Count(), 3, "returns 20 records"); var savedPaymentsList = savedPayments; savedPaymentsList.ForEach ( p => { Debug.WriteLine(p.PaymentId + " - " + p.Amount + " " + p.Message.MessageId); } ); }; }
public void SendCommentToServer(int? parentMessageId, string comment) { string userName = Context.User.Identity.Name; var authorRepository = new AuthorRepository(); var author = authorRepository.GetAllFilteredBy(x => x.Login.Equals(userName, StringComparison.InvariantCultureIgnoreCase)).Single(); var messageRepository = new MessageRepository(); Message newMessage = messageRepository.AddMessage(parentMessageId, comment, author, messageRepository); Clients.addComment(parentMessageId, newMessage.Id, comment, new { Id = author.Id, Name = author.Name, SmallPicturePath = author.SmallPicturePath, MediumPicturePath = author.MediumPicturePath }); }
public void AddSuccess() { IMessageRepository messageRepository = new MessageRepository(); var message = new Message { Text = "Test message", Level = Level.Information }; messageRepository.Add(message); Assert.IsNotNull( _mongoDatabase.GetCollection<Type.Message>("Message").FindOneByIdAs<Type.Message>( new ObjectId(message.Id.Value))); }
protected void Button1_Click(object sender, EventArgs e) { String text = this.TextBox1.Text; MessageRepository msr = new MessageRepository(); message ms = new message(); ms.content = text; msr.Insert(ms); ShowPopUpMsg("已发布信息"); }
public void AddMessage() { using (CapriconContext context = new CapriconContext()) { var newMessage = new Message() { Body = "Testing...............", Sent = DateTime.Now, MessageStatus = MessageStatus.Sent }; var messageRep = new MessageRepository(context); messageRep.Add(newMessage); try { context.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } //retrieve saved object var context1 = new CapriconContext(); var repository = new MessageRepository(context1); var savedMessages = repository.GetAll().ToList(); Assert.AreEqual(savedMessages.Count(), 2, "returns 20 records"); var savedMessagesList = savedMessages; savedMessagesList.ForEach ( m => { Debug.WriteLine(m.MessageId + " - " + m.Body); } ); }; }
public void TestInitialize() { _target = new MessageRepository(); _target.FilePath = "data/initial_offers.json"; _target.InitializeFromFile(); Console.Out.WriteLine("Initialized from file with following data"); Console.Out.WriteLine(JSON.Serialize(_target.AllMessages())); List<IMessage> messages = new List<IMessage>(_target.AllMessages()); //Assert.AreEqual(9, messages.Count, "Expected 6 messages after initializing from " + _target.FilePath ); }
public void SerializeDemoMessagesToFile() { ILocationProvider locationProvider = new MockLocationProvider(); IMessageParser realMessageParser = new RegexMessageParser(_singletonTagProvider, locationProvider); MessageRepository tempMessageRepository = new MessageRepository(); TagRepository tempTagRepository = new TagRepository(); IncomingMessageProcessor incomingMessageProcessor = new IncomingMessageProcessor(tempMessageRepository, tempTagRepository, realMessageParser); IRawMessageProvider rawMessageProvider = new DemoMessageProvider(incomingMessageProcessor); rawMessageProvider.Update(); tempMessageRepository.FilePath = "../../data/demo_offers.json"; tempMessageRepository.SerializeToFile(); }
public static void Initialize() { UserRepository = new UserRepository(); PostRepository = new PostRepository(); HeaderImageRepository = new HeaderImageRepository(); MessageRepository = new MessageRepository(); CommentRepository = new CommentRepository(); PostVotingRepository = new PostVotingRepository(); CommentVotingRepository = new CommentVotingRepository(); MessageSettingsRepository = new MessageSettingsRepository(); TagRepository = new TagRepository(); TagPostRepository = new TagPostRepository(); }
protected void Page_Load(object sender, EventArgs e) { MessageRepository msr = new MessageRepository(); var ls = from a in msr.FindAll() select a; String text = ""; int i = 0; foreach(var m in ls) { i++; text += i + ". " + m.content + "</br>"; } this.Literal1.Text = text; }
public TestMessageExecutor() { MockMessageParser mockParser = new MockMessageParser(); ignoredUsers = new IgnoredUserRepository(); //var ignoredUser = MockData.Users[0]; //signoredUsers.Save(ignoredUser); MessageRepository messageRepository = new MessageRepository(ignoredUsers); TagRepository tagRepository = new TagRepository(); IncomingMessageProcessor incomingMessageProcessor = new IncomingMessageProcessor(messageRepository,tagRepository, mockParser); //_target = new TagDexQueryExecutor(); MockRawMessageProvider mockProvider = new MockRawMessageProvider(incomingMessageProcessor); _target = messageRepository; mockProvider.Update(); }
public void InitializeTwitterProvider() { //for this test create real objects all the way down the line - so...more of an integration test really // (which is why this is disabled) TagRepository singletonTagProvider = new TagRepository(); singletonTagProvider.FilePath = "data/initial_tags.json"; singletonTagProvider.InitializeFromFile(); ILocationProvider locationProvider = new MockLocationProvider(); RegexMessageParser realMessageParser = new RegexMessageParser(singletonTagProvider, locationProvider); _messageRepository = new MessageRepository(); _tagRepository = new TagRepository(); IncomingMessageProcessor target = new IncomingMessageProcessor(_messageRepository, _tagRepository, realMessageParser); TwitterRawMessageProvider twitterProvider = new TwitterRawMessageProvider((IRawMessageReceiver)target, new MockWebRequestFactory()); twitterProvider.Update(); }
public void Setup() { this.userrepository = new UserRepository(); this.msgrepository = new MessageRepository(); this.service = new ActivityService(this.msgrepository, this.userrepository); UserService uservice = new UserService(this.userrepository); this.user = uservice.NewUser("user"); for (int k = 1; k <= 100; k++) { User follower = uservice.NewUser("follower" + k); uservice.AddFollower(this.user.Id, follower.Id); this.followers.Add(follower); } }
public string Delete() { string result = ""; int id = Numerics.GetInt(Request["id"]); try { var repo = new MessageRepository(); repo.Delete(id); result = JsonResult(true, Resources.Messages.Delete); } catch (Exception ex) { result = JsonResult(false, ex.Message); } return result; }
public void DeleteMessage() { using (var uow = new CapriconContext()) { var messageRep = new MessageRepository(uow); var existingMessage = messageRep.Find(m => m.MessageId == 2).FirstOrDefault(); Assert.IsNotNull(existingMessage); int messageId; if (existingMessage != null) { messageId = existingMessage.MessageId; //Delete message messageRep.Delete(existingMessage); try { uow.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } Assert.IsNull(messageRep.Find(m => m.MessageId == messageId).FirstOrDefault()); } else //no messages were selected Assert.Fail("No message was selected"); } }
public void AllSuccess() { string guid = Guid.NewGuid().ToString(); for (int i = 0; i < 10; i++) { var message = new Type.Message { _id = ObjectId.GenerateNewId(), RecordDate = DateTime.Now, Level = Type.Level.Information, Text = guid }; _mongoDatabase.GetCollection<Type.Message>("Message").Insert(message); } IMessageRepository messageRepository = new MessageRepository(); Assert.AreEqual(10, messageRepository.All().Count(m => m.Text == guid)); }
public void InitializeWithRecentOffers_BlowsUpWithWrongFile() { try { //Global.InitializeWithRecentOffers("data/typo_asdfuihsg.json"); // should be copied to bin/Debug output directory because of build action properties on that file _target = new MessageRepository(); _target.FilePath = "data/typo_asdfuihsg.json"; _target.InitializeFromFile(); Assert.Fail("Expected to get an exception from trying to trying to load bad file"); } catch (IOException) { //expected } catch (Exception ex) { Assert.Fail("Expected to get an IOexception from trying to trying to load bad file, instead got:" + ex); } }
public async Task CanAccess_ShouldReturnFalse_WhenTheUserHasNeitherSentNorReceivedTheMessage() { // Arrange const int userId = 1; const int messageId = 1; DbSet <Message> expectedMessages = new[] { new Message { MessageId = 1, AuthorId = 2, MessageRecipients = new List <MessageRecipient> { new MessageRecipient { Recipient = new Recipient { UserId = 3 } }, new MessageRecipient { Recipient = new Recipient { UserId = 4 } } } }, } .AsQueryable() .BuildMockDbSet() .Object; _contextMock .Setup(m => m.Messages) .Returns(expectedMessages); MessageRepository repository = new MessageRepository(_contextMock.Object); // Act bool canAccess = await repository.CanAccess(messageId, userId); // Assert Assert.False(canAccess); }
public async Task <IActionResult> Create(InputModels.MessageInput input) { if (ModelState.IsValid) { if (Request.Method == "GET" && input.BoardId != null) { input.SelectedBoards.Add((int)input.BoardId); } else { foreach (var board in BoardRepository) { if (Request.Form.TryGetValue("Selected_" + board.Id, out var boardSelected)) { if (boardSelected == "True") { input.SelectedBoards.Add(board.Id); } } } } var serviceResponse = await MessageRepository.CreateTopic(input); return(await ForumViewResult.RedirectFromService(this, serviceResponse, FailureCallback)); } return(await FailureCallback()); async Task <IActionResult> FailureCallback() { var viewModel = new ViewModels.Messages.CreateTopicPage() { BoardId = input.BoardId, Body = input.Body }; return(await Task.Run(() => { return ForumViewResult.ViewResult(this, viewModel); })); } }
public void GetMessagesNotReaded() { SQLiteRepository con = new SQLiteRepository(); con.CreateDatabase(); MessageRepository messageRepository = new MessageRepository(con); ContactRepository contactRepository = new ContactRepository(con); Contact contact = new Contact { Id = 1, FirstName = "Pablo", LastName = "Corral", Phone = "34676681420" }; Chat m = new Chat { Mensaje = "hola", FromTo = "34676681420", Send = true, Created = DateTime.Now, Seen = true }; Chat m1 = new Chat { Mensaje = "hola, que tal?", FromTo = "34676681420", Send = false, Created = DateTime.Now.AddSeconds(10), Seen = false }; using (var connection = con.GetConnection()) { contactRepository.InsertContact(contact); messageRepository.InsertMessage(m); messageRepository.InsertMessage(m1); var result = messageRepository.GetMessagesNotReaded().Count; Assert.AreEqual(1, result); } }
public async Task <IActionResult> Edit(InputModels.MessageInput input) { if (ModelState.IsValid) { var serviceResponse = await MessageRepository.EditMessage(input); if (input.SideLoad) { foreach (var kvp in serviceResponse.Errors) { ModelState.AddModelError(kvp.Key, kvp.Value); } } else { return(await ForumViewResult.RedirectFromService(this, serviceResponse, FailureCallback)); } } if (input.SideLoad) { var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage }); return(new JsonResult(errors)); } else { return(await FailureCallback()); } async Task <IActionResult> FailureCallback() { var viewModel = new ViewModels.Messages.CreateTopicForm { Id = "0", Body = input.Body, ElementId = "create-topic" }; return(await ForumViewResult.ViewResult(this, viewModel)); } }
protected override void OnResume() { base.OnResume(); database = new SQLiteRepository(); contactRepository = new ContactRepository(database); messageRepository = new MessageRepository(database); configRepository = new ConfigRepository(database); configuracion = configRepository.GetConfig(); errorText = new ErrorText(); loginService = new LoginService(); messageService = new MessageService(); count = 0; try { client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } } catch (Exception ex) { this.FinishAffinity(); } speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext); speechReco.SetRecognitionListener(this); intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech); intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es"); intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName); intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch); intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1); gestureDetector = new GestureDetector(this); toSpeech = new TextToSpeech(this, this); }
public async Task <IActionResult> Edit(ControllerModels.Messages.EditInput input) { var message = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id); if (message is null || message.Deleted) { throw new HttpNotFoundError(); } if (message.PostedById != UserContext.ApplicationUser.Id && !UserContext.IsAdmin) { throw new HttpForbiddenError(); } if (ModelState.IsValid) { var result = await MessageRepository.EditMessage(input); ModelState.AddModelErrors(result.Errors); if (ModelState.IsValid) { await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message { TopicId = result.TopicId, MessageId = result.MessageId }); var redirectPath = Url.DisplayMessage(result.TopicId, result.MessageId); return(Redirect(redirectPath)); } } var viewModel = new ViewModels.Messages.EditMessageForm { Id = input.Id.ToString(), Body = input.Body, ElementId = $"edit-message-{input.Id}" }; return(await ForumViewResult.ViewResult(this, viewModel)); }
public async Task <IActionResult> XhrReply(ControllerModels.Messages.CreateReplyInput input) { if (input.Id > 0) { var message = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id); if (message is null || message.Deleted) { throw new HttpNotFoundError(); } } if (ModelState.IsValid) { var result = await MessageRepository.CreateReply(input); ModelState.AddModelErrors(result.Errors); if (ModelState.IsValid) { var hubAction = "new-reply"; if (result.Merged) { hubAction = "updated-message"; } await ForumHub.Clients.All.SendAsync(hubAction, new HubModels.Message { TopicId = result.TopicId, MessageId = result.MessageId }); return(Ok()); } } var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage }); return(new JsonResult(errors)); }
public override void Execute() { using (var messageRepo = new MessageRepository()) { messageRepo.ReadLevel = MessageRepository.MessageReadLevel.WithSenderReceiver; _messages = messageRepo.GetAll(); } int subjectNo = -1; do { base.Execute(); PrintInfoMessage($"Total Messages: ({_messages.Count})"); PrintSubjects(); PrintSeparator(); do { Console.WriteLine("Choose a subject number to read the relevant message."); string input = Console.ReadLine(); Int32.TryParse(input, out subjectNo); }while (subjectNo < 0 || subjectNo > _messages.Count); if (subjectNo != 0) { Console.Clear(); PrintSeparator(); Console.WriteLine("==================== MESSAGE TEXT ========================"); PrintSeparator(); WriteLineWordWrap(_messages[subjectNo - 1].Text); PrintSeparator(); Console.ReadLine(); } }while (subjectNo != 0); new MainMenu(); }
public JsonResult ContactUs(ContactMessageVM ContactMessage) { MessageRepository messageRepo = new MessageRepository(); UserRepository userRepo = new UserRepository(); Message newMessage = new Message(); if (userRepo.GetByEmail(ContactMessage.SenderEmail) == null) { newMessage.Sender = "NotRegistered"; } else { newMessage.Sender = userRepo.GetByEmail(ContactMessage.SenderEmail).Username; } newMessage.Receiver = userRepo.GetAdmin().Username; newMessage.Text = ContactMessage.Text; newMessage.DateTime = DateTime.Now; newMessage.Deleted = false; messageRepo.Add(newMessage); return(Json(true, JsonRequestBehavior.AllowGet)); }
public UnitOfWork() { _dbContext = new ApplicationDbContext(); Users = new UserRepository(_dbContext); Teachers = new TeacherRepository(_dbContext); Students = new StudentRepository(_dbContext); Courses = new CourseRepository(_dbContext); Rooms = new RoomRepository(_dbContext); Campuses = new CampusRepository(_dbContext); Attendances = new AttendanceRepository(_dbContext); StatusAttendances = new StatusAttendanceRepository(_dbContext); StatusTimeTables = new StatusTimeTableRepository(_dbContext); TimeSlots = new TimeSlotRepository(_dbContext); TimeTables = new TimeTableRepository(_dbContext); StudentGroups = new StudentGroupRepository(_dbContext); StatusTakeAttendances = new StatusTakeAttendanceRepository(_dbContext); StudentFaces = new StudentFacesRepository(_dbContext); IdentityStudents = new IdentityStudentRepository(_dbContext); RecognitionImages = new RecognitionImageRepository(_dbContext); Messages = new MessageRepository(_dbContext); StatusesMessage = new StatusMessageRepository(_dbContext); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { UsersRepository repemplo = new UsersRepository(); User user = repemplo.getUserById(Session["userid"].ToString().ToInt()); Name.InnerText = user.FirstName + " " + user.LastName; MessageRepository repmsg = new MessageRepository(); messageCount.InnerText = repmsg.CountUserNewMessages(Session["userid"].ToString().ToInt()); ContactUsRepository repo = new ContactUsRepository(); ContactWay cnw = repo.Findcwy(1); phone.InnerHtml = "<span><i class='fa fa-phone' style='margin-right: 7px'></i>" + cnw.PhoneNumber + "</span>"; mail.InnerHtml = "<span><i class='fa fa-envelope-o' style='margin-right: 7px'></i>" + cnw.Email + "</span>"; AboutUs.InnerHtml = cnw.AboutUs; contactEmail.InnerHtml = "<i class='fa fa-envelope'></i>" + cnw.Email; contactPhone.InnerHtml = "<i class='fa fa-phone'></i>" + cnw.PhoneNumber; contactHome.InnerHtml = "<i class='fa fa-home'></i>" + cnw.Adrees; logo.Attributes["style"] = "background-image:url(" + cnw.logo + ")"; } }
public void GetContactsByNameWithChatC3() { SQLiteRepository con = new SQLiteRepository(); con.CreateDatabase(); MessageRepository messageRepository = new MessageRepository(con); ContactRepository contactRepository = new ContactRepository(con); Contact contact = new Contact { Id = 1, FirstName = "Pablo", LastName = "Corral", Phone = "34676681420" }; Contact c = new Contact { Id = 2, FirstName = "Dani", LastName = "Pablo", Phone = "34666666666" }; Chat m = new Chat { Mensaje = "hola", FromTo = "34676681420", Send = true, Created = DateTime.Now, Seen = true }; using (var connection = con.GetConnection()) { contactRepository.InsertContact(contact); contactRepository.InsertContact(c); messageRepository.InsertMessage(m); var result = contactRepository.GetContactsByNameWithChat("Dani Pablo"); Assert.AreEqual(0, result.Count); } }
public ActionResult Edit(int id, string Action, TPO.Model.RawMaterials.RawMaterialReceived rawMaterialReceived) { if (Action == "Edit") { if (ModelState.IsValid) { //TODO: add mapper var dto = new TPO.Domain.DTO.RawMaterialReceivedDTO(); dto.DateEntered = rawMaterialReceived.DateEntered.Value; dto.EnteredBy = rawMaterialReceived.EnteredBy; dto.LotNumber = rawMaterialReceived.LotNumber; dto.PlantID = rawMaterialReceived.PlantID; dto.RawMaterialID = rawMaterialReceived.RawMaterialID; dto.ID = rawMaterialReceived.ID; dto.ModifiedBy = CurrentUser; TPO.BL.RawMaterials.RawMaterialReceived.Update(dto); TempData["ActionMessage"] = MessageRepository.GetStringValue(MessageKeys.ResponseMessageSuccessSave); TempData["ActionMessageType"] = MessageRepository.GetStringValue(MessageKeys.ResponseTypeSuccess); } else { ViewBag.PlantId = CurrentPlantId; TPO.BL.RawMaterials.RawMaterial RawMatList = new TPO.BL.RawMaterials.RawMaterial(); rawMaterialReceived.RawMaterials = from s in RawMatList.GetRawMaterials() select new SelectListItem { Value = s.RawMaterialId.ToString(CultureInfo.InvariantCulture), Text = (s.RawMaterialCode + " | " + s.RawMaterialName) }; ModelState.AddModelError(string.Empty, "Please enter required fields."); rawMaterialReceived.Users = new SelectList(this.UserRepo.GetAllUsers(), "UserName", "UserName"); TempData["ActionMessage"] = MessageRepository.GetStringValue(MessageKeys.ResponseMessageFailSave); TempData["ActionMessageType"] = MessageRepository.GetStringValue(MessageKeys.ResponseTypeError); return(View(rawMaterialReceived)); } } return(RedirectToAction("Index")); }
public async Task GetSendedMessagesTest() { //Arrange var options = new DbContextOptionsBuilder <DataContext>() .UseInMemoryDatabase(databaseName: "GetSendedMessages") .Options; using (var context = new DataContext(options)) { var user1 = new User { Id = 1 }; var user2 = new User { Id = 2 }; context.Add(new Message { Content = "test", MessageId = 1, Recipient = user1, Sender = user2 }); context.Add(new Message { Content = "test", MessageId = 2, Recipient = user1, Sender = user2 }); context.Add(new Message { Content = "test", MessageId = 3, Recipient = user2, Sender = user1 }); context.SaveChanges(); var repository = new MessageRepository(context); //Act var action = await repository.GetSendedMessages(user2.Id, 0); //Assert Assert.Equal(2, action.Count()); } }
public Messages( ApplicationDbContext dbContext, UserContext userContext, AccountRepository accountRepository, BoardRepository boardRepository, MessageRepository messageRepository, SmileyRepository smileyRepository, TopicRepository topicRepository, IHubContext <ForumHub> forumHub, ForumViewResult forumViewResult ) { DbContext = dbContext; UserContext = userContext; AccountRepository = accountRepository; BoardRepository = boardRepository; MessageRepository = messageRepository; SmileyRepository = smileyRepository; TopicRepository = topicRepository; ForumHub = forumHub; ForumViewResult = forumViewResult; }
public async Task UserLeft_UserIdNotFound() { //assemble var queryContext = AssembleMocks.GetQueryContext(); var commandContext = AssembleMocks.GetCommandContext(); var userSummaryRepo = new UserSummaryRepository(queryContext.Object); var conversationRepo = new ConversationRepository(queryContext.Object, commandContext.Object); var messageRepo = new MessageRepository(queryContext.Object, commandContext.Object); var conversationContext = new ConversationBoundedContext(conversationRepo, userSummaryRepo, messageRepo); var conversation = await conversationContext.GetById(4); var userSummary = await userSummaryRepo.GetById(1); conversation.UserJoined(userSummary); //workaround since can't seem to mock a working Include() Assert.IsTrue(conversation.ActiveUsers.Count() == 1); //act conversation.UserLeft(5); //assert Assert.IsTrue(conversation.ActiveUsers.Count() == 1); }
public async Task Update_updates_user() { var context = CreateMiniTwitContext(); var repo = new UserRepository(context, _loggerUser); var messageRepo = new MessageRepository(context); await Add_dummy_data(repo, messageRepo); var user = new User { Id = 2, UserName = "******", Email = "*****@*****.**" }; await repo.UpdateAsync(user); var entity = await context.Users.FindAsync(2); Assert.Equal("newuser2", entity.UserName); Assert.Equal("*****@*****.**", entity.Email); }
public PusherManager( IEventAggregator eventAggregator, IEnumerable <IEntityPuller> entityPullers, IEnumerable <IAttributePuller> attributePullers, ResolverFactory resolverFactory, EntityRepository entityRepository, AttributeRepository attributeRepository, ConnectionRepository connectionRepository, MessageRepository messageRepository, QueueItemRepository queueItemRepository) { this.eventAggregator = eventAggregator; this.entityPullers = entityPullers; this.attributePullers = attributePullers; this.resolverFactory = resolverFactory; this.entityRepository = entityRepository; this.attributeRepository = attributeRepository; this.connectionRepository = connectionRepository; this.messageRepository = messageRepository; this.queueItemRepository = queueItemRepository; _messages = new List <string>(); }
/// <summary> /// 添加留言 /// </summary> /// <param name="t"></param> /// <returns></returns> public async Task <bool> AddMessageAsync(MessageEntity t) { bool flag; var user = await UserService.GetUserByIdAsync(t.userId); if (await IsExistsMessageOnNewestByUserId(t.userId)) { // 判断用户是否为空 if (user == null) { return(false); } t.location = LocationHelper.GetLocation(t.location); flag = await MessageRepository.AddAsync(t); } else { throw new Exception("你已经在一分钟前提交过一次了"); } return(flag); }
public void AddOrUpdate_GoodInput_AddedInContext() { IMessageRepository repository = new MessageRepository { Context = _context }; var entity = new MessageEntity { Id = Guid.NewGuid(), Text = "test", CreateDate = DateTime.Now }; int itemsCount = _context.Storage.Count; repository.AddOrUpdate(entity); BaseEntity actual = _context.Storage.FirstOrDefault(x => x.Id == entity.Id); Assert.Equal(entity, actual); Assert.IsType <MessageEntity>(actual); Assert.Equal(entity.Id, actual.Id); Assert.Equal(entity.Text, ((MessageEntity)actual).Text); Assert.Equal(entity.CreateDate, ((MessageEntity)actual).CreateDate); Assert.False(((MessageEntity)actual).IsDelivered); Assert.Equal(itemsCount + 1, _context.Storage.Count); }
public void testDeleteMessage() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "Delete_message_from_database") .Options; string subject = "Test Subject"; string body = "Test Body"; Message message = new Message( subject, body ); using (ApplicationDbContext context = new ApplicationDbContext(options)) { IMessageRepository messageRepo = new MessageRepository(context); messageRepo.AddMessage(message); messageRepo.Save(); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new ApplicationDbContext(options)) { Assert.True(context.Message.Count() == 1); } using (var context = new ApplicationDbContext(options)) { IMessageRepository messageRepo = new MessageRepository(context); messageRepo.DeleteMessage(message.id); messageRepo.Save(); } using (var context = new ApplicationDbContext(options)) { Assert.True(context.Message.Count() == 0); } }
public void GetConversationMessagesWithUsers_ConversationIdPassed_CorrectMessagesReturned() { //Arrange var context = new Mock <DatabaseContext>(); var dbSetMock = new Mock <DbSet <Message> >(); var dbSetMockUsers = new Mock <DbSet <User> >(); dbSetMock.As <IQueryable <Message> >().Setup(m => m.Provider).Returns(messageList.Provider); dbSetMock.As <IQueryable <Message> >().Setup(m => m.Expression).Returns(messageList.Expression); dbSetMock.As <IQueryable <Message> >().Setup(m => m.ElementType).Returns(messageList.ElementType); dbSetMock.As <IQueryable <Message> >().Setup(m => m.GetEnumerator()).Returns(messageList.GetEnumerator()); context.Setup(x => x.Messages).Returns(dbSetMock.Object); dbSetMockUsers.As <IQueryable <User> >().Setup(m => m.Provider).Returns(userList.Provider); dbSetMockUsers.As <IQueryable <User> >().Setup(m => m.Expression).Returns(userList.Expression); dbSetMockUsers.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(userList.ElementType); dbSetMockUsers.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(userList.GetEnumerator()); context.Setup(x => x.Users).Returns(dbSetMockUsers.Object); var mockSet = Substitute.For <DbSet <Message>, IQueryable <Message> >(); ((IQueryable <Message>)mockSet).Provider.Returns(messageList.Provider); ((IQueryable <Message>)mockSet).Expression.Returns(messageList.Expression); ((IQueryable <Message>)mockSet).ElementType.Returns(messageList.ElementType); ((IQueryable <Message>)mockSet).GetEnumerator().Returns(messageList.GetEnumerator()); mockSet.Include(Arg.Any <string>()).Returns(mockSet); var repository = new MessageRepository(context.Object); context.Setup(x => x.Messages).Returns(mockSet); //Act var messages = repository.GetConversationMessagesWithUsers(2); //Assert Assert.IsTrue(messages.Any()); }
public void GetUserMessages() { var repo = new MessageRepository(ConnectionString); var expectedMessages = new[] { new MessageDataModel { Id = 1, UserId = 1, ContactId = 2, SendTime = DateTime.Parse("2019-05-18 16:18"), DeliveryTime = DateTime.Parse("2019-05-18 16:19"), Content = "Hi Tom!" }, new MessageDataModel { Id = 3, UserId = 1, ContactId = 3, SendTime = DateTime.Parse("2019-05-18 16:19"), DeliveryTime = DateTime.Parse("2019-05-18 16:25"), Content = "Hi Mark!" } }; var messages = repo.GetUserMessages(1).ToArray(); Assert.AreEqual(messages.Length, 2); Assert.True(Enumerable.Range(0, 2).All ( i => messages[i].Id == expectedMessages[i].Id && messages[i].ContactId == expectedMessages[i].ContactId && messages[i].UserId == expectedMessages[i].UserId && messages[i].SendTime == expectedMessages[i].SendTime && messages[i].DeliveryTime == expectedMessages[i].DeliveryTime && messages[i].Content == expectedMessages[i].Content) ); }
public ActionResult Index() { using (MyAppContext context = new MyAppContext()) { UserRepository repoUser = new UserRepository(context); User user = repoUser.getUser(HttpContext.User.Identity.Name); MessageRepository repo = new MessageRepository(context); List <Message> messages = repo.getAllByName(user.nickName); List <Message> alMessages = new List <Message>(); foreach (Message m in messages) { Message model = new Message() { author = m.author, text = m.text }; alMessages.Add(model); } return(View(alMessages)); } }
public void SendPrivateMessage(string toUserId, string message) { UserRepository userRepo = new UserRepository(); MessageRepository messageRepo = new MessageRepository(); string fromUserId = Context.ConnectionId; var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId); var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId); if (toUser != null && fromUser != null) { // send to Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message); // send to caller user Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message); messageRepo.Insert(new Models.Entities.Message { DateSent = DateTime.Now, UserNameReceiver = toUser.UserName, UserNameSender = fromUser.UserName, Body = message }); } }
public ActionResult GetJsonMessages() { /* * var db = new ChatDbContext(); * var messages = db.Messages.OrderBy(x => x.CreatedDate).ToList().Select(x => new * { * x.Id, * x.MessageContent, * x.UserName, * CreatedDate = x.CreatedDate.ToString(CultureInfo.InvariantCulture) * }).ToList(); */ var repository = new MessageRepository(); return(Json(repository.GetAllMessages().Select(x => new { x.Id, x.MessageContent, x.UserName, CreatedDate = x.CreatedDate.ToString(CultureInfo.InvariantCulture) }), JsonRequestBehavior.AllowGet)); //return Json(messages, JsonRequestBehavior.AllowGet); }
public void Send(string name, string message, string groupId, string latitude, string longitude, string browser) { var newLat = latitude.Replace('.', ','); var newLong = longitude.Replace('.', ','); if (string.IsNullOrEmpty(groupId)) { var newGroupId = Guid.NewGuid().ToString().Replace("-", ""); try { MessageRepository.Insert(MessageFactory.Create(name, newGroupId, message, DateTime.Now, Double.Parse(newLat), Double.Parse(newLong), browser)); } catch (Exception) { throw new Exception(string.Concat(name + " " + message + " " + groupId + " " + latitude + " " + longitude + " " + browser)); } } else { MessageRepository.Insert(MessageFactory.Create(name, groupId, message, DateTime.Now, Convert.ToDouble(latitude), Convert.ToDouble(longitude), browser)); } Clients.All.broadcastMessage(name, message, groupId); }
public void AddWrongMessage_Exception() { // Arrange MessageRepository messageRepository = new MessageRepository(dbContext); bool hasSubject = Convert.ToBoolean(TestContext.DataRow["HasSubject"]); Message message = new Message { Date = new DateTime(year: Convert.ToInt32(TestContext.DataRow["Year"]), month: Convert.ToInt32(TestContext.DataRow["Month"]), day: Convert.ToInt32(TestContext.DataRow["Day"])), User = dbContext.Users.First(), Subject = hasSubject ? dbContext.Subjects.First() : null, Text = Convert.ToString(TestContext.DataRow["Text"]) }; // Act messageRepository.Insert(message); // Assert Assert.ThrowsException <System.Data.Entity.Validation.DbEntityValidationException>(() => dbContext.SaveChanges()); // undo adding ((IObjectContextAdapter)dbContext).ObjectContext.Detach(message); }
public async Task <ActionResult> ListEmailMessages() { var appState = Session["ClientCredsAddinAppState"] as AppState; // get requested mailbox var requestedMailbox = Request.Form["Mailbox"]; // build view model var viewModel = new MailViewModel { AppState = appState, SelectedMailbox = requestedMailbox, UserListSelectors = GetMailboxSelectOptions(appState.MailboxList) }; // get messages var repo = new MessageRepository(viewModel.AppState.ExchangeOnlineAccessToken); var results = await repo.GetMessages(requestedMailbox); viewModel.SelectedMailbox = requestedMailbox; viewModel.Messages = results; return(View("Index", viewModel)); }
public async Task All_Messages_If_Following_Everyone() { var context = CreateMiniTwitContext(); var userRepo = new UserRepository(context, _loggerUser); var messageRepo = new MessageRepository(context); await Add_dummy_data(userRepo, messageRepo); var follower = new User { UserName = "******", Email = "*****@*****.**" }; var(_, followerReturnedId) = await userRepo.CreateAsync(follower); foreach (var user in context.Users.Where(user => user.Id != followerReturnedId)) { await userRepo.AddFollowerAsync(followerReturnedId, user.Id); } Assert.Equal(9, follower.Follows.Count); Assert.Equal(11, (await messageRepo.ReadMessagesFromFollowedWithinTimeAsync(followerReturnedId)).Count()); }
public void TestVariableTypeSerialization() { MessageRepository messageRepository = new MessageRepository(); // need to keep this seperate so as not to mess up other tests TagRepository tempTagRepository = new TagRepository(); //ditto IMessageParser messageParser = new RegexMessageParser(_singletonTagProvider, new MockLocationProvider()); IRawMessageReceiver messageReceiver = new IncomingMessageProcessor(messageRepository, tempTagRepository, messageParser); //add two messages of different types messageReceiver.Notify(DemoData.RawMessages[0]); messageReceiver.Notify(MockData.RawMessages[0]); var openSocialRawMessage = new OpenSocialRawMessage("ooooby", "i have vegetables available in wellington. for #free. #ooooby", "utunga", "", ""); messageReceiver.Notify(openSocialRawMessage); //serialize out string tempFileName = "testOffers.json"; messageRepository.FilePath = tempFileName; messageRepository.SerializeToFile(); // ok great now check that we can deserialize messageRepository = new MessageRepository(); // need to keep this seperate so as not to mess up other tests messageRepository.FilePath = tempFileName; messageRepository.InitializeFromFile(); Assert.AreEqual(messageRepository.MessageCount, 3, "expected to find 3 messages after deserialization"); //TwitterStatusXml twitterStatus = new TwitterStatusXml(); //twitterStatus.CreatedAt = DateUtils.TwitterTimeStampFromUTCDateTime(DateTime.Now); //twitterStatus. = DateUtils.TwitterTimeStampFromUTCDateTime(DateTime.Now); }
public void UpdateUserMessage() { using (var uow = new CapriconContext()) { var userMessageRepository = new UserMessageRepository(uow); var existingUserMessage = userMessageRepository.Find(um => um.Id == 1).FirstOrDefault(); Assert.IsNotNull(existingUserMessage); //retreive an existing user var userRepository = new UserRepository(uow); var existingUser = userRepository.Find(u => u.UserId == 1).FirstOrDefault(); Assert.IsNotNull(existingUser); //retreive an existing message var messageRepository = new MessageRepository(uow); var existingMessage = messageRepository.Find(m => m.MessageId == 1).FirstOrDefault(); Assert.IsNotNull(existingMessage); //edit an existing user message existingUserMessage.User = existingUser; existingUserMessage.Message = existingMessage; userMessageRepository.Attach(existingUserMessage); uow.Entry(existingUserMessage).State = EntityState.Modified; try { uow.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } //retrieve saved object var uow1 = new CapriconContext(); var repository = new UserMessageRepository(uow1); var savedUserMessages = repository.GetAll().ToList(); Assert.AreEqual(savedUserMessages[0].User, existingUser); Assert.AreEqual(savedUserMessages[0].Message, existingMessage); }; }
public void UpdatePayment() { using (var uow = new CapriconContext()) { var paymentRep = new PaymentRepository(uow); var existingPayments = paymentRep.GetAll().ToList(); var existingPayment = existingPayments.Find(p => p.PaymentId == 3); Assert.IsNotNull(existingPayment); var messageRepository = new MessageRepository(uow); var existingMessage = messageRepository.GetAll().FirstOrDefault(); Assert.IsNotNull(existingMessage); existingPayment.PaymentDate = DateTime.Now; existingPayment.Amount = 350; existingPayment.Message = existingMessage; //check for validation rules //existingPayment.PaymentDate = DateTime.Now; paymentRep.Attach(existingPayment); uow.Entry(existingPayment).State = EntityState.Modified; try { uow.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } }; //retrieve saved object var uow1 = new CapriconContext(); var repository = new PaymentRepository(uow1); var savedPayments = repository.GetAll().ToList(); Assert.AreEqual(savedPayments[0].Amount, 350); }
public MimeMessageLoader(MessageRepository messageRepository, ILogger logger) { _messageRepository = messageRepository; _logger = logger.ForContext<MimeMessageLoader>(); }
public void UpdateMessage() { using (var uow = new CapriconContext()) { var messageRep = new MessageRepository(uow); var existingMessages = messageRep.GetAll().ToList(); var existingMessage = existingMessages.Find(m => m.MessageId == 3); Assert.IsNotNull(existingMessage); existingMessage.Body = ""; existingMessage.Sent = DateTime.Now; existingMessage.MessageStatus = MessageStatus.Received; //check for validation rules //existingMessage.Body = ""; //existingMessage.Sent = DateTime.Now; //existingMessage.MessageStatus = MessageStatus.Not_Specified; messageRep.Attach(existingMessage); uow.Entry(existingMessage).State = EntityState.Modified; try { uow.SaveChanges(); } catch (DbEntityValidationException ex) { //Retrieve validation errors ex.EntityValidationErrors.ToList().ForEach ( v => { v.ValidationErrors.ToList().ForEach ( e => { System.Diagnostics.Debug.WriteLine(e.ErrorMessage); } ); } ); Assert.Fail("Test failed"); } }; //retrieve saved object var uow1 = new CapriconContext(); var repository = new MessageRepository(uow1); var savedMessages = repository.GetAll().ToList(); Assert.AreEqual(savedMessages[0].MessageId, 1); }
public TestPushToCouchDBReceiver() { _messageRepository = new MessageRepository(); _tagRepository = new TagRepository(); _target = new PushToCouchDBReceiver() { CouchServer = "http://*****:*****@chchneeds.couchone.com", CouchDB = "unit_test" }; }
public MessageAction() { _messageRepository = new MessageRepository(); }