private void NewChat_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count != 1) { return; } UserModel selectedUser = (UserModel)((LongListSelector)sender).SelectedItem; AllConversationsViewModel existingConversations = ViewModelLocator.Instance.CreateOrGetViewModel <AllConversationsViewModel>(); ConversationModel existingConversation = existingConversations.GetConversation(selectedUser.Id); Guid conversationId; if (existingConversation != null) { conversationId = existingConversation.ConversationId; } else { conversationId = Guid.Empty; } NavigationService.Navigate(new Uri(string.Format("/Views/ConversationMessagesView.xaml?conversationId={0}&recipientId={1}&recipientName={2}&isGroup={3}&pivot=0", conversationId, selectedUser.Id, selectedUser.Name, selectedUser.UserType == UserType.Group), UriKind.Relative)); }
private string GetConversationMessagesViewUri(ConversationModel selectedItemData) { YapperChatViewModel viewModel = (YapperChatViewModel)this.DataContext; viewModel.AllConversations.SelectedConversation = selectedItemData; string uriString = null; UserModel recipient = null; foreach (UserModel user in selectedItemData.ConversationParticipants) { if (!user.Equals(UserSettingsModel.Instance.Me)) { recipient = user; } } if (recipient != null) { uriString = string.Format( "/Views/ConversationMessagesView.xaml?conversationId={0}&recipientName={1}&recipientId={2}&isGroup={3}", selectedItemData.ConversationId, recipient.Name, recipient.Id, selectedItemData.IsGroupConversation); } return(uriString); }
private void NavigateToConversationView(object sender) { if ((sender as ListBox).SelectedIndex < 0) { return; } ConversationModel selectedItemData = (sender as ListBox).SelectedItem as ConversationModel; if (selectedItemData != null && NavigationService != null) { var uriString = GetConversationMessagesViewUri(selectedItemData); if (uriString != null) { NavigationService.Navigate( new Uri( uriString, UriKind.Relative)); selectedItemData.UnreadCount = 0; } } (sender as ListBox).SelectedIndex = -1; }
public async Task <IActionResult> GetConversationById([FromBody] ConversationModel model) { var receiver = await FindByEmailAsync(model.ReceiversEmail); var messages = new List <ReturnMessage>(); _context.Messages.Where(m => m.ConversationId == model.ConversationID).ToList().ForEach(async me => { var content = DecryptWithAes(me, receiver); if (content.Equals(String.Empty)) { var sender = await FindByEmailAsync(model.SendersEmail); content = DecryptWithAes(me, sender); } var rMessage = new ReturnMessage { MessageId = me.Id, Content = content, ConversationId = me.ConversationId, EmailOfSender = me.EmailOfSender, DataIsTrusted = EncryptionServices.VerifyData (content, _context.PublicKeyStores.FirstOrDefault(store => store.Email == me.EmailOfSender) ?.PublicKey, me.SignedData) }; messages.Add(rMessage); } ); return(Ok(messages)); }
/// <summary> /// Добавить или обновить диалог двух пользователей по их идентификаторам /// </summary> /// <param name="firstUser">Идентификатор первого пользователя</param> /// <param name="secondUser">Идентификатор первого пользователя</param> /// <returns>Идентификатор созданные или обновлённые данные о диалоге</returns> public long AddOrUpdateConversation(long firstUser, long secondUser) { var now = DateTime.UtcNow; // Получаем текущие дату и время // Получаем данные о диалоге var conversation = GetConversationByUsersId(firstUser, secondUser); if (conversation == null) // Если диалога не существует { // Создаём данные о ноыом диалоге conversation = new ConversationModel { UserOneID = firstUser, // Первый пользователь UserTwoID = secondUser, // Второй пользователь CreationDate = now, // Текущие дата и время создания ModificationDate = now // Текущие дата и время изменения }; // Добавляем данные о диалоге в хранилище conversationsRepository.Insert(conversation); } else // Если диалог существует { // Изменяем дату изменения на текущую conversation.ModificationDate = DateTime.Now; // можно заменить на now // Обновляем данные о диалоге в хранилище conversationsRepository.Update(conversation); } // Подтверждаем Единицу работы UnitOfWork.Commit(); // Возвращаем идентификатор диалога return(conversation.ID); }
/// <summary> /// Remove one RB Conversation (by ID) from the ViewModel /// </summary> /// <param name="id">Rainbow Conversation's ID</param> private void RemoveRbConversationFromModel(String id) { ConversationModel conversation = GetConversationById(id); lock (lockObservableConversations) DynamicList.Items.Remove(conversation); }
public MainController(IMainView view, ConversationModel conversationModel) { MainView = view; MainConversation = conversationModel; MainView.SetController(this); //mainView.SetMessageList(conv.File.MessageList); }
public async Task <IActionResult> Conversation(string id, string returnUrl = null) { var user = await _userManager.GetUserAsync(HttpContext.User); var otherUser = await _userManager.FindByIdAsync(id); string DocId; string PatId; if (user.AccountType == "Doctor") { DocId = user.Id; PatId = id; } else { DocId = id; PatId = user.Id; } ViewData["ReturnUrl"] = "/Message/Conversation/" + id; var messageList = (from message in _context.Messages where message.DoctorID == DocId && message.PatientID == PatId select message); var data = new ConversationModel(); data.IsDoctor = (user.AccountType == "Doctor"); data.Messages = messageList; data.DisplayName = otherUser.FirstName + " " + otherUser.LastName; return(View(data)); }
/** * 设置用户某会话接收新消息时是否进行消息提醒。 * * @param conversation 会话信息 其中type(必传) * @return ResponseResult **/ public async Task <ResponseResult> UnMute(ConversationModel conversation) { string message = CommonUtil.CheckFiled(conversation, PATH, CheckMethod.UNMUTE); if (null != message) { return(RongJsonUtil.JsonStringToObj <ResponseResult>(message)); } StringBuilder sb = new StringBuilder(); sb.Append("&conversationType=").Append(HttpUtility.UrlEncode(conversation.Type, UTF8)); sb.Append("&requestId=").Append(HttpUtility.UrlEncode(conversation.UserId, UTF8)); sb.Append("&targetId=").Append(HttpUtility.UrlEncode(conversation.TargetId, UTF8)); sb.Append("&isMuted=").Append(HttpUtility.UrlEncode("0", UTF8)); string body = sb.ToString(); if (body.IndexOf("&", StringComparison.OrdinalIgnoreCase) == 0) { body = body.Substring(1, body.Length - 1); } string result = await RongHttpClient.ExecutePost(AppKey, AppSecret, body, RongCloud.ApiHostType.Type + "/conversation/notification/set.json", "application/x-www-form-urlencoded"); return(RongJsonUtil.JsonStringToObj <ResponseResult>( CommonUtil.GetResponseByCode(PATH, CheckMethod.UNMUTE, result))); }
private bool BatchProcessFiles(string[] paths, BackgroundWorker worker) { var model = new ConversationModel(); int progress = 0; foreach (string p in paths) { //Open file if (!model.LoadFromFile(p)) { continue; } //In case no name found if (model.FileCont.Name == null) { model.FileCont.Name = Path.GetFileNameWithoutExtension(p); } //Name new file and export string newFileName = Path.Combine(Path.GetDirectoryName(p), model.FileCont.Name + "_Processed.txt"); model.ExportStrippedFile(newFileName); //Report progress progress++; worker.ReportProgress(progress / paths.Length * 100); } return(true); }
private void ConversationList_SelectedConversationChanged(object sender, Controls.SelectedConversationChangedEventArgs e) { SelectedConversation = e.Conversation; FileList.ClearFiles(); FileList.AddFiles(_files.Where(obj => obj.ConversationId == e.Conversation.Id).ToList()); FileList.Sort(); }
public ActionResult Conversation(ConversationViewModel model) { try { //get conversation data ConversationModel conversation = new ConversationModel(model.ConversationID); if (!ModelState.IsValid) { model.Messages = conversation.Messages; return(View(model)); } //Add message to conversation conversation.AddMessage(model.NewMessageText, model.File); //initiate view model data model = new ConversationViewModel(conversation); return(RedirectToAction("Conversation", "Conversation", model.ConversationID)); } catch (Exception e) { return(RedirectToAction("HandledCodeError", "ErrorHandler", new { exception = e.ToString() })); } }
public async Task SendMessage_ExistConversation() { //Arrange var input = new SendMessageInput() { Message = "message", ReceiverUserName = "******" }; var existsConversation = new ConversationModel() { Id = new ObjectId() }; _mockRepository.Get(Arg.Any <Expression <Func <ConversationModel, bool> > >()) .ReturnsForAnyArgs(existsConversation); //Act await _messageService.SendMessage(input); //Assert await _mockRepository.Received().Update(Arg.Is(existsConversation.Id.ToString()), Arg.Is <ConversationModel>(x => x.Messages.Any(m => m.MessageText == input.Message && m.ReceiverUserName == input.ReceiverUserName && m.SenderUserName == _loggedUser.UserName))); }
public async Task <ConversationModel> FindConversationForEmployee(int employeeId) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(ApiUrl); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, $"conversation?employeeId={employeeId}"); requestMessage.Headers.Add("Authorization", "bearer " + UserToken); var responseString = string.Empty; var response = await client.SendAsync(requestMessage); if (!response.IsSuccessStatusCode) { return(null); } responseString = await response.Content.ReadAsStringAsync(); ConversationModel data = JsonConvert.DeserializeObject <ConversationModel>(responseString); return(data); } }
/// <summary> /// Add one Conversation Model in the ViewModel /// </summary> /// <param name="rbConversation">a Rainbow Conversation object</param> private void AddConversationToModel(ConversationModel newConversation) { if (newConversation != null) { // First remove this conversation if already in the model RemoveRbConversationFromModel(newConversation.Id); lock (lockObservableConversations) { Boolean itemAdded = false; int nb = DynamicList.Items.Count; for (int i = 0; i < nb; i++) { if (newConversation.LastMessageDateTime.ToUniversalTime() > DynamicList.Items[i].LastMessageDateTime.ToUniversalTime()) { DynamicList.Items.Insert(i, newConversation); itemAdded = true; break; } } if (!itemAdded) { DynamicList.Items.Add(newConversation); } // Check if we need to update the view due to DateTime purpose CheckIfUpdateModelForDateTimePurpose(newConversation.LastMessageDateTime); } } }
internal MainController(Interface.IMainView view, ConversationModel model) { mainView = view; targetModel = model; sourceModel = new ConversationModel(); mainView.SetController(this); }
public long AddOrUpdateConversation(long firstUser, long secondUser) { var now = DateTime.UtcNow; var conversation = GetConversationByUsersId(firstUser, secondUser); if (conversation == null) { conversation = new ConversationModel { UserOneID = firstUser, UserTwoID = secondUser, CreationDate = now, ModificationDate = now }; conversationsRepository.Insert(conversation); } else { conversation.ModificationDate = DateTime.Now; conversationsRepository.Update(conversation); } UnitOfWork.Commit(); return(conversation.ID); }
/// <summary> /// Constructor to create new EstablishConversationAsyncResult. /// </summary> /// <param name="destinationQueue">Destination queue.</param> /// <param name="localParticipant">Local participant name.</param> /// <param name="userCallback">User callback.</param> /// <param name="state">User state.</param> internal TerminateConversationAsyncResult(ConversationModel conversationModel, AsyncCallback userCallback, object state) : base(userCallback, state) { Debug.Assert(null != conversationModel, "Conversation model is null."); m_conversationModel = conversationModel; }
public void showConversationPage(ConversationModel conversation) { ConversationPage conversationPage = new ConversationPage(); conversationPage.Title = conversation.ConversationTitle; conversationPage.BindingContext = new ConversationViewModel(conversation); navigation.PushAsync(conversationPage); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { _convModel = (SerializationHelper.Deserialize(Request.Form[_dataKey]) ?? TempData[_dataKey] ?? new ConversationModel()) as ConversationModel; TryUpdateModel(_convModel); }
public JsonResult JsonSend(string key, ConversationModel model) { if (IsBlocked()) { return(Json(new { errors = (IEnumerable <string>) new[] { "Try again!" } })); } return((JsonResult)_Send(key, model, Json(new { success = true, message = "Your message has been sent." }), Json(new { errors = GetErrorsFromModelState() }))); }
public ForceConversation(PlayerEventModel playerEventModel) : base(playerEventModel) { var conversationRepository = new ConversationRepository(ContextMap.DefaultMap); var conversationId = uint.Parse(playerEventModel.EventModel.EventContentsModel.Arg[0]); this.conversationModel = conversationRepository.Get(conversationId); this.isAlive = true; }
public NewEmailMessage(ConversationModel conversation, MainWindow parent, string subject = "") { InitializeComponent(); _parent = parent; if (_parent.EmailClients != null && _parent.EmailClients.Count > 0) { foreach (EmailModel email in _parent.EmailClients) { EmailComboBox.AddItem(email.Address, email.Login != "" && !email.CannotConnect); } if (EmailComboBox.Items.Any(obj => obj.Enabled)) { EmailComboBox.SelectedItem = EmailComboBox.Items.First(obj => obj.Enabled); } } else { EmailComboBox.AddItem("Brak dostępnych adresów e-mail", false); } visibleIdLabel.Content = "(" + conversation.VisibleId + ")"; titleBox.Text = subject; messageBox.Text = ""; Loaded += (s, ea) => { titleBox.Focusable = true; titleBox.Focus(); Keyboard.Focus(titleBox); }; ReadyButton.Clicked += (s, ea) => { if (_parent.EmailClients != null && _parent.EmailClients.Count > 0 && EmailComboBox.SelectedItem != null) { OutputSubject = "(" + conversation.VisibleId + ")" + titleBox.Text; SendingAddress = EmailComboBox.SelectedItem.Caption; Message = messageBox.Text; ReadyButtonClicked?.Invoke(this, EventArgs.Empty); } }; CancelButton.Clicked += (s, ea) => { CancelButtonClicked?.Invoke(this, EventArgs.Empty); }; AddFileFromDisk.Clicked += AddFileFromDisk_Clicked; AddExistingFile.Clicked += AddExistingFile_Clicked; AddFileFromScanner.Clicked += AddFileFromScanner_Clicked; _parent.DownloadClient.FileDownloaded += DownloadClient_FileDownloaded; }
public void ServiceUpdateExistingConversationTest() { List <List <ConversationModel> > conversations = new List <List <ConversationModel> >(); List <UserModel> owners = new List <UserModel>(); this.LoadConversations(conversations, owners); for (int i = 0; i < conversations.Count; i++) { if (conversations[i].Count == 0) { return; } List <ConversationModel> serviceConversation = new List <ConversationModel>(); for (int j = 0; j < conversations[i].Count; j++) { ConversationModel newConversation = new ConversationModel(); newConversation.ConversationId = conversations[i][j].ConversationId; newConversation.ConversationParticipants = conversations[i][j].ConversationParticipants; newConversation.LastPostUtcTime = DateTime.Now; newConversation.LastPostPreview = "New message for conversation" + j.ToString(); serviceConversation.Add(newConversation); } MockServiceProxy serviceProxy = new MockServiceProxy() { Conversations = serviceConversation }; MockUserSettings userSettings = new MockUserSettings(); MockDataContextWrapper dataContextWrapper = new MockDataContextWrapper(new MockDatabase() { Conversations = conversations[i] }); userSettings.Save(owners[i]); using (AllConversationsViewModel allConversations = new AllConversationsViewModel(serviceProxy, userSettings, dataContextWrapper)) { allConversations.LoadInitialConversations(); NotifyCollectionChangedTester <ConversationModel> collectionChangedTester = new NotifyCollectionChangedTester <ConversationModel>(allConversations.Conversations); while (!allConversations.IsLoaded) { System.Threading.Thread.Sleep(1000); } Assert.AreEqual(collectionChangedTester.Count, serviceConversation.Count, "Service proxy changes weren't generated"); for (int j = 0; j < allConversations.Conversations.Count; j++) { Assert.AreEqual(allConversations.Conversations[j].LastPostUtcTime, serviceConversation[j].LastPostUtcTime, "Date didn't match with the service proxy update"); Assert.AreEqual(allConversations.Conversations[j].LastPostPreview, serviceConversation[j].LastPostPreview, "preview didn't match with the service proxy update"); } } } }
public async Task <ConversationModel> GetConversationMessages(string token, int conversationId) { var uri = new Uri(string.Format(Constants.RestUrl + "/api/inbox/conversation/" + conversationId, string.Empty)); string authToken = Preferences.Get("api_key", "null");; ConversationModel response = await _requestService.GetAsync <ConversationModel>(uri.ToString(), authToken); return(response); }
public TwoFileController(IComparisonView view, ConversationModel conversationModel) : base(view, conversationModel) { sourceView = view; sourceConv = new ConversationModel(); sourceView.SetController(this); sourceView.SetMessageList(conversationModel.File.MessageList); SetOptions(); }
/// <summary> /// Constructor to create new SendImMessageAsyncResult. /// </summary> /// <param name="conversationModel">Conversation model.</param> /// <param name="message">Message.</param> /// <param name="userCallback">User callback.</param> /// <param name="state">User state.</param> internal SendImMessageAsyncResult(ConversationModel conversationModel, string message, AsyncCallback userCallback, object state) : base(userCallback, state) { Debug.Assert(null != conversationModel, "Conversation model is null."); m_conversationModel = conversationModel; m_message = message; }
/// <summary> /// Constructor to create new EstablishConversationAsyncResult. /// </summary> /// <param name="localParticipant">Local participant name.</param> /// <param name="userCallback">User callback.</param> /// <param name="state">User state.</param> internal EstablishConversationAsyncResult(ConversationModel conversationModel, Dictionary <string, string> context, AsyncCallback userCallback, object state) : base(userCallback, state) { Debug.Assert(null != conversationModel, "Conversation model is null."); m_conversationModel = conversationModel; m_context = context; }
public Task <AuthenticationServiceResponse> DeleteConversation(ConversationModel conversationModel) { //int id = conversationModel.MessageId.Decrypt(); //var publicMessage = _conversationService.publicMessageRepository.Get(x => x.MessageId == id).FirstOrDefault(); //publicMessage.IsDeleted = true; //_conversationService.publicMessageRepository.Update(publicMessage); return(Task.FromResult(new AuthenticationServiceResponse { Message = "Message Deleted Successfully", Success = true })); }
private void Button1_Click(object sender, EventArgs e) { conversationModel = new ConversationModel( comboBoxIdCity.Text, comboBoxIdSubscriber.Text, textBoxMinute.Value, comboBoxRDay.Text, comboBoxRDay.Text ); if (conversationModel.validate(errorCity, errorSubscribe, errorMinute)) { commandString = $@" INSERT INTO [dbo].[Conversation] ([IdSubScriber] ,[IdCity] ,[Date] ,[CountMinutes] ,[TimesOfDay] ,[PriceConverstation]) VALUES ( '{conversationModel.IDSubscriber}', '{conversationModel.IDCity}', '{conversationModel.date.ToShortDateString()}', '{conversationModel.CountMinutes}', '{conversationModel.date.ToShortTimeString()}', '{conversationModel.PriceConverstation}' )" ; sqlConnection = new SqlConnection(con); try { sqlConnection.Open(); } catch (Exception) { MessageBox.Show("Не удалось подключиться"); } command = new SqlCommand(commandString, sqlConnection); command.ExecuteNonQuery(); sqlConnection.Close(); DataTable DT = dataGridView1.DataSource as DataTable; DT.Clear(); adapter.Fill(tableConversation); ValidateController.CleanerNumeric(textBoxMinute); } else { MessageBox.Show("Заполните данные"); } }