Exemple #1
0
        public async Task <bool> CreateChat(string chatName)
        {
            try
            {
                if (App.MobileClient.CurrentUser != null &&
                    !string.IsNullOrEmpty(App.MobileClient.CurrentUser.MobileServiceAuthenticationToken))
                {
                    var model = new UserChatModel()
                    {
                        ChatName = chatName,
                        Email    = App.MobileClient.CurrentUser.UserId
                    };

                    var response = await this.client.PostAsync(AppValues.BaseServerUrl + "/api/chat/create",
                                                               new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));

                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(false);
        }
        public ActionResult HelpDeskLogin(HelpDeskUserModel paramHelpDeskInfo)
        {
            UserChatModel userInfo = new Models.UserChatModel();

            try
            {
                if (ModelState.IsValid)
                {
                    userInfo = new UserChatModel()
                    {
                        _GroupNameChat = paramHelpDeskInfo._GroupNameChat,
                        _UserFullName  = paramHelpDeskInfo._FullName,
                        _UserType      = UserChatModel.RegisteredUserType.helpDeskUser,
                        _UserEmail     = paramHelpDeskInfo._UserEmail
                    };

                    return(RedirectToAction("ChatRoom", userInfo));
                }
                else
                {
                    return(View());
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = String.Format("Se ha presentado un problema al tratar de iniciar sesión. \n {0}", ex.Message);
                return(View());
            }
        }
        public async Task <ActionResult> Index(UserChatModel paramUserInfo)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    paramUserInfo._UserType      = UserChatModel.RegisteredUserType.regularUser;
                    paramUserInfo._GroupNameChat = Guid.NewGuid().ToString();

                    EmailModel emailService = new EmailModel();

                    //creates custom URL to access HelpDesk Login for users in service desk
                    string    urlWebDomain     = ConfigurationManager.AppSettings["WebDomain"];
                    UrlHelper uhelper          = new UrlHelper(ControllerContext.RequestContext);
                    string    urlHelpDeskLogin = urlWebDomain + uhelper.Action("HelpDeskLogin", "Chat", new { groupName = paramUserInfo._GroupNameChat });

                    //sends the email to helpdesk group
                    await emailService.CreatesUserStartSessionNotificationEmail(paramUserInfo, urlHelpDeskLogin);

                    return(RedirectToAction("ChatRoom", paramUserInfo));
                }
                else
                {
                    return(View());
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = String.Format("Se ha presentado un problema al tratar de ingresar al chat. \n {0}", ex.Message);
                return(View());
            }
        }
