public async Task <IHttpActionResult> CreateChatMessage(int chatId, [FromBody] ChatRequestData data) { DataHelper dataHelper = new DataHelper(); object userId; Request.Properties.TryGetValue("user_id", out userId); int uid = Convert.ToInt32(userId); if (string.IsNullOrEmpty(data.Message)) { return(BadRequest()); } try { ChatMessage chatMessage = await dataHelper.CreateChatMessage(uid, chatId, data.Message); UserChat userChat = await dataHelper.CreateUserChat(uid, chatId); User user = await dataHelper.FindUserById(uid); return(Ok(new { data = DataHelper.BuildChatMessageResponseData(chatMessage, user), meta = new { } })); } catch (Exception e) { // log return(InternalServerError()); } }
public async Task <object> saveUserChat(vmMessage _model) { string message = string.Empty; try { using (_ctx = new SignalRChatContext()) { UserChat model = new UserChat() { Chatid = _ctx.UserChat.DefaultIfEmpty().Max(x => x == null ? 0 : x.Chatid) + 1, Connectionid = _model.Connectionid, Senderid = _model.Senderid, Receiverid = _model.Receiverid, Message = _model.Message, Messagestatus = _model.Messagestatus, Messagedate = _model.Messagedate, IsGroup = _model.IsGroup, IsPrivate = _model.IsPrivate, IsMultiple = _model.IsMultiple }; _ctx.UserChat.Add(model); await _ctx.SaveChangesAsync(); message = "Saved"; } } catch (Exception ex) { message = "Error:" + ex.ToString(); } return(message); }
public async Task <IActionResult> Edit(Guid id, [Bind("UserId,ChatId,Id")] UserChat userChat) { if (id != userChat.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(userChat); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserChatExists(userChat.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["ChatId"] = new SelectList(_context.Chat, "ChatId", "ChatId", userChat.ChatId); ViewData["UserId"] = new SelectList(_context.Profile, "UserId", "UserId", userChat.UserId); return(View(userChat)); }
public async Task <IActionResult> PutUserChat(Guid id, UserChat userChat) { if (id != userChat.Id) { return(BadRequest()); } _context.Entry(userChat).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserChatExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <long> SendMessage(vmMessage message) { long chatId = 0; //Receive Message List <string> ReceiverConnectionids = _connections.GetConnections(message.Receiverid).ToList <string>(); if (ReceiverConnectionids.Count() > 0) { //Save-Receive-Message try { UserChat model = new UserChat() { Senderid = message.Senderid, Receiverid = message.Receiverid, Message = message.Message, Messagedate = message.Messagedate }; UserChat userChat = await _chatDBService.SaveItemAsync(model); chatId = userChat.Chatid; await Clients.Clients(ReceiverConnectionids).SendAsync("ReceiveMessage", message); } catch (Exception) { } } return(chatId); }
public object DeleteUserFromChat(int chatId, int userId, int owenerId, string token) { var context = ConnectionService.GetContext(); var delUserChat = context.Tokens.Where(duc => duc.UserId == userId).FirstOrDefault(); UserChat userChat = context.UserChats.Where(du => du.ChatId == chatId && du.UserId == userId).FirstOrDefault(); if (userChat != null && delUserChat != null) { if (userId == owenerId && delUserChat.UserId == userId && delUserChat.TokenId == token) { context.UserChats.Remove(userChat); context.SaveChanges(); return(true); } else { var chat = context.Chats.Where(o => o.Id == chatId).FirstOrDefault(); if (chat.UserId == owenerId) { context.UserChats.Remove(userChat); context.SaveChanges(); return(new { error = false, chatId = chat.Id, userId = userId, user = owenerId }); } } } return(new { error = true, messageError = "Указанный Вами токен не подходит" }); }
public async Task SendMessage(UserChatDto message) { //var httpContext = Context.GetHttpContext(); //var services = httpContext.RequestServices; //var chatDalLayerInstance = (IChatDalLayer)services.GetService(typeof(IChatDalLayer)); //_chatManager = new ChatManager(chatDalLayerInstance); //Receive Message List <string> ReceiverConnectionids = _connections.GetConnections(message.Receiverid).ToList <string>(); if (ReceiverConnectionids.Count() > 0) { //Save-Receive-Message try { message.Connectionid = string.Join(",", ReceiverConnectionids); var userChatEntity = new UserChat(); userChatEntity.Connectionid = message.Connectionid; userChatEntity.Message = message.Message; userChatEntity.Messagedate = message.Messagedate; userChatEntity.Messagestatus = message.Messagestatus; userChatEntity.Receiverid = message.Receiverid; userChatEntity.Senderid = message.Senderid; userChatEntity.IsPrivate = true; await _chatManager.SaveUserChat(userChatEntity); await Clients.Clients(ReceiverConnectionids).SendAsync("ReceiveMessage", message); } catch (Exception) { } } }
public object DelitingFromChat(int chatId, int userId, string token) { var context = ConnectionService.GetContext(); var Tkn = context.Tokens.Where(t => t.UserId == userId).FirstOrDefault(); if (Tkn == null || Tkn.TokenId == token) { return(new { error = true, message = "неверный токен" }); } var findChat = context.Chats.Where(fch => fch.Id == chatId).FirstOrDefault(); if (findChat != null) { var findUser = context.UserChats.Where(fu => fu.UserId == userId && fu.ChatId == chatId).FirstOrDefault(); if (findUser != null) { UserChat userChat = new UserChat(); userChat.ChatId = chatId; userChat.UserId = userId; context.UserChats.Remove(userChat); context.SaveChanges(); } return(new { error = false, chat = chatId, user = userId }); } return(new { error = true, message = "ошибка удаления" }); }
public DirectChat AddDirectChat(string userId, string interlocutorId) { if (GetDirectChatByUserIds(userId, interlocutorId) == null) { var chatToAdd = new DirectChat(); var userChatForUser = new UserChat { UserId = userId, Chat = chatToAdd, }; var userChatForInterlocutor = new UserChat { UserId = interlocutorId, Chat = chatToAdd, }; context.AddRange(chatToAdd, userChatForUser, userChatForInterlocutor); context.SaveChanges(); return(chatToAdd); } else { return(null); } }
)> GetCachedContextsAsync(IUpdateContext context, UserChat userchat, CancellationToken cancellationToken) { var userProfile = (UserProfile)context.Items[nameof(UserProfile)]; BusPredictionsContext busCacheContext; if (context.Items.TryGetValue(nameof(BusPredictionsContext), out var busCacheContextObj)) { busCacheContext = (BusPredictionsContext)busCacheContextObj; } else { busCacheContext = await _cache.GetBusPredictionAsync(userchat, cancellationToken) .ConfigureAwait(false); } UserLocationContext locationContext; if (context.Items.TryGetValue(nameof(UserLocationContext), out var locationContextObj)) { locationContext = (UserLocationContext)locationContextObj; } else { locationContext = await _cache.GetLocationAsync(userchat, cancellationToken) .ConfigureAwait(false); } return(userProfile, busCacheContext, locationContext); }
public async Task <AddParticipantPayload> GetAddParticipantAsync( AddParticipantInput input, [ScopedService] ApplicationDbContext dbContext, [Service] IHttpContextAccessor contextAccessor, UserByIdDataLoader userById, ChatByIdDataLoader chatById, CancellationToken ct ) { var user = await userById.LoadAsync(input.UserId, ct) ?? throw new Exception("User not found."); var chat = await chatById.LoadAsync(input.ChatId, ct) ?? throw new Exception("Chat not found."); // Todo: Check if user is allowed to add participants --> add something like a groupadmin var userChat = new UserChat { UserId = user.Id, ChatId = chat.Id }; chat.UserChats.Add(userChat); await dbContext.SaveChangesAsync(); return(new AddParticipantPayload(chat)); }
private static void SeedChatRoom(ApplicationDbContext dbContext) { if (!dbContext.Chats.Any()) { var usersId = dbContext.Users.Select(u => u.Id).ToList(); var userChats = new List <UserChat>(); foreach (var userId in usersId) { var userChat = new UserChat { ApplicationUserId = userId, CreatedOn = DateTime.UtcNow, }; userChats.Add(userChat); } var globalChatRoom = new Chat { Name = GlobalConstants.GlobalChatRoomName, CreatedOn = DateTime.UtcNow, UserChats = userChats }; dbContext.Chats.Add(globalChatRoom); dbContext.SaveChanges(); } }
public async Task <IHttpActionResult> PostUserChat(UserChat userChat) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.UserChats.Add(userChat); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (UserChatExists(userChat.id)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = userChat.id }, userChat)); }
void SlimeParty2() { if (SP2Started == false && gm.isInterRound == false) { UserChat.CreateChat("아니 이게 무슨..!", 2); UserChat.CreateChat("메이플 하고싶다", 3); UserChat.CreateChat(UserChat.BadChat("내 다람쥐 어디갔어!!"), 2); SP2Started = true; } if (gm.timeLeft <= 1) { // 다람쥐와 슬라임을 스왑함 GameObject temp = GameObject.Find("AddBasicDaram").GetComponent <AddBasicDaram>().daram; GameObject.Find("AddBasicDaram").GetComponent <AddBasicDaram>().daram = SlimeParty_Slime; SlimeParty_Slime = temp; SlimeParty_Slime.GetComponent <Daram>().Type = "Slime"; gm.EventCheck -= SlimeParty2; Instantiate(SlimeParty_Box2); Unlockables.SetBool("UnlockSlime1", true); Unlockables.SetBool("UnlockSlime1_Amount10", true); Unlockables.SetBool("UnlockMush2", true); Unlockables.SetBool("UnlockMush2_Amount10", true); } }
public async Task <object> userChat([FromQuery] string param) { object result = null; object resdata = null; try { if (param != string.Empty) { dynamic data = JsonConvert.DeserializeObject(param); UserChat model = JsonConvert.DeserializeObject <UserChat>(data.ToString()); if (model != null) { resdata = await _objChat.getUserChat(model); } } } catch (Exception ex) { ex.ToString(); } result = new { resdata }; return(result); }
public async Task <IHttpActionResult> PutUserChat(Guid id, UserChat userChat) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != userChat.id) { return(BadRequest()); } db.Entry(userChat).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserChatExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public static Message AddUserMessage(string userId, int chatId, MessageBindingModel model) { Chat chat = context.Chats.FirstOrDefault(c => c.ChatId == chatId); if (chat == null) { throw new NullReferenceException(); } UserChat uchat = context.UserChats.FirstOrDefault(u => u.UserId.Equals(userId) && u.ChatId.Equals(chatId)); if (!uchat.UserId.Equals(userId)) { throw new UnauthorizedAccessException(); } var message = new Message { ChatId = chatId, SentDate = DateTime.Now, Text = model.Text, UserId = userId }; context.Messages.Add(message); context.SaveChanges(); return(message); }
public static List <MessageViewModel> GetUserChatMessages(string userId, int chatId) { Chat chat = context.Chats.FirstOrDefault(c => c.ChatId == chatId); if (chat == null) { throw new NullReferenceException(); } UserChat uchat = context.UserChats.FirstOrDefault(u => u.UserId.Equals(userId) && u.ChatId.Equals(chatId)); if (!uchat.UserId.Equals(userId)) { throw new UnauthorizedAccessException(); } return(context.Messages.Where(m => m.ChatId == chat.ChatId).Select(m => new MessageViewModel { MessageId = m.MessageId, SentDate = m.SentDate, Text = m.Text, UserName = context.Users.FirstOrDefault(u => u.Id.Equals(m.UserId)).UserName }).ToList()); }
public Message AddMessage(MessageViewModel message) { UserChat existingUserChat = context.UserChats .Where(uc => uc.UserId == message.Author.Id) .Where(uc => uc.ChatId == message.ChatId) .SingleOrDefault(); if (existingUserChat != null) { var messageToAdd = new Message { Author = message.Author, PublicationTime = DateTime.UtcNow, Body = message.Body, ChatId = message.ChatId, }; context.Chats.Find(message.ChatId).LastMessage = messageToAdd; context.Messages.Add(messageToAdd); context.SaveChanges(); return(messageToAdd); } else { return(null); } }
public object AddToExistChat(int chatId, int userId, string token) { var context = ConnectionService.GetContext(); var findUserInTokens = context.Tokens.Where(t => t.UserId == userId).FirstOrDefault(); if (findUserInTokens == null || findUserInTokens.TokenId != token) { return(new { error = true, message = "неверный токен" }); } var findChat = context.Chats.Where(fch => fch.Id == chatId).FirstOrDefault(); if (findChat != null) { var findUser = context.UserChats.Where(fu => fu.UserId == userId && fu.ChatId == chatId).FirstOrDefault(); var banList = context.Bans.Where(ban => ban.UserId == userId && ban.ChatId == chatId).FirstOrDefault(); if (findUser == null && findUser.ChatId != banList.ChatId && findUser.UserId != banList.UserId) { UserChat userChat = new UserChat(); userChat.UserId = userId; userChat.ChatId = chatId; context.UserChats.Add(userChat); context.SaveChanges(); } else { return(new { error = true, message = "Доступ закрыт" }); } return(new { error = false, chat = chatId, user = userId }); } return(new { error = true, message = "ошибка добавления" }); }
private void UserChatMenuItem_Click(object sender, EventArgs e) { var Form = new UserChat(); Form.Show(this); Form.Activate(); }
public async Task <bool> DeleteChatFor(long chatId, long deleteFor) { bool success = false; try { using (dbContext = new SignalRChatContext()) { UserChat userChat = await(from x in dbContext.UserChat where x.Chatid == chatId select x).FirstOrDefaultAsync(); if (userChat != null && (userChat.Deletedfor > 0 || deleteFor < 0)) { dbContext.Remove(userChat); } else { userChat.Deletedfor = deleteFor; dbContext.Update(userChat); } await dbContext.SaveChangesAsync(); success = true; } } catch (Exception ex) { ex.ToString(); } return(success); }
public async Task <CacheUserContext2> GetCachedContextAsync(UserChat userchat) { CacheUserContext2 cacheContext2 = this[userchat]; cacheContext2 = cacheContext2 ?? new CacheUserContext2(); if (cacheContext2.AgencyTag == null) { var result = await _dbContext.UserChatContexts .Where(uc => uc.ChatId == userchat.ChatId && uc.UserId == userchat.UserId) .Select(uc => new { uc.AgencyId, uc.Agency.Tag, }) .SingleAsync(); cacheContext2.AgencyTag = result.Tag; cacheContext2.AgencyId = result.AgencyId; this[userchat] = cacheContext2; } return(cacheContext2); }
private void GenerateUserChats() { foreach (var user in this.UserData) { var chats = this.ChatData.Where(c => c.ChatLines.Any(cl => cl.ApplicationUserId == user.Id)); var userChats = new List <UserChat>(); foreach (var chat in chats) { var userChat = new UserChat() { Id = Guid.NewGuid().ToString(), ApplicationUser = user, ApplicationUserId = user.Id, Chat = chat, ChatId = chat.Id, CreatedOn = GetRandomDate() }; userChats.Add(userChat); } user.UserChats = userChats; } }
public async Task <Chat> CreateChatFor(Guid senderId, Guid reciverId) { Chat chat = new Chat() { Id = Guid.NewGuid(), CreationDateTime = DateTime.Now, }; UserChat sender = new UserChat() { UserId = senderId, ChatId = chat.Id, Id = Guid.NewGuid(), User = dbContext.Users.Find(senderId) }; UserChat reciver = new UserChat() { UserId = reciverId, ChatId = chat.Id, Id = Guid.NewGuid(), User = dbContext.Users.Find(reciverId) }; chat.UserChats = new Collection <UserChat> { sender, reciver }; chat.Messeges = new Collection <Messege>().ToList(); await base.Create(chat ); return(chat); }
public async Task <ChatDto> CreateGroupAsync(NewChatModel newChat) { var chat = new Chat { Name = newChat.Name, Type = ChatType.Group }; await _unitOfWork.Chats.CreateAsync(chat); var principal = _contextAccessor.HttpContext.User; var ownerUser = await _userManager.GetUserAsync(principal); var ownerParticipant = new UserChat() { ChatId = chat.Id, UserId = ownerUser.Id, IsAdmin = true }; chat.Participants.Add(ownerParticipant); ownerUser.Chats.Add(ownerParticipant); foreach (var participantId in newChat.ParticipantIds) { var validator = new ValidateGuidAttribute(); if (!validator.IsValid(participantId)) { throw new ItemNotFoundException("Specified Id is not a valid GUID"); } var user = await _userManager.FindByIdAsync(participantId); if (user == null) { throw new ItemNotFoundException("User with specified Id was not found"); } var chatParticipant = new UserChat() { ChatId = chat.Id, UserId = new Guid(participantId), }; chat.Participants.Add(chatParticipant); user.Chats.Add(chatParticipant); } try { await _unitOfWork.SaveChangesAsync(); } catch (InvalidOperationException ex) when(ex.Message.Contains("already being tracked")) { throw new DuplicateChatParticipantException("Participant is already in this chat"); } return(chat.ToDto()); }
public async Task <UserChat> Add(UserChat entity) { var result = await context.AddAsync(entity); await context.SaveChangesAsync(); return(result.Entity); }
/// <summary> /// Remove User to Chat link from DB /// </summary> /// <param name="chatId"></param> /// <param name="username"></param> public void DeleteUserChat(long chatId, string username) { UserChat userchat = _context.UserChats .Where(d => d.ChatId == chatId && d.UserName == username) .First(); _context.UserChats.Remove(userchat); _context.SaveChanges(); }
public static async Task AddUserChatAsync(long id, long idChat, string chatPosition) { using (HotelTelegramBotContext db = new HotelTelegramBotContext()) { UserChat user = new UserChat(0, idChat, chatPosition); db.UserChats.Add(user); await db.SaveChangesAsync(); } }
void Start() { uc = this; gm = GameManager.gm; _ChatText = ChatText; gm.UserChat += NoDaram; gm.UserChat += DaramNumber; gm.UserChat += UserCount; }