Esempio n. 1
0
        private void SaveMessageToConversation(long customerId, long toCustomerId, string message)
        {
            using (var db = new ChatSignalrContext())
            {
                var ids = new long[] { customerId, toCustomerId };
                // get old conversation between 2 customers
                var conv = db.Conversations
                           .Include(i => i.Customers)
                           .FirstOrDefault(x => x.Customers.Count == 2 && x.Customers.All(n => ids.Contains(n.Id)));

                var newMsg = new Message
                {
                    Content     = message,
                    DateCreated = DateTime.Now,
                    Customer    = db.Customers.Find(customerId)
                };

                if (conv == null)
                {
                    conv = new Conversation();
                    conv.Customers.Add(db.Customers.Find(customerId));
                    conv.Customers.Add(db.Customers.Find(toCustomerId));
                    conv.FirstMessage = newMsg;
                    db.Conversations.Add(conv);
                    db.SaveChanges();
                }

                conv.Messages.Add(newMsg);

                conv.LastMessage     = conv.Messages.Last();
                db.Entry(conv).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
Esempio n. 2
0
        public ActionResult SignalRChat()
        {
            // # BƯỚC NÀY SẼ CHUẨN BỊ DỮ LIỆU HỢP LỆ CHO ChatHub.cs
            // # KIEM TRA COOKIE HỢP LỆ
            // # NEU KO HỢP LỆ THÌ TẠO CUSTOMER MỚI & LƯU VÀO COOKIE MỚI

            var cookieValue = GetBasicCookie(AppConstants.COOKIE_CHAT_CUSTOMERID);

            if (string.IsNullOrEmpty(cookieValue))
            {
                //if (!int.TryParse(Request.Cookies.Get(AppConstants.COOKIE_CHAT_CUSTOMERID)?.Value, out customerId)  // neu ko parse dc customerId
                //    || !CheckUserExisted(customerId))    // neu customer ko ton tai trong db

                // add new customer
                var index       = db.Customers.Count() + 1;
                var newCustomer = new Customer();
                newCustomer.Name = "Guest";
                db.Customers.Add(newCustomer);
                db.SaveChanges();
                newCustomer.Name           += " " + newCustomer.Id;
                db.Entry(newCustomer).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                // set cookie customerid
                //var newCookie = new HttpCookie(AppConstants.COOKIE_CHAT_CUSTOMERID, newCustomer.Id.ToString());
                //newCookie.Expires = DateTime.Now.AddMonths(1);
                //Response.SetCookie(newCookie);
                SetBasicCookie(AppConstants.COOKIE_CHAT_CUSTOMERID, newCustomer.Id.ToString());
            }

            return(View());
        }
        public ActionResult Create([Bind(Include = "Id,Name")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(customer));
        }
Esempio n. 4
0
        public override Task OnConnected()
        {
            var currentUserId = GetCurrentContextUserId();

            using (var db = new ChatSignalrContext())
            {
                // #1 - Check Valid: current user id from cookie phai luon co trong db, buoc nay da duoc kiem tra o ChatRoomController
                if (currentUserId == 0 || !db.Customers.Any(n => n.Id == currentUserId))
                {
                    // Nếu ko tìm thấy user , nhưng ko chắc chắn có set đc cookie ở trong Hub này không
                    // nên tạm thời xử lý trường hợp này ở ChatRoomController.
                    Clients.Caller.showErrorMessage("Could not find current user (" + currentUserId + ") or CurrentUserId is empty, please reload page again to get new UserId");
                    return(base.OnConnected());
                }

                // #2 - Add new user connection
                var user = db.Customers
                           .Include(i => i.Connections)
                           .FirstOrDefault(x => x.Id == currentUserId);
                user.Connections.Add(new Connection
                {
                    Connected    = true,
                    UserAgent    = Context.Request.Headers["User-Agent"],
                    ConnectionId = Context.ConnectionId
                });
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                // #3 show list all online users to the caller
                var onlineUsers = db.Customers
                                  .Include(i => i.Connections)
                                  .Where(x => x.Connections.Any(n => n.Connected));

                foreach (var item in onlineUsers) // (KeyValuePair<long, Customer> entry in dictOnlineCustomers)
                {
                    // load onlines in caller
                    Clients.Caller.online(item.Id, item.Name);
                }

                // #4 notify this user have entered to the others.
                Clients.Others.enters(user.Id, user.Name);
            }

            return(base.OnConnected());
        }
Esempio n. 5
0
        private void TestDataDemo()
        {
            using (var db = new ChatSignalrContext())
            {
                var allConn = db.Customers
                              .Include(i => i.Connections)
                              .SelectMany(s => s.Connections)
                              .Where(x => x.Connected)
                              .ToList();

                foreach (var item in allConn)
                {
                    item.Connected       = false;
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }
Esempio n. 6
0
        // Can test lai ve ham disconnect nay
        //public override Task OnDisconnected(bool stopCalled)
        //{
        //    //var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
        //    var item = dictOnlineCustomers.FirstOrDefault(x => x.Value.Connections.Any(n => n.ConnectionId == Context.ConnectionId));
        //    Customer s;
        //    if (!dictOnlineCustomers.TryRemove(item.Key, out s))
        //        throw new Exception("Customer " + item.Key + " remove failed!");

        //    // notify caller about the disconnection if current chat view is still existing.
        //    Clients.Caller.selfDisconnected(item.Key, item.Value.Name);
        //    // notify all about the disconnection
        //    return Clients.All.disconnected(item.Key, item.Value.Name);
        //    //base.OnDisconnected(stopCalled: true);
        //}



        /// <summary>
        /// Kiem tra lai truong hop nao se goi
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            // #1 truon ghop refresh lai page
            // #2 truon ghop close tab or browser

            //var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
            var dictItem = dictOnlineCustomers.FirstOrDefault(x => x.Value.Connections.Any(n => n.ConnectionId == Context.ConnectionId));

            using (var db = new ChatSignalrContext())
            {
                // update connected status

                var customer = db.Customers
                               .FirstOrDefault(x => x.Id == dictItem.Key);
                var conn = customer.Connections.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
                conn.Connected       = false;
                db.Entry(conn).State = EntityState.Modified;
                db.SaveChanges();

                var connItem = dictItem.Value.Connections.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
                dictItem.Value.Connections.Remove(connItem);
            }

            // if this customer not has nay connections: notify to all about this disconnection
            if (dictItem.Value.Connections.Count == 1)
            {
                Customer s;
                if (!dictOnlineCustomers.TryRemove(dictItem.Key, out s))
                {
                    throw new Exception("Customer " + dictItem.Key + " remove failed!");
                }

                // notify caller about the disconnection if current chat view is still existing.
                Clients.Caller.selfDisconnected(dictItem.Key, dictItem.Value.Name);
                // notify all about the disconnection
                Clients.All.disconnected(dictItem.Key, dictItem.Value.Name);
            }

            return(base.OnDisconnected(stopCalled));
        }
Esempio n. 7
0
        public override Task OnDisconnected(bool stopCalled)
        {
            using (var db = new ChatSignalrContext())
            {
                var user = db.Customers
                           .Include(i => i.Connections)
                           .FirstOrDefault(x => x.Connections.Any(n => n.ConnectionId == Context.ConnectionId));

                var conn = user.Connections
                           .FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);

                conn.Connected       = false;
                db.Entry(conn).State = EntityState.Modified;
                db.SaveChanges();

                if (!user.Connections.Any(n => n.Connected))
                {
                    // If all user connections is disconnected, notify to all about this disconnection of the user.
                    Clients.All.disconnected(user.Id, user.Name);
                }
            }

            return(base.OnDisconnected(stopCalled));
        }
Esempio n. 8
0
        //public void Notify() //  public void Notify(string name, string id)
        //{
        //    var customerId = GetCookieCustomerId();
        //    if (dictOnlineCustomers.ContainsKey(customerId))
        //    {
        //        Clients.Caller.differentName();
        //    }
        //    else
        //    {
        //        dictOnlineCustomers.TryAdd(customerId, id);
        //        foreach (KeyValuePair<String, String> entry in dic)
        //        {
        //            Clients.Caller.online(entry.Key);
        //        }
        //        Clients.Others.enters(name);
        //    }
        //}

        //public override Task OnConnected()
        //{
        //    // #1 check valid customerid (ChatRoom/SignalrChat is already checked & prepared)
        //    Cookie s;
        //    int customerId = 0;
        //    if (!Context.Request.Cookies.TryGetValue(AppConstants.COOKIE_CHAT_CUSTOMERID, out s) // neu ko ton tai cookie
        //        || !int.TryParse(s.Value, out customerId)   // neu ko parse dc customerId
        //        || !CheckExisted(customerId))    // neu customer ko ton tai trong db
        //        throw new Exception("Need to check valid cookie " + AppConstants.COOKIE_CHAT_CUSTOMERID + " in action ChatRoom/SignalRChat");

        //    using (var db = new ChatSignalrContext())
        //    {
        //        var customer = db.Customers
        //            .Include(i => i.Connections)
        //            .FirstOrDefault(x => x.Id == customerId);

        //        // #2 update old customer connections, set connected = false
        //        foreach (var itm in customer.Connections.Where(x => !x.Connected).ToList())
        //        {
        //            itm.Connected = false;
        //            db.Entry(itm).State = EntityState.Modified;
        //            db.SaveChanges();
        //        }

        //        // #3 update new customer connection to current customer
        //        customer.Connections.Add(new Connection
        //        {
        //            Connected = true,
        //            UserAgent = Context.Request.Headers["User-Agent"],
        //            ConnectionId = Context.ConnectionId
        //        });

        //        db.Entry(customer).State = EntityState.Modified;
        //        db.SaveChanges();

        //        // #4 update onlines list to dict
        //        if (dictOnlineCustomers.ContainsKey(customer.Id))
        //        {
        //            /// truong hợp mở tab mới trong khi tab cũ chưa ngắt kết nối
        //            /// tạm thời ko xét trường hợp này
        //            // throw new Exception("This customer - " + customer.Id + " is online");
        //        }
        //        else
        //        {
        //            //add model only
        //            var customerModel = new Customer
        //            {
        //                Connections = customer.Connections.Where(x => x.Connected).ToList(),
        //                Id = customer.Id,
        //                Name = customer.Name,
        //            };

        //            if (!dictOnlineCustomers.TryAdd(customerModel.Id, customerModel))
        //                throw new Exception("Add this customer " + customerModel.Id + " to dictOnlineCustomers is failed!");
        //        }

        //        // #5 notify (update) onlines list to all current customers
        //        foreach (KeyValuePair<long, Customer> entry in dictOnlineCustomers)
        //        {
        //            // load onlines in caller
        //            string lastMessage = "";
        //            Clients.Caller.online(entry.Key, entry.Value.Name, lastMessage);
        //            //Clients.All.online(entry.Key, entry.Value.Name);
        //        }

        //        // notify other this customer have enter.
        //        Clients.Others.enters(customer.Id, customer.Name);
        //    }

        //    return base.OnConnected();
        //}

        public override Task OnConnected()
        {
            System.Threading.Thread.Sleep(4000);

            // #1 check valid customerid (ChatRoom/SignalrChat is already checked & prepared)
            Cookie s;
            int    customerId = 0;

            if (!Context.Request.Cookies.TryGetValue(AppConstants.COOKIE_CHAT_CUSTOMERID, out s) || // neu ko ton tai cookie
                !int.TryParse(s.Value, out customerId) || // neu ko parse dc customerId
                !CheckExisted(customerId))                // neu customer ko ton tai trong db
            {
                throw new Exception("Need to check valid cookie " + AppConstants.COOKIE_CHAT_CUSTOMERID + " in action ChatRoom/SignalRChat");
            }

            using (var db = new ChatSignalrContext())
            {
                var user = db.Customers
                           .Include(i => i.Connections)
                           .FirstOrDefault(x => x.Id == customerId);

                // #3 add connection to current user
                var newConn = new Connection
                {
                    Connected    = true,
                    UserAgent    = Context.Request.Headers["User-Agent"],
                    ConnectionId = Context.ConnectionId
                };

                user.Connections.Add(newConn);
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                var newestActiveConns = user.Connections.Where(x => x.Connected).ToList();

                // #4 update onlines list to dict
                if (dictOnlineCustomers.ContainsKey(user.Id))
                {
                    // update connection to dictionary
                    //var item = dictOnlineCustomers.FirstOrDefault(x => x.Value.Connections.Any(n => n.ConnectionId == Context.ConnectionId));
                    var item = dictOnlineCustomers.FirstOrDefault(x => x.Key == user.Id);
                    item.Value.Connections.Clear();
                    item.Value.Connections = newestActiveConns; // kie tra lai de dam bao se cap nhat vao dict
                }
                else
                {
                    // add model only
                    var customerModel = new Customer
                    {
                        Connections = newestActiveConns,
                        Id          = user.Id,
                        Name        = user.Name,
                    };

                    if (!dictOnlineCustomers.TryAdd(customerModel.Id, customerModel))
                    {
                        throw new Exception("Add this customer " + customerModel.Id + " to dictOnlineCustomers is failed!");
                    }
                }

                // #5 notify (update) onlines list to all current customers
                foreach (KeyValuePair <long, Customer> entry in dictOnlineCustomers)
                {
                    // load onlines in caller
                    string lastMessage = "";
                    Clients.Caller.online(entry.Key, entry.Value.Name, lastMessage);
                    //Clients.All.online(entry.Key, entry.Value.Name);
                }

                // notify other this customer have enter.
                Clients.Others.enters(user.Id, user.Name);
            }

            return(base.OnConnected());
        }