Exemple #4
0
        public JsonResult CheckLogin(FormCollection collection)
        {
            string userName = collection["userName"];
            string password = collection["password"];

            var user = new UserChatModel();

            using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
            {
                JsonResult jr = new JsonResult();

                try
                {
                    string query = "select * from UserChats Where UserName = '******'";
                    user = db.Query <UserChatModel>(query).SingleOrDefault();
                }
                catch {
                    jr.Data = new
                    {
                        status = "F"
                    };
                }

                if (user == null)
                {
                    jr.Data = new
                    {
                        status = "F"
                    };
                }
                else
                {
                    if (user.MatKhau == password)
                    {
                        Session["userName"]      = user.UserName;
                        Session["currentUserId"] = user.UserId;
                        Session.Timeout          = 5;
                        jr.Data = new
                        {
                            status = "OK",
                            userId = user.UserId,
                        };
                    }
                    else
                    {
                        jr.Data = new
                        {
                            status = "F"
                        };
                    }
                }

                return(Json(jr, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #5
0
        public IHttpActionResult CreateChat([FromBody] UserChatModel model)
        {
            var user = this.context.Users.FirstOrDefault(x => x.Email == model.Email);
            var chat = new Chat()
            {
                Name = model.ChatName
            };

            this.context.Chats.Add(chat);
            user.Chats.Add(chat);
            this.context.SaveChanges();
            return(this.Ok());
        }
Exemple #6
0
        public async Task <IActionResult> Chat()
        {
            User thisUser = await userManager.GetUserAsync(HttpContext.User);

            List <Message> allUsersMessages = (List <Message>)dataRepository.GetAllMessagesOfUser(thisUser);

            User lastCommUser = null;
            int  unreadLatest = 0;

            if (!(allUsersMessages is null) && allUsersMessages.Count > 0)
            {
                if (allUsersMessages.LastOrDefault().Receiver.Id == thisUser.Id)
                {
                    lastCommUser = allUsersMessages.LastOrDefault().Sender;
                }
                else
                {
                    lastCommUser = allUsersMessages.LastOrDefault().Receiver;
                }
                unreadLatest = allUsersMessages.Where(m => m.Sender.Id == lastCommUser.Id && m.isUnread).ToList().Count;
            }
            List <UserChatModel> Correspondance = new List <UserChatModel>();

            List <User> ThisUsersFriends = dataRepository.GetUsersFriends(thisUser).ToList();

            foreach (User friend in ThisUsersFriends)
            {
                List <Message> friendsExchanged = allUsersMessages.Where(m => m.Receiver.Id == friend.Id || m.Sender.Id == friend.Id).ToList();

                UserChatModel userChat = new UserChatModel
                {
                    Correspondant          = friend,
                    CorrespondantsMessages = friendsExchanged,
                    UnreadReceived         = friendsExchanged.Where(m => m.Sender.Id == friend.Id && m.isUnread).ToList().Count
                };
                Correspondance.Add(userChat);
            }

            MessengerViewModel messengerView = new MessengerViewModel
            {
                ThisUser           = thisUser,
                LatestCommunicator = lastCommUser,
                UnreadLatest       = unreadLatest,
                FriendsAndMessages = Correspondance
            };

            logger.LogInformation("User " + thisUser.UserName + " navigated to Chat Page");
            return(View(messengerView));
        }
        public void Connect(UserChatModel userInfo)
        {
            var id = Context.ConnectionId;

            StringBuilder welcomeMsg = new StringBuilder();
            string        newUserMsg = null;
            string        count      = "NA";

            userInfo._UserId = id;

            Groups.Add(id, userInfo._GroupNameChat); //agrega el usuario a un grupo privado de chat

            if (userInfo._UserType == UserChatModel.RegisteredUserType.regularUser)
            {
                welcomeMsg.AppendLine("Bienvenido a la plataforma de servicio al cliente del BCCR");
                welcomeMsg.AppendLine("En un momento será atendido por uno de nuestros representantes ...");

                newUserMsg = "El usuario " + userInfo._UserFullName + " se ha unido al chat.";

                StringBuilder userDetails = new StringBuilder();
                userDetails.AppendLine("Información del usuario conectado al chat");
                userDetails.AppendLine(String.Format("Nombre: {0}", userInfo._UserFullName));
                userDetails.AppendLine(String.Format("Correo Electrónico: {0}", userInfo._UserEmail));
                userDetails.AppendLine(String.Format("No. Teléfono: {0}", userInfo._UserPhone));
                userDetails.AppendLine(String.Format("Pregunta: {0}", userInfo._UserQuestion));

                AddSystemMessageinCache(userInfo._GroupNameChat, userDetails.ToString()); //almacena en el cache del chat, la informacion del cliente conectado

                Clients.Caller.receiveMessage("", welcomeMsg.ToString(), "");
            }
            else
            {
                newUserMsg = "Está hablando con " + userInfo._UserFullName + ".";

                //MessagesChatModel SendMessages = SendMessagesList.FirstOrDefault(x => x._ChatGroupName == userInfo._GroupNameChat);

                StringBuilder userChatDetails = new StringBuilder();

                //foreach (var item in SendMessagesList.FirstOrDefault(x => x._ChatGroupName == userInfo._GroupNameChat)._ChatConversation)
                //{
                userChatDetails.AppendLine(SendMessagesList.FirstOrDefault(x => x._ChatGroupName == userInfo._GroupNameChat)._ChatConversation[0]);
                //}

                Clients.Caller.receiveMessage("", userChatDetails.ToString(), "");
            }

            Clients.OthersInGroup(userInfo._GroupNameChat).receiveMessage("", newUserMsg, count);
        }
Exemple #8
0
        public IHttpActionResult GetMessages([FromUri] UserChatModel model)
        {
            var messages = this.context.Messages
                           .Include(x => x.Chat)
                           .Include(x => x.Sender)
                           .Where(x => x.Chat.Name == model.ChatName)
                           .ToList();
            var result = messages.Select(x => new MessageInfo()
            {
                Text        = x.Text,
                ChatName    = x.Chat.Name,
                SenderEmail = x.Sender.Email
            }).ToList();

            return(this.Json(result));
        }
Exemple #9
0
        public async Task <IActionResult> Chat([FromBody] string UserID)
        {
            User correspondant = await userManager.FindByIdAsync(UserID);

            User thisUser = await userManager.GetUserAsync(HttpContext.User);

            List <Message> allUsersMessages = dataRepository.GetAllMessagesOfUsers(thisUser, correspondant).ToList();

            UserChatModel messengerView = new UserChatModel
            {
                CorrespondantsMessages = allUsersMessages
            };

            logger.LogInformation("User " + thisUser.UserName
                                  + " navigated to Chat Page with default correspondant "
                                  + correspondant.UserName);
            return(Json(messengerView));
        }
 public ActionResult ChatRoom(UserChatModel paramUserInfo)
 {
     if (paramUserInfo != null)
     {
         if ((paramUserInfo._UserFullName != null) && (paramUserInfo._GroupNameChat != null))
         {
             return(View(paramUserInfo));
         }
         else
         {
             return(RedirectToAction("Index"));
         }
     }
     else
     {
         return(RedirectToAction("Index"));
     }
 }
        public JsonResult CreateAccount(FormCollection collection)
        {
            JsonResult jr = new JsonResult();

            try
            {
                var userInfo = new UserChatModel
                {
                    UserName = collection["userName"],
                    MatKhau  = collection["passWord"],
                    FullName = collection["fullName"],
                    Birthday = DateTime.Parse(collection["birthday"]),
                    Email    = collection["email"],
                    Phone    = collection["phone"],
                };

                var query_selectMaxUserId = "select Max(UserId) maxUserId from UserChats";
                var newUserId             = db.Query(query_selectMaxUserId).FirstOrDefault().maxUserId + 1;

                //var userId =  tmpUserId.maxUserId ;

                string query_insertUser = "******";

                db.Execute(query_insertUser, new { UserId = newUserId, FullName = userInfo.FullName, Birthday = userInfo.Birthday, Phone = userInfo.Phone, Email = userInfo.Email, UserName = userInfo.UserName, MatKhau = userInfo.MatKhau });

                jr.Data = new
                {
                    status = "Success"
                };
            }
            catch
            {
                jr.Data = new
                {
                    status = "F"
                };
            }



            return(Json(jr, JsonRequestBehavior.AllowGet));
        }
        public HttpResponseMessage GetChatList([FromBody] ChatModel ChatModel)
        {
            var userList = new UserChatModel();
            var models   = new List <ChatsModel>();

            try
            {
                int          count           = 0;
                List <Guid?> ListCustomerIDs = new List <Guid?>();
                ListCustomerIDs.Add(ChatModel.CustomerIdBy);
                ListCustomerIDs.Add(ChatModel.CustomerIdTo);

                var Chats = _ChatService.GetAll().Where(x => ListCustomerIDs.Contains(x.CustomerIdBy) && ListCustomerIDs.Contains(x.CustomerIdTo)).ToList();

                var Results = (from m in Chats where m.CustomerIdBy == ChatModel.CustomerIdBy && m.CustomerIdTo == ChatModel.CustomerIdTo select m)
                              .Concat(from m in Chats where m.CustomerIdBy == ChatModel.CustomerIdTo && m.CustomerIdTo == ChatModel.CustomerIdBy select m)
                              .OrderBy(x => x.DateTimeCreated);


                Mapper.CreateMap <HomeHelp.Entity.Chat, HomeHelp.Models.ChatsModel>().ForMember(c => c.CustomersBy, option => option.Ignore()).ForMember(c => c.CustomersTo, option => option.Ignore());
                foreach (var Chat in Results)
                {
                    bool IsSkipRec = false;
                    if (Chat.CustomerIdBy == ChatModel.CustomerIdBy && Convert.ToBoolean(Chat.IsDeletedCustomerBy))
                    {
                        IsSkipRec = true;
                    }
                    else if (Chat.CustomerIdTo == ChatModel.CustomerIdBy && Convert.ToBoolean(Chat.IsDeletedCustomerTo))
                    {
                        IsSkipRec = true;
                    }

                    if (!IsSkipRec)
                    {
                        //When Our Customer ID (By) will match with Others CustomerID (To) then Update Read Message status
                        if (Chat.CustomerIdTo == ChatModel.CustomerIdBy)
                        {
                            //Update the Chat For IsRead Field true, It will Update by Trigger in SQL Table
                            _ChatService.Update(new HomeHelp.Entity.Chat
                            {
                                ChatId              = Chat.ChatId,
                                CustomerIdBy        = Chat.CustomerIdBy,
                                CustomerIdTo        = Chat.CustomerIdTo,
                                ChatContent         = Chat.ChatContent,
                                DateTimeCreated     = Chat.DateTimeCreated,
                                IsDeletedCustomerBy = Chat.IsDeletedCustomerBy,
                                IsDeletedCustomerTo = Chat.IsDeletedCustomerTo,
                                IsRead              = true
                            });
                            //End : Update the Chat For IsRead Field true

                            //Set the Read Message Status for List
                            Chat.IsRead = true;
                        }
                        Models.ChatsModel chatModel        = Mapper.Map <HomeHelp.Entity.Chat, HomeHelp.Models.ChatsModel>(Chat);
                        string            sqlFormattedDate = Chat.DateTimeCreated.HasValue ? Chat.DateTimeCreated.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") : "";

                        chatModel.DateTimeCreated = sqlFormattedDate;
                        //chatModel.ChatTime = chatTime(Chat.DateTimeCreated);


                        // chatModel.ChatTime = Convert.ToDateTime(Chat.DateTimeCreated).ToString("hh:mm tt");
                        //Set Customer By
                        Mapper.CreateMap <HomeHelp.Entity.Customer, HomeHelp.Models.UserCustomerDetailModel>();
                        HomeHelp.Entity.Customer       customersBy     = _CustomerService.GetCustomer(Chat.CustomerIdBy);
                        Models.UserCustomerDetailModel customerByModel = Mapper.Map <HomeHelp.Entity.Customer, HomeHelp.Models.UserCustomerDetailModel>(customersBy);
                        //End : Set Customer By
                        chatModel.CustomersBy = customerByModel;
                        //Set Customer To
                        Mapper.CreateMap <HomeHelp.Entity.Customer, HomeHelp.Models.UserCustomerDetailModel>();
                        HomeHelp.Entity.Customer       customersTo     = _CustomerService.GetCustomer(Chat.CustomerIdTo);
                        Models.UserCustomerDetailModel customerToModel = Mapper.Map <HomeHelp.Entity.Customer, HomeHelp.Models.UserCustomerDetailModel>(customersTo);
                        //End : Set Customer To
                        chatModel.CustomersTo = customerToModel;
                        count++;

                        models.Add(chatModel);
                    }
                }

                int numberOfObjectsPerPage = 10;
                var modelsdata             = models.OrderByDescending(c => c.DateTimeCreated).Skip(numberOfObjectsPerPage * ChatModel.PageNumber).Take(numberOfObjectsPerPage).ToList();
                //userList.CountMessage = count;
                //userList.chatList = modelsdata;
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", modelsdata), Configuration.Formatters.JsonFormatter));
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", models), Configuration.Formatters.JsonFormatter));
            }
        }