public void SendChatMessage(ChatModel model) { string userName = Context.User.Identity.Name; // Clients.Client(Context.ConnectionId).addChatMessage(userName, model.ChatMsgBoxtext); foreach (var connectionId in _connections.GetConnections(model.ChatFriendName)) { int hostId = model.ChatHostId; model.ChatHostName = model.ChatFriendName; model.ChatFriendName = Context.User.Identity.Name; model.ChatHostId = model.ChatFriendId; model.ChatFriendId = hostId; Clients.Client(connectionId).appendChatBoxOnFriend(model); //Clients.Client(connectionId).addChatMessage(model.ChatFriendName, model.ChatMsgBoxtext); } }
public ChatView GetChat(ChatModel chatModel) { return(f_Notebook.GetChat(chatModel)); }
/// <summary> /// LoadConversationToStack Loads the users conversation /// </summary> /// <param name="Stack"> the parent stack</param> /// <param name="RecepientID"> the ID of the receiver</param> public static async Task LoadConversationToStack(StackLayout Stack, int RecepientID, bool IsLocalLoaded, Grid ChatControlGrid, int LastID = 0) { int LastMessageID = LastID; JObject ConversationDecodedJson = new JObject(); String ConversationResponseJson = ""; //if false, then local db is empty else info is loaded from local db if (!IsLocalLoaded) { Device.BeginInvokeOnMainThread(delegate { Stack.Children.Clear(); }); System.Diagnostics.Debug.WriteLine("IN IF, Old Last Server " + LastServerChatId); ConversationResponseJson = await ChatModel.Chat(Utilities.PostDataEncoder(new Dictionary <int, string[]> { { 0, new String[] { "sender", Utilities.ID.ToString() } }, { 1, new String[] { "receiver", RecepientID.ToString() } }, }), "chat/conversations"); ConversationDecodedJson = JObject.Parse(ConversationResponseJson); LastMessageID = (int)ConversationDecodedJson["conversations"].Last["id"]; var LastMessageDate = DateTime.Parse(ConversationDecodedJson["conversations"].Last["time"].ToString()); if ((DateTime.Now.Day - LastMessageDate.Day) >= 7)///one week since last chat disabled messaging { Device.BeginInvokeOnMainThread(delegate { ChatControlGrid.IsVisible = false; }); } await Utilities.RunTask(async delegate { foreach (var conversation in ConversationDecodedJson["conversations"]) { await ChatHandler.InsertMessage(conversation["message"].ToString(), conversation["time"].ToString(), (bool)conversation["sent"], RecepientID, MessageType.Text, true, (int)conversation["id"], Utilities.ID.ToString() + "-" + RecepientID); if (conversation["message"].ToString() == "{Appointment Accepted, Default Message}") { var ChildStack = new Grid { HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(10, 2, 10, 2) }; ChildStack.Children.Add(new Label { Text = conversation["message"].ToString().Replace(", Default Message", "").Replace("{", "").Replace("}", ""), BackgroundColor = (Color)App.Current.Resources["_MedAppBlack"], TextColor = Color.White, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HeightRequest = 30, HorizontalOptions = LayoutOptions.FillAndExpand }); Device.BeginInvokeOnMainThread(() => { Stack.Children.Add(ChildStack); ControlTagger <String> .SetTag(Stack, conversation["id"].ToString()); }); } else { DateTime MessageTime = DateTime.Parse(conversation["time"].ToString()); String MessageTimeString = ""; if (MessageTime.Day != DateTime.Now.Day && MessageTime.Month == DateTime.Now.Month) { MessageTimeString = MessageTime.ToString(""); } Device.BeginInvokeOnMainThread(() => { Stack.Children.Add(SingleMessageTemplate.CreateMessage01((Convert.ToBoolean(conversation["sent"]) ? 1 : 0), conversation["message"].ToString(), Utilities.GetValidatedTime(MessageTime, ChatSectionType.Chat))); ControlTagger <String> .SetTag(Stack, conversation["id"].ToString()); }); } } }); } ///Update chat in Background while (ListenForNewConversation) { ConversationResponseJson = await ChatModel.Chat(Utilities.PostDataEncoder(new Dictionary <int, string[]> { { 0, new String[] { "sender", Utilities.ID.ToString() } }, { 1, new String[] { "receiver", RecepientID.ToString() } }, }), "chat/conversations"); ConversationDecodedJson = JObject.Parse(ConversationResponseJson); if (LastMessageID < (int)ConversationDecodedJson["conversations"].Last["id"]) { await Utilities.RunTask(async delegate { foreach (var conversation in ConversationDecodedJson["conversations"]) { if ((int)conversation["id"] > LastMessageID) { LastServerChatId = (int)conversation["id"]; ///save updates locally await ChatHandler.InsertMessage(conversation["message"].ToString(), conversation["time"].ToString(), (bool)conversation["sent"], RecepientID, MessageType.Text, true, (int)conversation["id"], Utilities.ID + "-" + RecepientID); if (conversation["message"].ToString() == "{Appointment Accepted, Default Message}") { var ChildStack = new Grid { HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(10, 2, 10, 2) }; ChildStack.Children.Add(new Label { Text = conversation["message"].ToString().Replace(", Default Message", "").Replace("{", "").Replace("}", ""), BackgroundColor = (Color)App.Current.Resources["_MedAppBlack"], TextColor = Color.White, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HeightRequest = 30, HorizontalOptions = LayoutOptions.FillAndExpand }); Device.BeginInvokeOnMainThread(() => { Stack.Children.Add(ChildStack); ControlTagger <int> .SetTag(Stack, (int)conversation["id"]); }); } else { DateTime MessageTime = DateTime.Parse(conversation["time"].ToString()); String MessageTimeString = ""; if (MessageTime.Day != DateTime.Now.Day && MessageTime.Month == DateTime.Now.Month) { MessageTimeString = MessageTime.ToString(""); } Device.BeginInvokeOnMainThread(() => { Stack.Children.Add(SingleMessageTemplate.CreateMessage01((Convert.ToBoolean(conversation["sent"]) ? 1 : 0), conversation["message"].ToString(), Utilities.GetValidatedTime(MessageTime, ChatSectionType.Chat))); ControlTagger <int> .SetTag(Stack, (int)conversation["id"]); }); } } } }); LastMessageID = (int)ConversationDecodedJson["conversations"].Last["id"]; } } }
public ActionResult Index(string user, bool?logOn, bool?logOff, string chatMessage) { try { if (chatModel == null) { chatModel = new ChatModel(); } //оставляем только последние 10 сообщений if (chatModel.Messages.Count > 15) { chatModel.Messages.RemoveRange(0, chatModel.Messages.Count - 10); } // если обычный запрос, просто возвращаем представление if (!Request.IsAjaxRequest()) { return(View(chatModel)); } // если передан параметр logOn else if (logOn != null && (bool)logOn) { //проверяем, существует ли уже такой пользователь if (chatModel.Users.FirstOrDefault(u => u.Name == user) != null) { throw new Exception("Пользователь с таким ником уже существует"); } else if (chatModel.Users.Count > 10) { throw new Exception("Чат заполнен"); } else { // добавляем в список нового пользователя chatModel.Users.Add(new ChatUser() { Name = user, LoginTime = DateTime.Now, LastPing = DateTime.Now }); // добавляем в список сообщений сообщение о новом пользователе chatModel.Messages.Add(new ChatMessage() { Text = user + " вошел(а) в чат", Date = DateTime.Now }); } return(PartialView("ChatRoom", chatModel)); } // если передан параметр logOff else if (logOff != null && (bool)logOff) { LogOff(chatModel.Users.FirstOrDefault(u => u.Name == user)); return(PartialView("ChatRoom", chatModel)); } else { ChatUser currentUser = chatModel.Users.FirstOrDefault(u => u.Name == user); //для каждлого пользователя запоминаем воемя последнего обновления currentUser.LastPing = DateTime.Now; // удаляем неавтивных пользователей, если время простоя больше 15 сек List <ChatUser> toRemove = new List <ChatUser>(); foreach (Models.ChatUser usr in chatModel.Users) { TimeSpan span = DateTime.Now - usr.LastPing; if (span.TotalSeconds > 15) { toRemove.Add(usr); } } foreach (ChatUser u in toRemove) { LogOff(u); } // добавляем в список сообщений новое сообщение if (!string.IsNullOrEmpty(chatMessage)) { chatModel.Messages.Add(new ChatMessage() { User = currentUser, Text = chatMessage, Date = DateTime.Now }); } return(PartialView("History", chatModel)); } } catch (Exception ex) { //в случае ошибки посылаем статусный код 500 Response.StatusCode = 500; return(Content(ex.Message)); } }
/// <summary> /// 直接跳跃到对应的聊天界面 /// </summary> /// <param name="group"></param> public void JumpToChatModel(IChat chat, bool isJumpToChat = false, string tipMsg = "", bool isFileAssistant = false) { bool isGroup = (chat is GroupModel) ? true : false; var chatVM = this.ChatListVM.Items.ToList().FirstOrDefault(info => info.Model.ID == chat.ID && info.IsGroup == isGroup); if (!this.ChatListVM.ChatVMDic.ContainsKey(chat.ID, isGroup)) { if (chatVM == null) { ChatModel chatModel = new ChatModel(chat); chatModel.LastMsg = new MessageModel() { SendTime = DateTime.Now, TipMessage = tipMsg }; chatVM = new ChatViewModel(chatModel); App.Current.Dispatcher.Invoke(new Action(() => { if (chatVM.IsGroup) { chatVM.IsShowGroupNoticeBtn = true; } else { chatVM.IsShowGroupNoticeBtn = false; } this.ChatListVM.Items.Add(chatVM); })); } } if (!isFileAssistant) { bool isTemporaryChat; if (chat is UserModel userModel && (userModel.LinkDelType == 1 || userModel.LinkDelType == 3)) { chat.TopMostTime = chat.TopMostTime ?? DateTime.MinValue; isTemporaryChat = true; if (AppData.MainMV.ChatListVM.StrangerChatIds.Any(x => x == userModel.ID)) { chatVM.CurrentChatType = ChatType.Stranger; } else { chatVM.CurrentChatType = ChatType.Temporary; } int sex = userModel.Sex == "女" ? 0 : 1; ThreadPool.QueueUserWorkItem(async m => { await SDKClient.SDKClient.Instance.InsertOrUpdateStrangerInfo(userModel.ID, userModel.HeadImgMD5, userModel.Name, sex); }); } else { isTemporaryChat = false; } chatVM.IsTemporaryChat = isTemporaryChat; this.ChatListVM.DeleteStrangerItem(chatVM, isTemporaryChat); App.Current.Dispatcher.Invoke(() => { AppData.MainMV.ChatListVM.ResetSort(); }); if (chatVM.Chat.IsGroup) { chatVM.IsShowGroupNoticeBtn = true; SDKClient.SDKClient.Instance.UpdateChatRoomVisibility(chat.ID, 1, true); } else { chatVM.IsShowGroupNoticeBtn = false; SDKClient.SDKClient.Instance.UpdateChatRoomVisibility(chat.ID, 0, true); } }
public async Task SendParseEvent(ChatModel chat, Chat_ParseField field, bool success, bool searchMode, string answer) { var content = CreateParseEventContent(chat, field, success, searchMode); var filteredAnswer = filterService.FilterUserData(chat.CurrentState, answer); content.Parse = new { rule = field.RuleData, answer = filteredAnswer }; content.Result = filteredAnswer; content.ResultProbability = success ? 1.0 : 0.0; string indexType = "intent_unknown"; switch (field.ParseType) { case ChatRuleType.AddressParser: indexType = "intent_address"; break; case ChatRuleType.AppNameParser: indexType = "intent_appname"; break; case ChatRuleType.BluetoothDeviceParser: indexType = "intent_bluetoothdevice"; break; case ChatRuleType.ColorParser: indexType = "intent_color"; break; case ChatRuleType.ContinueParser: indexType = "intent_continue"; break; case ChatRuleType.DontKnowParser: indexType = "intent_dontknow"; break; case ChatRuleType.DateParser: case ChatRuleType.DateParserV2: indexType = "intent_date"; break; case ChatRuleType.Email: indexType = "intent_email"; break; case ChatRuleType.FuzzyMatch: indexType = "intent_fuzzymatch"; break; case ChatRuleType.IntentGatewayParser: indexType = "intent_intentgateway"; break; case ChatRuleType.LossCategoryParserOptions: case ChatRuleType.LossCategoryParser: indexType = "intent_losscategory"; break; case ChatRuleType.NameParse: case ChatRuleType.NameParseNoHistory: indexType = "intent_name"; break; case ChatRuleType.NumberParser: indexType = "intent_number"; break; case ChatRuleType.Parse: indexType = "intent"; break; case ChatRuleType.ParseBackupProvider: indexType = "intent_backupprovider"; break; case ChatRuleType.ParseCarrier: indexType = "intent_carrier"; break; case ChatRuleType.ParseDevice: indexType = "intent_device"; break; case ChatRuleType.ParseRetailPartner: indexType = "intent_retailpartner"; break; case ChatRuleType.PauseParser: indexType = "intent_pause"; break; case ChatRuleType.PhoneNumber: case ChatRuleType.PhoneNumberNoHistory: indexType = "intent_phone"; break; case ChatRuleType.Regex: indexType = "intent_regex"; break; case ChatRuleType.TimeParser: indexType = "intent_time"; break; case ChatRuleType.YesNoParser: indexType = "intent_yesno"; break; case ChatRuleType.ZipCodeParser: indexType = "intent_zipcode"; break; } await InternalSendKinesisParseEvent(field.ParseType, indexType, chat, content); }
public void receiveMessage(ChatModel message) { MessagingCenter.Send <MessageCenterManager, ChatModel>(this, "messageReceived", message); }
public async void LoginExecute() { if (Username == TextConstants.SystemUsername) { MessageBox.Show(TextConstants.TextUsernameDenied); return; } Chat = new ChatModel(Username, Port); Chat.UsernameDenied += (sender, args) => OnUsernameDenied(); Chat.DisableNormalChat = true; _usernameDenied = false; Chat.SendCheckUsername(); LoginButtonVisibility = Visibility.Collapsed; ProcessingBarVisibility = Visibility.Visible; await Task.Delay(2000); Chat.DisableNormalChat = false; Chat.UsernameDenied = null; LoginButtonVisibility = Visibility.Visible; ProcessingBarVisibility = Visibility.Collapsed; if (_usernameDenied) { MessageBox.Show(TextConstants.TextUsernameDenied); return; } Chat.SendNewUser(); ChatInterfaceVisibility = Visibility.Visible; LoginInterfaceVisibility = Visibility.Collapsed; }
/** * 0 = Reply Message * 1 = Delete Message * 2 = Copy to Message **/ public void sendAction(ChatModel message, int category) { MessagingCenter.Send <MessageCenterManager, ChatModel>(this, category.ToString(), message); }
public void sendMessage(ChatModel message) { MessagingCenter.Send <MessageCenterManager, ChatModel>(this, "sendMessage", message); }
//--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- private void OnNewMucMemberPresenceMessage(XMPPClient client, NewMUCMemberPresenceMessageEventArgs args) { Task.Run(async() => { MUCMemberPresenceMessage msg = args.mucMemberPresenceMessage; string roomJid = Utils.getBareJidFromFullJid(msg.getFrom()); if (roomJid is null) { return; } SemaLock semaLock = DataCache.INSTANCE.NewChatSemaLock(); ChatModel chat = DataCache.INSTANCE.GetChat(client.getXMPPAccount().getBareJid(), roomJid, semaLock); semaLock.Dispose(); if (chat is null || chat.muc is null) { return; } // Prevent multiple accesses to the same occupant at the same time: await OCCUPANT_CREATION_SEMA.WaitAsync(); MucOccupantModel occupant = chat.muc.occupants.Where(o => string.Equals(o.nickname, msg.FROM_NICKNAME)).FirstOrDefault(); bool newOccupant = occupant is null; if (newOccupant) { occupant = new MucOccupantModel() { nickname = msg.FROM_NICKNAME }; } occupant.affiliation = msg.AFFILIATION; occupant.role = msg.ROLE; occupant.fullJid = msg.JID; bool isUnavailable = Equals(msg.TYPE, "unavailable"); bool nicknameChanged = false; if (isUnavailable) { if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.PRESENCE_SELFE_REFERENCE)) { // Nickname got changed by user or room: if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.MEMBER_NICK_CHANGED) || msg.STATUS_CODES.Contains(MUCPresenceStatusCode.ROOM_NICK_CHANGED)) { nicknameChanged = true; // Update MUC info: chat.muc.nickname = msg.NICKNAME; // Update the user nickname: occupant.nickname = msg.NICKNAME; } // Occupant got kicked: else if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.MEMBER_GOT_KICKED)) { chat.muc.state = MucState.KICKED; } else if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.MEMBER_GOT_BANED)) { chat.muc.state = MucState.BANED; } else { chat.muc.state = MucState.DISCONNECTED; } } if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.MEMBER_GOT_KICKED)) { // Add kicked chat message: AddOccupantKickedMessage(chat, roomJid, occupant.nickname); } if (msg.STATUS_CODES.Contains(MUCPresenceStatusCode.MEMBER_GOT_BANED)) { // Add baned chat message: AddOccupantBanedMessage(chat, roomJid, occupant.nickname); } } using (SemaLock mucSemaLock = chat.muc.NewSemaLock()) { using (SemaLock occupantSemaLock = occupant.NewSemaLock()) { // If the type equals 'unavailable', a user left the room: if (isUnavailable && !nicknameChanged) { if (!newOccupant) { using (MainDbContext ctx = new MainDbContext()) { chat.muc.occupants.Remove(occupant); chat.muc.OnOccupantsChanged(); ctx.Update(chat.muc); } using (MainDbContext ctx = new MainDbContext()) { ctx.Remove(occupant); } } } else { if (newOccupant) { occupant.Add(); chat.muc.occupants.Add(occupant); chat.muc.OnOccupantsChanged(); using (MainDbContext ctx = new MainDbContext()) { ctx.Update(chat.muc); } } else { using (MainDbContext ctx = new MainDbContext()) { ctx.Update(occupant); } } } } } OCCUPANT_CREATION_SEMA.Release(); }); }
public ActionResult PostReply(ChatModel chat) { return Json(new { message = chat.Message, user = User.Identity.Name }); }
public void DisconnectExecute() { if (Chat != null) { Chat.SendUserLeaving(); Chat.Disconnect(); } _chat = null; ChatInterfaceVisibility = Visibility.Collapsed; LoginInterfaceVisibility = Visibility.Visible; }
public GroupChatView(ChatModel chat) : base(chat) { InitializeComponents(); }
public async Task AddChat([FromBody] ChatModel model) { model.user = manager.CurrentUser; await db.AddChat(model); }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public OnChatMessageToastEventArgs(ToastNotification toast, ChatModel chat) { TOAST = toast; CHAT = chat; }
public async Task SendChat(ChatModel chat) { await _hubConnection.SendAsync("AddChat", chat); }
/// <summary> /// 聊天记录VM /// </summary> /// <param name="view"></param> public ChatHistoryViewModel(ChatModel model) : base(model) { _targetChat = model; _hisMessages = new List <MessageModel>(); }
public ActionResult PostReply(ChatModel chat) { return(Json(new { message = chat.Message, user = User.Identity.Name })); }
public ChatScriptHost(ChatModel chatModel, ChatConfiguration configuration) { this.chatModel = chatModel; this.Configuration = configuration; }
public ChatModel Add(ChatModel chatModel) { context.ChatModel.Add(chatModel); context.SaveChanges(); return(chatModel); }
/// <summary> /// ChatsListToStack loads all the users conversation onto the specified stacklayout /// </summary> /// <param name="Stack"></param> /// <param name="Con"></param> public static async Task ChatsListToStack(StackLayout Stack, ContentPage Con, bool IsLocalLoaded = false) { if (!IsLocalLoaded) { Device.BeginInvokeOnMainThread(() => { Stack.Children.Clear(); }); } do { System.Diagnostics.Debug.WriteLine("Stack Child COunt" + Stack.Children.Count); try { Dictionary <int, String[]> ChatData = new Dictionary <int, string[]>(); Dictionary <int, String[]> Data = new Dictionary <int, string[]> { { 0, new String[] { "sender", Utilities.ID.ToString() } }, }; String ChatListResponseJson = await ChatModel.Chat(Utilities.PostDataEncoder(Data), "chat/get-list"); var ChatListDecodedJson = JObject.Parse(ChatListResponseJson); foreach (var Contact in ChatListDecodedJson["contacts"]) { ChatData.Add((int)Contact["info"]["id"], new string[5]); // key = receivers id ChatData[(int)Contact["info"]["id"]][0] = Contact["info"]["name"].ToString(); //index 0 = name String ConversationResponseJson = await ChatModel.Chat(Utilities.PostDataEncoder(new Dictionary <int, string[]> { { 0, new String[] { "sender", Utilities.ID.ToString() } }, { 1, new String[] { "receiver", Contact["info"]["id"].ToString() } }, }), "chat/conversations"); //System.Diagnostics.Debug.WriteLine(ConversationResponseJson); var ConversationDecodedJson = JObject.Parse(ConversationResponseJson); //System.Diagnostics.Debug.WriteLine("JSON" + ConversationDecodedJson["conversations"].Last); //System.Diagnostics.Debug.WriteLine("JSON" + ConversationDecodedJson["conversations"].Last["message"]); if (ConversationDecodedJson["conversations"].Last["message"].ToString() == "{Appointment Accepted, Default Message}") { ChatData[(int)Contact["info"]["id"]][1] = ConversationDecodedJson["conversations"].Last["message"].ToString();//index 1 = message } else { ChatData[(int)Contact["info"]["id"]][1] = ((bool)ConversationDecodedJson["conversations"].Last["sent"] ? "You: " : ""); ChatData[(int)Contact["info"]["id"]][1] += ConversationDecodedJson["conversations"].Last["message"].ToString(); } //System.Diagnostics.Debug.WriteLine("DICT" + ChatData[(int)Contact["info"]["id"]][1]); ChatData[(int)Contact["info"]["id"]][2] = ConversationDecodedJson["conversations"].Last["time"].ToString(); // index 2 = date try { ChatData[(int)Contact["info"]["id"]][3] = Contact["info"]["medic_id"].ToString(); //index 3 = medic id } catch { ///exception thrown and caught as the current receiver doesnt have a medic id since he/she is a normal user(patient) ChatData[(int)Contact["info"]["id"]][3] = "0"; } //last conversation id, index 4 = id of the last message for the current convo on the online db ChatData[(int)Contact["info"]["id"]][4] = ConversationDecodedJson["conversations"].Last["id"].ToString(); ///if local receiver doesnt exist, add to local db int Result = await ReceiverHandler.CheckReceiver((int)Contact["info"]["id"]); if (Result == 0) { await ReceiverHandler.NewReceiver(ChatData[(int)Contact["info"]["id"]][0], (int)Contact["info"]["id"], "", Convert.ToInt32(ChatData[(int)Contact["info"]["id"]][3])); } } await Utilities.RunTask(delegate { if (ChatData.Count > 0) { foreach (int key in ChatData.Keys) { if (Stack.Children.Count >= 4) { continue; } System.Diagnostics.Debug.WriteLine(" Count " + ChatData.Count + " [0] " + ChatData[key][0] + " [1] " + ChatData[key][1] + " [2] " + ChatData[key][2] + " [3] " + ChatData[key][3] + " [4] " + ChatData[key][4]); Device.BeginInvokeOnMainThread(async() => { StackLayout ChildStack; if (Stack.Children.Count > 0 && Stack.Children[0].GetType() == typeof(Label)) { ///clear message stack if default 'no chat message is shown' Stack.Children.Clear(); } if (Stack.Children.Count > 0) { ///IsNewConversation is true by default, the value is changed if the conversation exists on the chat list stack bool IsNewConversation = true; for (int i = 0; i < Stack.Children.Count; i++) { var child = Stack.Children[i]; //if the child is already on stack, recreate that child if different values String[] ChildStackTag = ControlTagger <String> .GetTag(child).Split('-'); ///receiver exists in stack if (key == Convert.ToInt32(ChildStackTag[1])) { System.Diagnostics.Debug.WriteLine("Is Old Convo :- False"); int NewMessageCount = await GetCountOfNewMessages(key, Convert.ToInt32(ChildStackTag[2])); System.Diagnostics.Debug.WriteLine("Child in Stack With Tag [" + ChildStackTag[0] + "-" + ChildStackTag[1] + "-" + ChildStackTag[2] + "-" + ChildStackTag[3] + "] Tag [" + Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + NewMessageCount + "] Last Server ID " + Convert.ToInt32(ChatData[key][4])); //receiver if ((Convert.ToInt32(ChildStackTag[2]) < Convert.ToInt32(ChatData[key][4]))) { /// create notification to show mew message List <Object> ListForNotification = new List <object>(); if (ChatData[key][1].Equals("{Appointment Accepted, Default Message}")) { ListForNotification.Add(ChatData[key][1].Replace(", Default Message", "").Replace("{", "").Replace("}", ""));//index 0 message } else { //ListForNotification.Add(ChatData[key][1]);//index 0 message ListForNotification.Add("" + NewMessageCount + " new messages from " + ChatData[key][0]);//index 0 message } ListForNotification.Add(ChatData[key][2]); //index 1 time ListForNotification.Add(NotificationType.Chat); //index 2 notificationtype ListForNotification.Add(key); // index 3 id NotificationPage.NotificationData.Add(NotificationPage.NotificationData.Count, ListForNotification); Stack.Children.RemoveAt(i); ChildStack = ListAllChatTemplate.CreateNewStackType01(ChatData[key][0], "", ChatData[key][1], Utilities.GetValidatedTime(DateTime.Parse(ChatData[key][2]), ChatSectionType.ChatList), Con, key, NewMessageCount, Convert.ToInt32(ChatData[key][3])); //ChildStack = new StackLayout { BackgroundColor = Color.Tomato }; ControlTagger <String> .SetTag(ChildStack, Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + NewMessageCount); //Stack.Children.Add(ChildStack); Stack.Children.Insert(0, ChildStack); } ///IsNewConversation is false as the current key exists in the chat list stack IsNewConversation = false; } } System.Diagnostics.Debug.WriteLine("Done, Status :- " + IsNewConversation); ///If IsNewConversation is true, this key is a new conversaton, create new childstack if (IsNewConversation) { ///{Appointment Accepted, Default Message} is the default sent message, create different view for it if (ChatData[key][1].Equals("{Appointment Accepted, Default Message}")) { ChatData[key][1] = ChatData[key][1].Replace(", Default Message", "").Replace("{", "").Replace("}", ""); ChildStack = ListAllChatTemplate.CreateNewStackType01(ChatData[key][0], "", ChatData[key][1], Utilities.GetValidatedTime(DateTime.Parse(ChatData[key][2]), ChatSectionType.ChatList), Con, key, 0, Convert.ToInt32(ChatData[key][3])); ControlTagger <String> .SetTag(ChildStack, Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + 0); Stack.Children.Insert(Stack.Children.Count, ChildStack); } else { ChildStack = ListAllChatTemplate.CreateNewStackType01(ChatData[key][0], "", ChatData[key][1], Utilities.GetValidatedTime(DateTime.Parse(ChatData[key][2]), ChatSectionType.ChatList), Con, key, 0, Convert.ToInt32(ChatData[key][3])); ControlTagger <String> .SetTag(ChildStack, Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + 0); Stack.Children.Insert(Stack.Children.Count, ChildStack); } } } else { ///{Appointment Accepted, Default Message} is the default sent message, create different view for it if (ChatData[key][1].Equals("{Appointment Accepted, Default Message}")) { /// create notification to show the appointment has been accepted List <Object> ListForNotification = new List <object>(); ListForNotification.Add(ChatData[key][1].Replace(", Default Message", "").Replace("{", "").Replace("}", "")); //index 0 message ListForNotification.Add(ChatData[key][2]); //index 1 time ListForNotification.Add(NotificationType.Appointment); //index 2 notificationtype ListForNotification.Add(key); // index 3 id NotificationPage.NotificationData.Add(NotificationPage.NotificationData.Count, ListForNotification); System.Diagnostics.Debug.WriteLine("Adding"); ChatData[key][1] = ChatData[key][1].Replace(", Default Message", "").Replace("{", "").Replace("}", ""); ChildStack = ListAllChatTemplate.CreateNewStackType01(ChatData[key][0], "", ChatData[key][1], Utilities.GetValidatedTime(DateTime.Parse(ChatData[key][2]), ChatSectionType.ChatList), Con, key, 0, Convert.ToInt32(ChatData[key][3])); ControlTagger <String> .SetTag(ChildStack, Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + 0); Stack.Children.Insert(Stack.Children.Count, ChildStack); } else { ChildStack = ListAllChatTemplate.CreateNewStackType01(ChatData[key][0], "", ChatData[key][1], Utilities.GetValidatedTime(DateTime.Parse(ChatData[key][2]), ChatSectionType.ChatList), Con, key, 0, Convert.ToInt32(ChatData[key][3])); ControlTagger <String> .SetTag(ChildStack, Utilities.ID + "-" + key + "-" + ChatData[key][4] + "-" + 0); Stack.Children.Insert(Stack.Children.Count, ChildStack); } } }); } } else { Device.BeginInvokeOnMainThread(() => { if (Stack.Children.Count == 0) { Stack.Children.Add(new Label { Text = (!Utilities.IsMedic) ? "Chats will appear after booking an appointment." : "Chats will appear after accepting an appointment.", Style = App.Current.Resources["_EmptyLabelTemplate"] as Style }); } }); } }); } catch (Exception ex) { await App.Current.MainPage.DisplayAlert("Alert", ex.StackTrace, "Ok"); } } while (ListenForChatListUpdate); }
public ActionResult Index(string user, bool?logOn, bool?logOff, string chatMessage) { try { if (chatModel == null) { chatModel = new ChatModel(); } if (chatModel.Messages.Count > 20) { chatModel.Messages.RemoveRange(0, 10); } if (!Request.IsAjaxRequest()) { return(View(chatModel)); } else if (logOn != null && (bool)logOn) { if (chatModel.Users.FirstOrDefault(u => u.Name == user) != null) { throw new Exception("такой пользователь уже есть"); } else if (chatModel.Users.Count > 10) { throw new Exception("В чате слишком много людей"); } else { chatModel.Users.Add(new ChatUser() { Name = user, LoginTime = DateTime.Now, LastPing = DateTime.Now }); chatModel.Messages.Add(new ChatMessage() { Text = user + "вошел в чат", Date = DateTime.Now }); } return(PartialView("ChatRoom", chatModel)); } else if (logOff != null && (bool)logOff) { LogOff(chatModel.Users.FirstOrDefault(u => u.Name == user)); return(PartialView("ChatRoom", chatModel)); } else { ChatUser currentUser = chatModel.Users.FirstOrDefault(u => u.Name == user); currentUser.LastPing = DateTime.Now; if (!string.IsNullOrEmpty(chatMessage)) { chatModel.Messages.Add(new ChatMessage() { User = currentUser, Text = chatMessage, Date = DateTime.Now }); } return(PartialView("History", chatModel)); } } catch (Exception ex) { Response.StatusCode = 500; return(Content(ex.Message)); } }
public void Send(ChatModel model) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(model); }
public static void ChangeActiveChat(ChatModel chatModel) { Console.WriteLine("Active chat: " + chatModel.Name); _FrontendManager.CurrentChat = chatModel; }
/// <summary> /// Loads the "MissingFlow" flow /// </summary> /// <param name="chatModel">Chat Model used to process partner/context, channel</param> /// <returns>MissingFlow step</returns> public async Task <ChatFlowStep> GetMissingFlow(ChatModel chatModel) { return(await GetFlowStep(chatModel, $"MissingFlow", "9999999")); }
public JsonResult Ajax(string AJAXParameter1) { chat = (ChatModel)TempData["Chat"]; string result = "OK"; customer = (CustomerData)TempData["CustomerObj"]; //customer.ACCOUNTS = (List<Account>)TempData["AccountObj"]; //customer.PLAN = (PaymentPlan)TempData.Peek("PaymentObj"); //customer.PLAN.TAKSIT_SAYISI = 8; JsonSendTable tableInfo = new JsonSendTable(); JsonSendTable paymentPlanTable = new JsonSendTable(); AJAXParameter1 = AJAXParameter1.Trim(); StateOfChat = (string)TempData["StateOfChat"]; conn = (OracleDatabaseAccess)TempData["DatabaseConnection"]; if (TempData["StateOfChat"].Equals("GetMüsNo") || TempData["StateOfChat"].Equals("InvalidMüsNo")) { if (IsAllDigits(AJAXParameter1) && !String.IsNullOrEmpty(AJAXParameter1)) { customer = conn.GetCustomerInfo(Int32.Parse(AJAXParameter1)); if (customer.MUSTERI_NO != 0) { customer.ACCOUNTS = conn.GetCustomerAccounts(customer.MUSTERI_NO); chat.usersChat.Add("GetMüsNo", AJAXParameter1); StateOfChat = "ValidMüsNo"; TempData["StateOfChat"] = StateOfChat; chat.botCorrectPath.Add("ValidMüsNo", "Merhaba " + customer.MUSTERI_ADI + ", karton bilgileriniz size gösterilecektir."); if (customer.ACCOUNTS.Count > 0) { result = "Table"; tableInfo.message = chat.botCorrectPath[StateOfChat]; decimal total = customer.ACCOUNTS[0].BAKIYE; tableInfo.tableData = "<tr>" + "<td>" + customer.ACCOUNTS[0].KARTON_KODU + "</td>" + "<td>" + customer.ACCOUNTS[0].BAKIYE + "</td>" + "</tr>"; for (int i = 1; i < customer.ACCOUNTS.Count; i++) { total += customer.ACCOUNTS[i].BAKIYE; tableInfo.tableData += "<tr>" + "<td>" + customer.ACCOUNTS[i].KARTON_KODU + "</td>" + "<td>" + customer.ACCOUNTS[i].BAKIYE + "</td>" + "</tr>"; } customer.PLAN = new PaymentPlan(); tableInfo.total = total; customer.PLAN.PLAN_ONCESI_BAKIYE = total; customer.PLAN.TOA_DURUM_KODU = '1'; } else { StateOfChat = "NoDebt"; TempData["StateOfChat"] = StateOfChat; chat.botCorrectPath.Add("NoDebt", "Merhaba " + customer.MUSTERI_ADI + ". Aktif borcunuz bulunmuyor. Sistemden çıkış yapabilirsiniz"); result = "Finished"; //Borç un olmadğı state } } else { StateOfChat = "InvalidMüsNo"; TempData["StateOfChat"] = StateOfChat; result = "OK"; } } else { StateOfChat = "InvalidMüsNo"; TempData["StateOfChat"] = StateOfChat; result = "OK"; } } else if (TempData["StateOfChat"].Equals("ValidMüsNo") || TempData["StateOfChat"].Equals("GetMonthAgain")) { string tempComp = AJAXParameter1.ToLower(); if (tempComp.Equals("evet") && String.IsNullOrEmpty(AJAXParameter1) == false) { chat.usersChat.Add("GetAnsPaymentPlan", AJAXParameter1); //StateOfChat = "FillTable"; StateOfChat = "GetMonth"; TempData["StateOfChat"] = StateOfChat; result = "OK"; } else if (tempComp.Equals("hayır") || tempComp.Equals("hayir") && !String.IsNullOrEmpty(AJAXParameter1)) { chat.usersChat.Add("GetAnsPaymentPlan", AJAXParameter1); chat.botCorrectPath.Add("DeclinedPlan", customer.MUSTERI_ADI + ", borcunuz ay sonu itibariyle " + TotalDebt(customer) + " TL olacaktır. Borcunuza temerrüt faizi her gün işlenmektedir. Banka icra yoluna gidebilir"); StateOfChat = "DeclinedPlan"; TempData["StateOfChat"] = StateOfChat; result = "Done"; } else { StateOfChat = "GetMonthAgain"; TempData["StateOfChat"] = StateOfChat; } } else if (TempData["StateOfChat"].Equals("GetMonth") || TempData["StateOfChat"].Equals("GetInstallmentAgain")) { if (IsAllDigits(AJAXParameter1) && !String.IsNullOrEmpty(AJAXParameter1)) { chat.usersChat.Add("GetMonth", AJAXParameter1); StateOfChat = "GetStartDate"; TempData["StateOfChat"] = StateOfChat; result = "OK"; customer.PLAN.TAKSIT_SAYISI = Int32.Parse(AJAXParameter1); } else { StateOfChat = "GetInstallmentAgain"; TempData["StateOfChat"] = StateOfChat; result = "OK"; } } else if (TempData["StateOfChat"].Equals("GetStartDate") || TempData["StateOfChat"].Equals("GetStartDateAgain") || TempData["StateOfChat"].Equals("GetStartDateAgainFurther")) { DateTime dateData = new DateTime(); if (GetDate(AJAXParameter1, ref dateData) && !String.IsNullOrEmpty(AJAXParameter1)) { if (dateData > DateTime.Today) { chat.usersChat.Add("GetStartDate", AJAXParameter1); StateOfChat = "CalculatePlan"; Session["StateOfChat"] = StateOfChat; result = "PaymentTable"; int month = Int32.Parse(chat.usersChat["GetMonth"]); List <DateTime> dates = new List <DateTime>(); dates = FillDateData(dateData, month); customer.PLAN.BASLANGIC_TARIHI = dates[0]; customer.PLAN.BITIS_TARIHI = dates[dates.Count - 1]; decimal totalDebt = TotalDebt(customer); decimal monthlyPayment = Installment(totalDebt, month, dateData); customer.PLAN.FAIZ_ORANI = GetInterest(month, dateData); customer.PLAN.TAKSIT_TUTARI = Math.Round(monthlyPayment, 2); for (int i = 0; i < dates.Count; i++) { tableInfo.tableData += "<tr>" + "<td>" + dates[i] + " TL</td>" + "<td>" + Math.Round(monthlyPayment, 2) + "</td>" + "</tr>"; } tableInfo.total = Math.Round(CalculatedDebt(totalDebt, dateData), 2); customer.PLAN.PLAN_SONRASI_BAKIYE = tableInfo.total; tableInfo.message = chat.botCorrectPath[StateOfChat]; } else { StateOfChat = "GetStartDateAgainFurther"; Session["StateOfChat"] = StateOfChat; result = "OK"; } } else { StateOfChat = "GetStartDateAgain"; Session["StateOfChat"] = StateOfChat; result = "OK"; } } else if (TempData["StateOfChat"].Equals("CalculatePlan") || TempData["StateOfChat"].Equals("CalculatePlanAgain")) { string tempComp = AJAXParameter1.ToLower(); if (tempComp.Equals("evet") && String.IsNullOrEmpty(AJAXParameter1) == false) { chat.usersChat.Add("CalculatePlanAns", AJAXParameter1); //StateOfChat = "FillTable"; StateOfChat = "CreatePaymentPlan"; TempData["StateOfChat"] = StateOfChat; result = "Done"; customer.PLAN.KREDI_YAPILANDIRILMASI = true; string paymentApplication = conn.AddPaymentPlan(customer); chat.botCorrectPath.Add("CreatePaymentPlan", paymentApplication); } else if (tempComp.Equals("hayır") || tempComp.Equals("hayir") && !String.IsNullOrEmpty(AJAXParameter1)) { chat.usersChat.Add("CalculatePlanAns", AJAXParameter1); chat.botCorrectPath.Add("DeclinedPlan2", customer.MUSTERI_ADI + ", borcunuz ay sonu itibariyle " + TotalDebt(customer) + " TL olacaktır. Borcunuza temerrüt faizi her gün işlenmektedir. Banka icra yoluna gidebilir"); StateOfChat = "DeclinedPlan2"; TempData["StateOfChat"] = StateOfChat; result = "Done"; customer.PLAN.KREDI_YAPILANDIRILMASI = false; } else { StateOfChat = "CalculatePlanAgain"; TempData["StateOfChat"] = StateOfChat; } } //else //{ // //StateOfChat = "NoAction"; // //TempData["StateOfChat"] = StateOfChat; // //chat.botCorrectPath.Add("NoAction", "Sistemden çıkış yapabilirsiniz"); // //Button u disable et //} List <string> data = new List <string>(); data.Add("AJAXParameter1=" + AJAXParameter1); TempData["Chat"] = chat; TempData["CustomerObj"] = customer; TempData["AccountObj"] = customer; TempData["PaymentObj"] = customer; TempData["DatabaseConnection"] = conn; TempData["StateOfChat"] = StateOfChat; string chatVal = chat.botCorrectPath[StateOfChat]; if (result.Equals("Table") || result.Equals("PaymentTable")) { return(Json(new { tableInfo, result })); } return(Json(new { chatVal, result })); }
int GetSortedChatPosition(ChatView chatView) { // starting with > 0.8 the Engine supplies ChatModel.Position for us if (Frontend.EngineVersion > new Version("0.8")) { return(chatView.Position); } // COMPAT: Engine <= 0.8 doesn't populate ChatModel.Position thus // _we_ have to find a good position var chat = chatView.ChatModel; // REMOTING CALL 1 int idx = chat.Position; // REMOTING CALL 2 ChatType type = chat.ChatType; // new group person and group chats behind their protocol chat if (idx == -1 && (type == ChatType.Person || type == ChatType.Group)) { // REMOTING CALL 3 IProtocolManager pm = chat.ProtocolManager; for (int i = 0; i < f_Notebook.NPages; i++) { ChatView page = (ChatView)f_Notebook.GetNthPage(i); ChatModel pageChat = page.ChatModel; // REMOTING CALL 4 and 5 if (pageChat.ChatType == ChatType.Protocol && pageChat.ProtocolManager == pm) { idx = i + 1; break; } } if (idx != -1) { // now find the first chat with a different protocol manager bool found = false; for (int i = idx; i < f_Notebook.NPages; i++) { ChatView page = (ChatView)f_Notebook.GetNthPage(i); ChatModel pageChat = page.ChatModel; // REMOTING CALL 6 if (pageChat.ProtocolManager != pm) { found = true; idx = i; break; } } if (!found) { // if there was no next protocol manager, simply append // the chat way to the end idx = -1; } } } return(idx); }
public async Task <ActionResult> ChatMessages(ChatModel model) { model = model ?? new ChatModel(); var db = new ZkDataContext(); bool isMuted = Punishment.GetActivePunishment(Global.AccountID, Request.UserHostAddress, 0, null, x => x.BanMute) != null; var minTime = DateTime.UtcNow.AddDays(-30); if (!string.IsNullOrEmpty(model.Channel)) { // only show allowed channels if (!Global.Server.ChannelManager.CanJoin(Global.Account, model.Channel)) { return(PartialView("LobbyChatMessages", model)); } if (!String.IsNullOrEmpty(model.Message) && !isMuted) { await Global.Server.GhostSay(new Say() { IsEmote = false, Place = SayPlace.Channel, Ring = false, Source = SaySource.Zk, Target = model.Channel, Text = model.Message, Time = DateTime.UtcNow, User = Global.Account.Name, }); } string channelName = model.Channel; model.Data = db.LobbyChatHistories .SqlQuery("SELECT TOP 30 * FROM [dbo].[LobbyChatHistories] WHERE [Target] = {0} AND [SayPlace] = {1} AND [Time] > {2} ORDER BY [Time] DESC", channelName, SayPlace.Channel, minTime) .ToList().OrderBy(x => x.Time).AsQueryable(); //Note if using Take(), it will be slow for uncommon channels like zktourney when ordering by Time and slow for common channels like zk if ordering by ID } else if (!string.IsNullOrEmpty(model.User)) { if (!String.IsNullOrEmpty(model.Message) && !isMuted) { await Global.Server.GhostSay(new Say() { IsEmote = false, Place = SayPlace.User, Ring = false, Source = SaySource.Zk, Target = model.User, Text = model.Message, Time = DateTime.UtcNow, User = Global.Account.Name, }); } string otherName = model.User; string myName = Global.Account.Name; //Users can abuse rename to gain access to other users PMs, it's a feature model.Data = db.LobbyChatHistories .Where(x => (x.User == otherName && x.Target == myName || x.User == myName && x.Target == otherName) && x.SayPlace == SayPlace.User && x.Time > minTime) .OrderByDescending(x => x.Time).Take(30) .ToList().OrderBy(x => x.Time).AsQueryable(); } else { string myName = Global.Account.Name; var ignoredIds = db.AccountRelations.Where(x => (x.Relation == Relation.Ignore) && (x.OwnerAccountID == Global.AccountID)).Select(x => x.TargetAccountID).ToList(); var ignoredNames = db.Accounts.Where(x => ignoredIds.Contains(x.AccountID)).Select(x => x.Name).ToHashSet(); model.Data = db.LobbyChatHistories .Where(x => x.Target == myName && x.SayPlace == SayPlace.User && x.Time > minTime) .OrderByDescending(x => x.Time).Take(30) .ToList() .Where(x => !ignoredNames.Contains(x.User)) .OrderBy(x => x.Time) .AsQueryable(); } model.Message = ""; return(PartialView("LobbyChatMessages", model)); }
public void AddNewItem(ChatModel model) { model.Name = Context.User?.Identity.Name; _list.Add(model); Clients.All.ReceiveMessage(model); }
public ActionResult Chat(ChatModel model) { model = model ?? new ChatModel(); return(View("LobbyChat", model)); }
/// <summary> /// When the method is called with no arguments, just return the view /// When argument logOn is true, a user logged on /// When argument logOff is true, a user closed their browser or navigated away (log off) /// When argument chatMessage is specified, the user typed something in the chat /// </summary> public ActionResult Index(string user, bool?logOn, bool?logOff, string chatMessage) { try { if (chatModel == null) { chatModel = new ChatModel(); } //trim chat history if needed if (chatModel.ChatHistory.Count > 100) { chatModel.ChatHistory.RemoveRange(0, 90); } if (!Request.IsAjaxRequest()) { //first time loading return(View(chatModel)); } else if (logOn != null && (bool)logOn) { //check if nickname already exists if (chatModel.Users.FirstOrDefault(u => u.NickName == user) != null) { throw new Exception("This nickname already exists"); } else if (chatModel.Users.Count > 10) { throw new Exception("The room is full!"); } else { #region create new user and add to lobby chatModel.Users.Add(new ChatModel.ChatUser() { NickName = user, LoggedOnTime = DateTime.Now, LastPing = DateTime.Now }); //inform lobby of new user chatModel.ChatHistory.Add(new ChatModel.ChatMessage() { Message = "User '" + user + "' logged on.", When = DateTime.Now }); #endregion } return(PartialView("Lobby", chatModel)); } else if (logOff != null && (bool)logOff) { LogOffUser(chatModel.Users.FirstOrDefault(u => u.NickName == user)); return(PartialView("Lobby", chatModel)); } else { ChatModel.ChatUser currentUser = chatModel.Users.FirstOrDefault(u => u.NickName == user); //remember each user's last ping time currentUser.LastPing = DateTime.Now; #region remove inactive users List <ChatModel.ChatUser> removeThese = new List <ChatModel.ChatUser>(); foreach (Models.ChatModel.ChatUser usr in chatModel.Users) { TimeSpan span = DateTime.Now - usr.LastPing; if (span.TotalSeconds > 15) { removeThese.Add(usr); } } foreach (ChatModel.ChatUser usr in removeThese) { LogOffUser(usr); } #endregion #region if there is a new message, append it to the chat if (!string.IsNullOrEmpty(chatMessage)) { chatModel.ChatHistory.Add(new ChatModel.ChatMessage() { ByUser = currentUser, Message = chatMessage, When = DateTime.Now }); } #endregion return(PartialView("ChatHistory", chatModel)); } } catch (Exception ex) { //return error to AJAX function Response.StatusCode = 500; return(Content(ex.Message)); } }
protected virtual void OnPropertyChanged(ChatModel chatItem) { var handler = PropertyChanged; handler?.Invoke(this, new ChatEventArgs(chatItem)); }
protected virtual void OnSwitchPage(object sender, Gtk.SwitchPageArgs e) { Trace.Call(sender, e); if (f_IsBrowseModeEnabled) { return; } // synchronize FrontManager.CurrenPage ChatView chatView = GetChat((int)e.PageNum); if (chatView == null) { return; } ChatModel chatModel = chatView.ChatModel; // clear activity and highlight chatView.HasHighlight = false; chatView.HasActivity = false; chatView.HasEvent = false; var lastMsg = chatView.OutputMessageTextView.LastMessage; var method = Trace.GetMethodBase(); f_SwitchPageQueue.Queue(delegate { // HACK: don't pass the real parameters are it's unsafe from // a non-main (GUI) thread! Trace.Call(method, null, null); try { DateTime start = DateTime.UtcNow, stop; var fm = Frontend.FrontendManager; if (fm == null) { // in case we are currently reconnecting to a remote engine return; } // OPT-TODO: we could use here a TaskStack instead which // would make sure only the newest task gets executed // instead of every task in the FIFO sequence! var nmanager = chatView.ProtocolManager; // TODO: only set the protocol manager and update network // status if the protocol manager differs from the old one // REMOTING CALL 2 fm.CurrentChat = chatModel; if (nmanager != null) { // REMOTING CALL 3 fm.CurrentProtocolManager = nmanager; } // even when we have no network manager, we still want to update // the network status and title // REMOTING CALL 4 fm.UpdateNetworkStatus(); // update last seen highlight // REMOTING CALL 5 if (lastMsg != null && !Frontend.UseLowBandwidthMode) { chatModel.LastSeenHighlight = lastMsg.TimeStamp; } stop = DateTime.UtcNow; #if LOG4NET f_Logger.Debug("OnSwitchPage(): task took: " + (stop - start).Milliseconds + " ms"); #endif } catch (Exception ex) { #if LOG4NET f_Logger.Error("OnSwitchPage(): Exception", ex); #endif Frontend.ShowException(ex); } }); }
public ActionResult Index(string user, bool? logOn, bool? logOff, string chatMessage, string sortBy) { try { if (chatModel == null) chatModel = new ChatModel(); //оставляем только последние 90 сообщений if (chatModel.Messages.Count > 100) chatModel.Messages.RemoveRange(0, 90); // если обычный запрос, просто возвращаем представление if (!Request.IsAjaxRequest()) { return View(chatModel); } else if (logOn != null && (bool)logOn) { //проверяем, существует ли уже такой пользователь if (chatModel.Users.FirstOrDefault(u => u.Name == user) != null) { throw new Exception("Пользователь с таким ником уже существует"); } else if (chatModel.Users.Count > 10) { throw new Exception("Чат заполнен"); } else { chatModel.Count++; // добавляем в список нового пользователя chatModel.Users.Add(new ChatUser() { ID = chatModel.Count, Name = user, LoginTime = DateTime.Now, LastPing = DateTime.Now }); } return PartialView("ChatRoom", chatModel); } else if (logOff != null && (bool)logOff) { LogOff(chatModel.Users.FirstOrDefault(u => u.Name == user)); return PartialView("ChatRoom", chatModel); } else { ChatUser currentUser = chatModel.Users.FirstOrDefault(u => u.Name == user); //для каждого пользователя запоминаем воемя последнего обновления currentUser.LastPing = DateTime.Now; // удаляем неаквтивных пользователей List<ChatUser> removeThese = new List<ChatUser>(); foreach (Models.ChatUser usr in chatModel.Users) { TimeSpan span = DateTime.Now - usr.LastPing; if (span.TotalSeconds > 15) removeThese.Add(usr); } foreach (ChatUser u in removeThese) { LogOff(u); } // добавляем в список сообщений новое сообщение if (!string.IsNullOrEmpty(chatMessage)) { chatModel.Messages.Add(new ChatMessage() { User = currentUser, Text = chatMessage, Time = DateTime.Now }); } if (sortBy == "ID") chatModel.SortMessagesByID(); return PartialView("History", chatModel); } } catch (Exception ex) { //в случае ошибки посылаем статусный код 500 Response.StatusCode = 500; return Content(ex.Message); } }