Beispiel #1
0
        public void ConnectionTimeoutTest()
        {
            // Arrange
            var connection = new Mock <Client.IConnection>();
            var transport  = new Mock <IClientTransport>();

            transport.Setup(m => m.SupportsKeepAlive).Returns(true);

            // Setting the values such that a timeout happens almost instantly
            var keepAliveData = new KeepAliveData(
                timeoutWarning: TimeSpan.FromSeconds(10),
                timeout: TimeSpan.FromSeconds(1),
                checkInterval: TimeSpan.FromSeconds(2)
                );

            using (var monitor = new HeartbeatMonitor(connection.Object, new object(), keepAliveData.CheckInterval))
            {
                connection.Setup(m => m.LastMessageAt).Returns(DateTime.UtcNow);
                connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
                connection.Setup(m => m.State).Returns(ConnectionState.Connected);
                connection.Setup(m => m.Transport).Returns(transport.Object);

                monitor.Start();

                // Act - Setting timespan to be greater then timeout
                monitor.Beat(TimeSpan.FromSeconds(5));

                // Assert
                Assert.True(monitor.TimedOut);
                Assert.False(monitor.HasBeenWarned);
                transport.Verify(m => m.LostConnection(connection.Object), Times.Once());
            }
        }
        public void ConnectionTimeoutTest()
        {
            // Arrange
            var connection = new Mock<Client.IConnection>();
            var transport = new Mock<IClientTransport>();

            transport.Setup(m => m.SupportsKeepAlive).Returns(true);

            // Setting the values such that a timeout happens almost instantly
            var keepAliveData = new KeepAliveData(
                timeoutWarning: TimeSpan.FromSeconds(10),
                timeout: TimeSpan.FromSeconds(1),
                checkInterval: TimeSpan.FromSeconds(2)
            );

            using (var monitor = new HeartbeatMonitor(connection.Object, new object(), keepAliveData.CheckInterval))
            {
                connection.Setup(m => m.LastMessageAt).Returns(DateTime.UtcNow);
                connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
                connection.Setup(m => m.State).Returns(ConnectionState.Connected);
                connection.Setup(m => m.Transport).Returns(transport.Object);

                monitor.Start();

                // Act - Setting timespan to be greater then timeout
                monitor.Beat(TimeSpan.FromSeconds(5));

                // Assert
                Assert.True(monitor.TimedOut);
                Assert.False(monitor.HasBeenWarned);
                transport.Verify(m => m.LostConnection(connection.Object), Times.Once());
            }
        }
Beispiel #3
0
        public void TestSuccess()
        {
            long actualNumHeartbeats = 0;

            _heartbeat.Setup(x => x.Beat())
            .Returns(() => Task.Factory.StartNew(() => { Interlocked.Increment(ref actualNumHeartbeats); }));

            HeartbeatMonitor monitor;

            using (monitor = new HeartbeatMonitor(_heartbeat.Object,
                                                  Debugger.Instance,
                                                  TimeSpan.FromSeconds(value: 0.1),
                                                  failureThreshold: 1,
                                                  enabledWithAttachedDebugger: true,
                                                  useHeartbeatFailureDetection: true,
                                                  allowRemoteHeartbeatDisable: true,
                                                  connectionId: _connectionId,
                                                  endPointName: "Test",
                                                  locEndPoint: _localEndPoint,
                                                  remoteEndPoint: _remoteEndPoint))
            {
                var failureDetected = false;
                monitor.OnFailure += unuse => failureDetected = true;
                monitor.Start();

                Thread.Sleep(TimeSpan.FromSeconds(value: 1));
                Console.WriteLine("# heartbeats: {0}", monitor.NumHeartbeats);

                monitor.FailureDetected.Should().BeFalse();
                failureDetected.Should().BeFalse();
            }

            // There should be 10 heartbeats in a perfect world, let's just verify that we've got half of that
            monitor.NumHeartbeats.Should().BeGreaterOrEqualTo(expected: 5);
        }
Beispiel #4
0
        public void NormalConnectionTest()
        {
            // Arrange
            var connection = new Mock <Client.IConnection>();
            var transport  = new Mock <IClientTransport>();

            // Setting the values such that a timeout or timeout warning isn't issued
            var keepAliveData = new KeepAliveData(
                timeoutWarning: TimeSpan.FromSeconds(5),
                timeout: TimeSpan.FromSeconds(10),
                checkInterval: TimeSpan.FromSeconds(2)
                );

            using (var monitor = new HeartbeatMonitor(connection.Object, new object(), keepAliveData.CheckInterval))
            {
                connection.Setup(m => m.LastMessageAt).Returns(DateTime.UtcNow);
                connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
                connection.Setup(m => m.State).Returns(ConnectionState.Connected);
                connection.Setup(m => m.Transport).Returns(transport.Object);

                monitor.Start();

                // Act - Setting timespan to be less than timeout and timeout warning
                monitor.Beat(TimeSpan.FromSeconds(2));

                // Assert
                Assert.False(monitor.TimedOut);
                Assert.False(monitor.HasBeenWarned);
            }
        }
Beispiel #5
0
        public static void Run(bool console = false)
        {
            BackgroundPool.config = new SettingsConfiguration();

            oUsToMonitor   = config.OUsToMonitor;
            oUsDNToMonitor = config.OUsDNToMonitor;

            try
            {
                InitializeLogging(console);

                PerformStartupChecks(config);

                hb = new HeartbeatMonitor();
                hb.configuration = config;
                hb.Start();

                threadBackgroundWorker.IsBackground = true;
                if (threadBackgroundWorker.ThreadState.HasFlag(System.Threading.ThreadState.Unstarted))
                {
                    threadBackgroundWorker.Start();
                }
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    Console.Error.WriteLine(e.InnerException.Message);
                    log.LogFatal(e.InnerException.Message);
                }
                Console.Error.WriteLine(e.Message);
                log.LogFatal(e.Message);
                throw;
            }
        }
        public void TimeoutWarningTest()
        {
            // Arrange
            var connection = new Mock <Client.IConnection>();
            var monitor    = new HeartbeatMonitor(connection.Object, new object());

            // Setting the values such that a warning is thrown almost instantly and a timeout doesn't occur
            var keepAliveData = new KeepAliveData(
                lastKeepAlive: DateTime.UtcNow,
                timeoutWarning: TimeSpan.FromSeconds(1),
                timeout: TimeSpan.FromSeconds(20),
                checkInterval: TimeSpan.FromSeconds(2)
                );

            connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
            connection.Setup(m => m.State).Returns(ConnectionState.Connected);

            // Act - Setting timespan to be greater than timeout warining but less than timeout
            monitor.Beat(TimeSpan.FromSeconds(5));

            // Assert
            Assert.True(monitor.HasBeenWarned);
            Assert.False(monitor.TimedOut);
            connection.Verify(m => m.OnConnectionSlow(), Times.Once());
        }
        public void ReconnectedClearsTimedOutAndHasBeenWarnedFlags()
        {
            var mockTransport = new Mock <IClientTransport>();

            mockTransport.Setup(t => t.SupportsKeepAlive).Returns(true);

            var mockConnection = new Mock <IConnection>();

            mockConnection.Setup(c => c.Transport).Returns(mockTransport.Object);
            mockConnection.Setup(c => c.KeepAliveData).Returns(new KeepAliveData(new TimeSpan(0, 0, 9)));
            mockConnection.Setup(c => c.State).Returns(ConnectionState.Connected);

            using (var monitor = new HeartbeatMonitor(mockConnection.Object, new object(), new TimeSpan(1, 0, 0)))
            {
                monitor.Start();
                // sets TimedOut flag
                monitor.Beat(new TimeSpan(0, 10, 0));
                // sets HasBeenWarned flag
                monitor.Beat(new TimeSpan(0, 0, 7));
                Assert.True(monitor.TimedOut);
                Assert.True(monitor.HasBeenWarned);

                monitor.Reconnected();
                Assert.False(monitor.TimedOut);
                Assert.False(monitor.HasBeenWarned);
            }
        }
        public void ReconnectedClearsTimedOutAndHasBeenWarnedFlags()
        {
            var mockTransport = new Mock<IClientTransport>();
            mockTransport.Setup(t => t.SupportsKeepAlive).Returns(true);

            var mockConnection = new Mock<IConnection>();
            mockConnection.Setup(c => c.Transport).Returns(mockTransport.Object);
            mockConnection.Setup(c => c.KeepAliveData).Returns(new KeepAliveData(new TimeSpan(0, 0, 9)));
            mockConnection.Setup(c => c.State).Returns(ConnectionState.Connected);

            using (var monitor = new HeartbeatMonitor(mockConnection.Object, new object(), new TimeSpan(1, 0, 0)))
            {
                monitor.Start();
                // sets TimedOut flag
                monitor.Beat(new TimeSpan(0, 10, 0));
                // sets HasBeenWarned flag
                monitor.Beat(new TimeSpan(0, 0, 7));
                Assert.True(monitor.TimedOut);
                Assert.True(monitor.HasBeenWarned);

                monitor.Reconnected();
                Assert.False(monitor.TimedOut);
                Assert.False(monitor.HasBeenWarned);
            }
        }
Beispiel #9
0
        public void NormalConnectionTest()
        {
            // Arrange
            var connection = new Mock<Client.IConnection>();
            var monitor = new HeartbeatMonitor(connection.Object, new object());
            var transport = new Mock<IClientTransport>();

            // Setting the values such that a timeout or timeout warning isn't issued
            var keepAliveData = new KeepAliveData(
                lastKeepAlive: DateTime.UtcNow,
                timeoutWarning: TimeSpan.FromSeconds(5),
                timeout: TimeSpan.FromSeconds(10),
                checkInterval: TimeSpan.FromSeconds(2)
            );

            connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
            connection.Setup(m => m.State).Returns(ConnectionState.Connected);
            connection.Setup(m => m.Transport).Returns(transport.Object);

            // Act - Setting timespan to be less than timeout and timeout warning
            monitor.Beat(TimeSpan.FromSeconds(2));

            // Assert
            Assert.False(monitor.TimedOut);
            Assert.False(monitor.HasBeenWarned);
        }
Beispiel #10
0
        public void TimeoutWarningTest()
        {
            // Arrange
            var connection = new Mock<Client.IConnection>();
            var monitor = new HeartbeatMonitor(connection.Object, new object());

            // Setting the values such that a warning is thrown almost instantly and a timeout doesn't occur
            var keepAliveData = new KeepAliveData(
                lastKeepAlive: DateTime.UtcNow,
                timeoutWarning: TimeSpan.FromSeconds(1),
                timeout: TimeSpan.FromSeconds(20),
                checkInterval: TimeSpan.FromSeconds(2)
            );

            connection.Setup(m => m.KeepAliveData).Returns(keepAliveData);
            connection.Setup(m => m.State).Returns(ConnectionState.Connected);

            // Act - Setting timespan to be greater than timeout warining but less than timeout
            monitor.Beat(TimeSpan.FromSeconds(5));

            // Assert
            Assert.True(monitor.HasBeenWarned);
            Assert.False(monitor.TimedOut);
            connection.Verify(m => m.OnConnectionSlow(), Times.Once());
        }
Beispiel #11
0
        protected HeartbeatMonitor AddHeartBeatMonitor()
        {
            var monitor = new HeartbeatMonitor(CategoryName);

            _registeredMonitors.Add(monitor);

            return(monitor);
        }
Beispiel #12
0
        public void TestDetectFailure4()
        {
            const bool enabledWithAttachedDebugger = false;

            _debugger.Setup(x => x.IsDebuggerAttached).Returns(value: true);

            long     actualNumHeartbeats = 0;
            DateTime?failureStarted      = null;

            _heartbeat.Setup(x => x.Beat())
            .Returns(() => Task.Factory.StartNew(() =>
            {
                // Let's simulate failure by blocking the task
                if (++actualNumHeartbeats == 25)
                {
                    failureStarted = DateTime.Now;
                    Thread.Sleep(millisecondsTimeout: 10000);
                }
            }));

            HeartbeatMonitor monitor;

            using (
                monitor =
                    new HeartbeatMonitor(_heartbeat.Object,
                                         _debugger.Object,
                                         TimeSpan.FromSeconds(value: 0.01),
                                         failureThreshold: 1,
                                         enabledWithAttachedDebugger: enabledWithAttachedDebugger,
                                         useHeartbeatFailureDetection: true,
                                         allowRemoteHeartbeatDisable: true,
                                         connectionId: _connectionId,
                                         endPointName: "Test",
                                         locEndPoint: _localEndPoint,
                                         remoteEndPoint: _remoteEndPoint))
            {
                var failureDetected = false;
                var actualId        = ConnectionId.None;
                monitor.OnFailure += id =>
                {
                    failureDetected = true;
                    actualId        = id;
                };
                monitor.Start();

                Thread.Sleep(TimeSpan.FromSeconds(value: 1));
                Console.WriteLine("# heartbeats: {0}", monitor.NumHeartbeats);

                const string reason = "Because the debugger is attached and no failures shall be reported when this is the case";
                monitor.FailureDetected.Should().BeFalse(reason);
                failureDetected.Should().BeFalse(reason);
                actualId.Should().Be(ConnectionId.None);
                failureStarted.Should().HaveValue();
                monitor.NumHeartbeats.Should().BeGreaterOrEqualTo(expected: 25);
            }
        }
        /// <summary>
        /// @Author: Taylor
        /// Launches the chat client. Sets session data for the client to be retrieved by the ChatValidatorController during authentication
        /// </summary>
        /// <returns>The Chat Client</returns>
        public ActionResult Index()
        {
            List<String> friendsList = new List<String>();

            var uid = SessionHandler.UID;

            //If the uid is negative one, the user must not be logged in.
            if (uid == -1)
            {
                return RedirectToAction("Log_in", "Login");
            }

            User user = (from u in db.Users
                         where u.id == uid
                         select u).FirstOrDefault();

            try
            {
                List<int> friends = (from friendslist in db.FriendsLists
                                     where friendslist.id == SessionHandler.UID
                                     select friendslist.friend_id
                               ).ToList();

                foreach (var friend in friends)
                {
                    User u = (from fUser in db.Users
                              where friend.Equals(fUser.id)
                              orderby fUser.username
                              select fUser).FirstOrDefault();
                    friendsList.Add(u.username);
                    //list.Add(friend.User);
                }
            }
            catch (Exception ex)
            {

            }
            SessionHandler.Username = user.username;
            SessionHandler.Banned = user.is_banned;
            SessionHandler.FriendsList = friendsList;

            loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);

            bool isAdmin = false;

            if (user.role == "admin")
            {
                isAdmin = true;
            }

            SessionHandler.IsAdmin = isAdmin;

            return View("Chat");
        }
Beispiel #14
0
        private void TestFailure(IDebugger debugger, bool enabledWithAttachedDebugger)
        {
            long     actualNumHeartbeats = 0;
            DateTime?failureStarted      = null;

            _heartbeat.Setup(x => x.Beat())
            .Returns(() => Task.Factory.StartNew(() =>
            {
                // Let's simulate failure by blocking the task
                if (++actualNumHeartbeats == 25)
                {
                    failureStarted = DateTime.Now;
                    Thread.Sleep(millisecondsTimeout: 10000);
                }
            }));

            HeartbeatMonitor monitor;

            using (
                monitor =
                    new HeartbeatMonitor(_heartbeat.Object,
                                         debugger,
                                         TimeSpan.FromSeconds(value: 0.01),
                                         failureThreshold: 1,
                                         enabledWithAttachedDebugger: enabledWithAttachedDebugger, useHeartbeatFailureDetection: true,
                                         allowRemoteHeartbeatDisable: true, connectionId: _connectionId,
                                         endPointName: "Test",
                                         locEndPoint: _localEndPoint,
                                         remoteEndPoint: _remoteEndPoint))
            {
                var failureDetected = false;
                var actualId        = ConnectionId.None;
                monitor.OnFailure += id =>
                {
                    failureDetected = true;
                    actualId        = id;
                };
                monitor.Start();

                Thread.Sleep(TimeSpan.FromSeconds(value: 1));
                Console.WriteLine("# heartbeats: {0}", monitor.NumHeartbeats);

                monitor.FailureDetected.Should().BeTrue();
                failureDetected.Should().BeTrue();
                actualId.Should().Be(_connectionId);
                monitor.NumHeartbeats.Should().Be(expected: 24, because: "Because failure was initiated on the 25th heartbeat");
                monitor.LastHeartbeat.Should().BeOnOrBefore(failureStarted.Value);
            }
        }
Beispiel #15
0
 public void TestStart()
 {
     using (var monitor = new HeartbeatMonitor(_heartbeat.Object,
                                               Debugger.Instance,
                                               new HeartbeatSettings(),
                                               _connectionId,
                                               "Test",
                                               _localEndPoint,
                                               _remoteEndPoint))
     {
         monitor.IsStarted.Should().BeFalse();
         monitor.Start();
         monitor.IsStarted.Should().BeTrue();
     }
 }
Beispiel #16
0
        public void TestTaskExceptionObservation()
        {
            var settings = new HeartbeatSettings
            {
                Interval = TimeSpan.FromMilliseconds(value: 10)
            };

            var exceptions = new List <Exception>();

            TaskScheduler.UnobservedTaskException += (sender, args) => exceptions.Add(args.Exception);

            using (var heartbeatFailure = new ManualResetEvent(initialState: false))
                using (
                    var monitor = new HeartbeatMonitor(_heartbeat.Object,
                                                       _debugger.Object,
                                                       settings,
                                                       _connectionId,
                                                       "Test",
                                                       _localEndPoint,
                                                       _remoteEndPoint))
                {
                    _heartbeat.Setup(x => x.Beat())
                    .Returns(() =>
                    {
                        var task = new Task(() =>
                        {
                            heartbeatFailure.WaitOne();
                            throw new ConnectionLostException();
                        });
                        task.Start();
                        return(task);
                    });

                    monitor.OnFailure += id => heartbeatFailure.Set();
                    monitor.Start();

                    heartbeatFailure.WaitOne(TimeSpan.FromMilliseconds(value: 500))
                    .Should().BeTrue("Because the task doesn't return before a failure was reported");
                }

            GC.Collect(generation: 2, mode: GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            exceptions.Should().Equal();
        }
Beispiel #17
0
        public void TestCtor1()
        {
            var monitor = new HeartbeatMonitor(_heartbeat.Object,
                                               Debugger.Instance,
                                               TimeSpan.FromSeconds(value: 2),
                                               failureThreshold: 4,
                                               enabledWithAttachedDebugger: true,
                                               useHeartbeatFailureDetection: true,
                                               allowRemoteHeartbeatDisable: true,
                                               connectionId: _connectionId,
                                               endPointName: "Test",
                                               locEndPoint: _localEndPoint,
                                               remoteEndPoint: _remoteEndPoint);

            monitor.Interval.Should().Be(TimeSpan.FromSeconds(value: 2));
            monitor.FailureInterval.Should()
            .Be(TimeSpan.FromSeconds(value: 10),
                "because we specified that 4 skipped heartbeats are to indicate failure which translates to 10 seconds");
            monitor.IsStarted.Should().BeFalse();
            monitor.IsDisposed.Should().BeFalse();
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// POST: Allows the user to remove the sent request, if the person hasn't responded to the request.
        /// </summary>
        /// <param name="userID">ID of the user to whom the friend request is sent.</param>
        /// <returns></returns>
        public ActionResult RemoveRequest(int friendID)
        {
            try
            {
                HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                FriendsList friend = (from f in db.FriendsLists
                                      where f.id == SessionHandler.UID && f.friend_id == friendID
                                      select f).FirstOrDefault();

                if (friend != null)
                {
                    db.FriendsLists.Remove(friend);

                    db.SaveChanges();
                }

                return RedirectToAction("Find", "FriendList");
            }
            catch (Exception ex)
            {
                return View("~/Views/Shared/Error.cshtml", ex);
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// Takes in the input and searches the database for either the user's firstname or lastname,
        /// or searches based on the user's username and returns the result to the view.
        /// </summary>
        /// <param name="friendSearchTxt">Value from the search text box</param>
        /// <param name="searchMethod">Value from the dropdown, which contains where to search based on the username or firstname lastname.</param>
        /// <returns></returns>
        public ActionResult Search(string friendSearchTxt, string searchMethod)
        {
            HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
            ViewBag.Message = "Friend Search Results";
            List<User> result = new List<User>();
            List<User> pendingList = new List<User>();
            List<User> friendsList = new List<User>();
            List<User> me = new List<User>();
            Dictionary<string, List<User>> searchResult = new Dictionary<string, List<User>>();
            if (SessionHandler.Logon)
            {
                string searchTxt = SecurityHelper.StripHTML(friendSearchTxt.ToLower());
                try
                {
                    List<FriendsList> pending = (from friendslist in db.FriendsLists
                                                 where friendslist.id == SessionHandler.UID && friendslist.status.Equals("pending")
                                                 select friendslist
                                           ).ToList();

                    List<FriendsList> friends = (from friendslist in db.FriendsLists
                                                 where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                                 select friendslist
                                           ).ToList();

                    if (pending != null)
                    {
                        foreach (var pend in pending)
                        {
                            User u = (from user in db.Users
                                      where pend.friend_id == user.id
                                      select user).FirstOrDefault();
                            pendingList.Add(u);
                        }
                    }

                    if (friends != null)
                    {
                        foreach (var friend in friends)
                        {
                            User u = (from user in db.Users
                                      where friend.friend_id == user.id
                                      select user).FirstOrDefault();
                            friendsList.Add(u);
                        }
                    }

                    if (searchMethod.Equals("name"))
                    {
                        // search based on first and last name
                        result = (from user in db.Users
                                  where user.firstname.ToLower().Equals(searchTxt) ||
                                  user.lastname.ToLower().Equals(searchTxt)
                                  select user).ToList();

                    }
                    else if (searchMethod.Equals("uname"))
                    {
                        // search based on the username
                        result = (from user in db.Users
                                  where user.username.ToLower().Equals(searchTxt)
                                  select user).ToList();
                    }

                    if (result.Count > 0)
                    {
                        me = (from user in db.Users
                              where user.id == SessionHandler.UID
                              select user).ToList();

                        var result2 = result.Except(me);
                        searchResult.Add("searchResult", result2.ToList());
                        searchResult.Add("pending", pendingList);
                        searchResult.Add("friend", friendsList);
                        return View("SearchFriends", searchResult);
                    }
                    else
                    {
                        searchResult.Add("searchResult", result);
                        searchResult.Add("pending", pendingList);
                        searchResult.Add("friend", friendsList);

                        ViewBag.SearchMessage = "No results found for your query: \" " + friendSearchTxt + " \"";
                        return View("SearchFriends", searchResult);
                    }
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }

            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// POST: if the user chooses Accept friend request, this function takes the id of the user
        /// who chooses "accept" and who sent the request and adds the row to the friendslist table
        /// and also access the row entered by the user who sent the request and changes the status
        /// from "pending" to "accepted"
        /// </summary>
        /// <param name="friendID">Takes in the the id of the user who sent the request.</param>
        /// <param name="userID">Id of the user to whom the request was sent.</param>
        /// <returns></returns>
        public ActionResult AcceptRequest(int friendID, int userID)
        {
            try
            {
                HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                var friend = (from fr in db.FriendsLists
                              where fr.id == userID && fr.friend_id == friendID
                              select fr).FirstOrDefault();

                if (friend != null)
                {
                    friend.status = "accepted";
                }
                else
                {
                    FriendsList fl = new FriendsList();
                    fl.id = userID;
                    fl.friend_id = friendID;
                    fl.num_requests_sent = 0;
                    fl.status = "accepted";
                    db.FriendsLists.Add(fl);
                }

                friend = (from fr in db.FriendsLists
                          where fr.id == friendID && fr.friend_id == userID
                          select fr).FirstOrDefault();

                if (friend != null)
                {
                    friend.status = "accepted";
                }

                var user = (from usr in db.Users
                            where usr.id == userID
                            select usr).FirstOrDefault();

                string userImage = user.image_url;

                UserMessage um = new UserMessage();
                um.datetime_sent = DateTime.Now;
                um.sender_id = userID;
                um.recipient_id = friendID;
                um.subject = "Friend Request Accepted";
                um.message = "<table><tr>" +
                    "<td border=\"0px\"> <img src=\"" + "../" + userImage + "\" height=\"50px\" width=\"45px\" /> </td>" +
                    "<td>" + user.firstname + " " + user.lastname + " has accepted your friend request. </td>" +
                    "</tr></table>";
                um.message_read = false;

                // add the message to the user messages table
                db.UserMessages.Add(um);

                // save the changes made to the database
                db.SaveChanges();

                // Redirect to specified view
                return RedirectToAction("Index", "FriendList");
            }
            catch (Exception ex)
            {
                return View("~/Views/Shared/Error.cshtml", ex);
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// GET: returns the list of friends associated with the user.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
            Dictionary<string, List<User>> dict = new Dictionary<string, List<User>>();
            if (SessionHandler.Logon)
            {
                try
                {
                    List<int> usersOnline = HeartbeatMonitor.getOnlineUsers(HttpContext);

                    List<int> friends = (from friendslist in db.FriendsLists
                                         where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                         select friendslist.friend_id
                                   ).ToList();

                    foreach (var friend in friends)
                    {
                        User u = (from user in db.Users
                                  where friend.Equals(user.id)
                                  select user).FirstOrDefault();
                        list.Add(u);
                    }

                    foreach (var userO in usersOnline)
                    {
                        User u = (from user in db.Users
                                  where userO == user.id
                                  select user).FirstOrDefault();
                        onlineUserList.Add(u);
                    }

                    dict.Add("friends", list);
                    dict.Add("online", onlineUserList);

                    ViewBag.Message = "Current Friends";
                    return View("Index", dict);
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// GET: Gets the list of users, except those who are your friends and also yourself(the logged-in user)
        /// and passes the dictionary of list of users to the view. 
        /// 
        /// It also passes the list of users to whom the request is sent and hasn't yet been accepted or declined.
        /// 
        /// Dictionary<"string", List<User>> dict
        /// dict.Add("nonFriends", list of no friends);
        /// dict.Add("pendingRequests", list of pending request);
        /// </summary>
        /// <returns></returns>
        public ActionResult Find()
        {
            List<User> findList = new List<User>();
            List<User> pendingList = new List<User>();
            if (SessionHandler.Logon)
            {
                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    Dictionary<string, List<User>> dictFindFriends = new Dictionary<string, List<User>>();
                    List<FriendsList> friends = (from friendslist in db.FriendsLists
                                                 where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                                 select friendslist
                                           ).ToList();

                    List<FriendsList> pending = (from friendslist in db.FriendsLists
                                                 where friendslist.id == SessionHandler.UID && friendslist.status.Equals("pending")
                                                 select friendslist
                                           ).ToList();

                    foreach (var friend in friends)
                    {
                        User u = (from user in db.Users
                                  where friend.friend_id == user.id
                                  select user).FirstOrDefault();
                        findList.Add(u);
                    }

                    foreach (var pend in pending)
                    {
                        User u = (from user in db.Users
                                  where pend.friend_id == user.id
                                  select user).FirstOrDefault();
                        pendingList.Add(u);
                    }

                    // Display a list of users not including the active user
                    List<User>  userList = (
                        from user in db.Users
                        where user.id != SessionHandler.UID
                        orderby user.username ascending
                        select user
                        ).ToList();

                    var list2 = userList.Except(findList);
                    ViewBag.Message = "Find Friends";

                    dictFindFriends.Add("nonFriends", list2.ToList());
                    dictFindFriends.Add("pending", pendingList);

                    return View("FindFriends", dictFindFriends);
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        public ActionResult Find(FormCollection fm)
        {
            bool sendRequest = true;
            if (SessionHandler.Logon)
            {

                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    //display a list of users not including the active user
                    int temp = Convert.ToInt32(fm.GetKey(0));

                    FriendsList friend = (from f in db.FriendsLists
                                          where f.id == SessionHandler.UID && f.friend_id == temp
                                          select f).FirstOrDefault();

                    if (friend != null)
                    {
                        if (friend.num_requests_sent < 10)
                        {
                            int i = friend.num_requests_sent;
                            friend.num_requests_sent = ++i;
                            friend.status = "pending";
                        }
                        else
                        {
                            sendRequest = false;
                        }
                    }
                    else
                    {
                        // Add a request to the friends list table
                        FriendsList fl = new FriendsList();
                        fl.id = SessionHandler.UID;
                        fl.friend_id = temp;
                        fl.num_requests_sent = 1;
                        fl.status = "pending";

                        db.FriendsLists.Add(fl);
                    }

                    if (sendRequest)
                    {
                        // get current users information
                        User c_user = (from userT in db.Users
                                       where userT.id == SessionHandler.UID
                                       select userT).FirstOrDefault();

                        // current users image
                        string userImage = c_user.image_url;

                        //send friend request message to the select user in find friends form.
                        UserMessage um = new UserMessage();

                        // current date and time, when message was sent
                        um.datetime_sent = DateTime.Now;

                        //this is the ID of the current logged in user
                        um.sender_id = SessionHandler.UID;

                        //This is the ID of the user, who is being sent the friend request.
                        um.recipient_id = temp;
                        um.subject = "Friend Request";
                        um.message = "<table><tr>" +
                            "<tdborder=\"0px\"> <img src=\"" + "../" + userImage + "\" height=\"50px\" width=\"45px\"/> </td>" +
                            "<td>" + c_user.firstname + " " + c_user.lastname + " has sent you a friend request. </td>" +
                            "<td><a href=\"../../../FriendList/AcceptRequest/?friendID=" + SessionHandler.UID + "&userID=" + temp + "\">Accept</a></td>" +
                            "<td><a href=\"../../../FriendList/DeclineRequest/?friendID=" + SessionHandler.UID + "&userID=" + temp + "\">Decline</a></td>" +
                            "</tr></table>";
                        um.message_read = false;

                        // add the message to the user messages table
                        db.UserMessages.Add(um);

                        // save the changes made to the database.
                        db.SaveChanges();
                    }

                    // Redirect to specified view
                    return RedirectToAction("Find", "FriendList");

                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// Get: Gives ability to remove friends from the list.
        /// Gets the list of users who are friends with the logged in user and passes it
        /// to the view.
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit()
        {
            if (SessionHandler.Logon)
            {
                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    List<int> friends = (from friendslist in db.FriendsLists
                                         where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                         select friendslist.friend_id
                                   ).ToList();

                    foreach (var friend in friends)
                    {
                        User u = (from user in db.Users
                                  where friend.Equals(user.id)
                                  select user).FirstOrDefault();
                        list.Add(u);
                    }

                    ViewBag.Message = "Click \"Remove\" to remove any friends";
                    return View("EditFriendList", list);
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        public ActionResult Edit(FormCollection fm)
        {
            if (SessionHandler.Logon)
            {
                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    int friendID = Convert.ToInt32(fm.GetKey(0));

                    var fr = (from f in db.FriendsLists
                              where f.id == SessionHandler.UID && f.friend_id == friendID
                              select f).FirstOrDefault();
                    if (fr != null)
                    {
                        db.FriendsLists.Remove(fr);
                    }

                    fr = (from f in db.FriendsLists
                          where f.id == friendID && SessionHandler.UID == f.friend_id
                          select f).FirstOrDefault();

                    if (fr != null)
                    {
                        db.FriendsLists.Remove(fr);
                    }

                    db.SaveChanges();

                    List<int> friends = (from friendslist in db.FriendsLists
                                         where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                         select friendslist.friend_id
                                   ).ToList();
                    ViewBag.Message = "Click \"Remove\" to remove any friends";

                    if (friends != null)
                    {

                        foreach (var friend in friends)
                        {
                            User u = (from user in db.Users
                                      where friend.Equals(user.id)
                                      select user).FirstOrDefault();
                            list.Add(u);
                        }

                        return View("EditFriendList", list);
                    }
                    else
                    {
                        return View("EditFriendList");
                    }

                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        /// <summary>
        /// @Author: Jivanjot Brar
        /// POST: In the message sent to the user, if the user chooses decline friends request,
        /// this function access the row in the friendslist table in the database and changes the 
        /// status to "denied".
        /// </summary>
        /// <param name="friendID">Takes in the the id of the user who sent the request.</param>
        /// <param name="userID">Id of the user to whom the request was sent.</param>
        /// <returns></returns>
        public ActionResult DeclineRequest(int friendID, int userID)
        {
            try
            {
                HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                var friend = (from fr in db.FriendsLists
                              where fr.id == friendID && fr.friend_id == userID
                              select fr).FirstOrDefault();
                if (friend != null)
                {
                    friend.status = "denied";
                    db.SaveChanges();
                }

                // Redirect to specified view
                return RedirectToAction("Index", "FriendList");
            }
            catch (Exception ex)
            {
                return View("~/Views/Shared/Error.cshtml", ex);
            }
        }
        public ActionResult Edit(FormCollection fm)
        {
            if (SessionHandler.Logon)
            {
                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    //array to hold post data
                    string[] formInfo = new string[5];

                    // get post data from form
                    formInfo[0] = SecurityHelper.StripHTML(fm.GetValues("firstnameTextBox")[0]);
                    formInfo[1] = SecurityHelper.StripHTML(fm.GetValues("lastnameTextBox")[0]);
                    formInfo[2] = SecurityHelper.StripHTML(fm.GetValues("ageTextBox")[0]);
                    formInfo[3] = SecurityHelper.StripHTML(fm.GetValues("sexTextBox")[0]);
                    formInfo[4] = SecurityHelper.StripHTML(fm.GetValues("locationTextBox")[0]);

                    if ((nameValidation(formInfo[0])) && (nameValidation(formInfo[1]))
                        && (ageValidation(formInfo[2])) && (sexValidation(formInfo[3]))
                        && (nameValidation(formInfo[4])))
                    {
                        string[] validInfo = new String[5];

                        Array.Copy(formInfo, validInfo, 5);

                        // get the current user to update in db
                        User currentUser = (from u in db.Users
                                            where u.id == SessionHandler.UID
                                            select u).FirstOrDefault();

                        // update user information
                        currentUser.firstname = validInfo[0];
                        currentUser.lastname = validInfo[1];
                        currentUser.age = Int32.Parse(validInfo[2]);
                        currentUser.sex = validInfo[3].Substring(0, 1);
                        currentUser.location = validInfo[4];

                        // db.Users.Add(currentUser);
                        db.SaveChanges();
                        Session["displayErrors"] = false;
                        // go back to profile page
                        return RedirectToAction("Index", "Profile");

                    }
                    else
                    {
                        //ModelState.AddModelError("firstnameTextBox", "You have entered invalid info, please go back and enter valid information.");
                        ViewBag.error = "You have entered invalid info, please go back and enter valid information.";
                        Session["displayErrors"] = true;
                        // go back to profile page
                        return RedirectToAction("Edit", "Profile");
                        // return View("~/Views/Profile/EditProfile.cshtml");
                    }
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }
            }
            else
            {
                //must go to the login action
                return RedirectToAction("Index", "Login");
            }
        }
        /// <summary>
        /// @author Shan Bains
        /// edit profile page - updates the user profile information
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit()
        {
            // if logged on
            if (SessionHandler.Logon)
            {

                try
                {
                    HeartbeatMonitor loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);
                    // list of characters
                    List<Character> list1 = new List<Character>();
                    // dictionary with user and character data
                    Dictionary<Dictionary<String, List<User>>, Dictionary<String, List<Character>>> dictionary =
                         new Dictionary<Dictionary<String, List<User>>, Dictionary<String, List<Character>>>();

                    Dictionary<String, List<User>> userDict = new Dictionary<String, List<User>>();
                    Dictionary<String, List<Character>> charDict = new Dictionary<String, List<Character>>();

                    //query to get the current user
                    User currentUser = (from u in db.Users
                                        where u.id == SessionHandler.UID
                                        select u).FirstOrDefault();

                    // get the list of the users friends as <Users>
                    List<int> friends = (from friendslist in db.FriendsLists
                                         where friendslist.id == SessionHandler.UID && friendslist.status.Equals("accepted")
                                         select friendslist.friend_id).ToList();

                    // holds the list of friends
                    List<User> CurrentUserFriends = new List<User>();

                    if (friends.Count <= 0)
                    {
                        User noFriend = new User();
                        noFriend.username = "******";
                        noFriend.firstname = "No";
                        noFriend.lastname = "Friends";
                        CurrentUserFriends.Add(noFriend);
                    }
                    else
                    {

                        foreach (var friend in friends)
                        {
                            User u = (from user in db.Users
                                      where friend.Equals(user.id)
                                      orderby user.username
                                      select user).FirstOrDefault();
                            CurrentUserFriends.Add(u);
                        }
                    }

                    // add current user and user's friends to dictionary
                    List<User> currentUserList = new List<User>();
                    currentUserList.Add(currentUser);
                    userDict.Add("currentUser", currentUserList);
                    userDict.Add("friends", CurrentUserFriends);

                    // query to get the current character from db
                    Character c_character = (from Character in db.Characters
                                             where Character.id == currentUser.current_character
                                             select Character).FirstOrDefault();

                    List<Character> currentCharacters = new List<Character>();
                    currentCharacters.Add(c_character);
                    // query to get all the users characters from the db
                    List<Character> userCharacters = (from Character in db.Characters
                                                      where Character.user_id == SessionHandler.UID
                                                      select Character).ToList();

                    charDict.Add("mainCharacter", currentCharacters);
                    charDict.Add("otherCharacters", userCharacters);

                    dictionary.Add(userDict, charDict);

                    return View("EditProfile", dictionary);
                }
                catch (Exception ex)
                {
                    return View("~/Views/Shared/Error.cshtml", ex);
                }

            }
            else
            {
                return RedirectToAction("Index", "Login");
            }
        }
        //
        // GET: /LeaderBoard/
        /// <summary>
        /// @author: Guillaume Jacques
        /// by default the controller is taking the first 10 players ordered by ascending names
        /// </summary>
        /// <returns>the list of the first 10 characters sorted by name</returns>
        public ActionResult Index()
        {
            //check if the persistent cookie exists
            HttpCookie _userInfoCookies = Request.Cookies["UserInfo"];
            if (_userInfoCookies != null)
            {
                //set session variables
                SessionHandler.Logon = true;
                SessionHandler.Role = _userInfoCookies["role"];
                SessionHandler.UID = Convert.ToInt32(_userInfoCookies["uid"]);
            }

            loginTimer = new HeartbeatMonitor(SessionHandler.UID, HttpContext);

            try
            {
                return View("Index", getScoreList());
            }
            catch (Exception ex)
            {
                return View("~/Views/Shared/Error.cshtml", ex);
            }
        }
Beispiel #30
0
        private Task Negotiate(IClientTransport transport)
        {
            _connectionData = OnSending();

            return transport.Negotiate(this, _connectionData)
                            .Then(negotiationResponse =>
                            {
                                VerifyProtocolVersion(negotiationResponse.ProtocolVersion);

                                ConnectionId = negotiationResponse.ConnectionId;
                                ConnectionToken = negotiationResponse.ConnectionToken;
                                _disconnectTimeout = TimeSpan.FromSeconds(negotiationResponse.DisconnectTimeout);
                                _totalTransportConnectTimeout = TransportConnectTimeout + TimeSpan.FromSeconds(negotiationResponse.TransportConnectTimeout);

                                // Default the beat interval to be 5 seconds in case keep alive is disabled.
                                var beatInterval = TimeSpan.FromSeconds(5);

                                // If we have a keep alive
                                if (negotiationResponse.KeepAliveTimeout != null)
                                {
                                    _keepAliveData = new KeepAliveData(TimeSpan.FromSeconds(negotiationResponse.KeepAliveTimeout.Value));
                                    _reconnectWindow = _disconnectTimeout + _keepAliveData.Timeout;

                                    beatInterval = _keepAliveData.CheckInterval;
                                }
                                else
                                {
                                    _reconnectWindow = _disconnectTimeout;
                                }

                                _monitor = new HeartbeatMonitor(this, _stateLock, beatInterval);

                                return StartTransport();
                            })
                            .ContinueWithNotComplete(() => Disconnect());
        }
        /// <summary>
        /// Starts the <see cref="Connection"/>.
        /// </summary>
        /// <param name="transport">The transport to use.</param>
        /// <returns>A task that represents when the connection has started.</returns>
        public Task Start(IClientTransport transport)
        {
            lock (_startLock)
            {
                _connectTask = TaskAsyncHelper.Empty;
                _disconnectCts = new CancellationTokenSource();

                if (!ChangeState(ConnectionState.Disconnected, ConnectionState.Connecting))
                {
                    return _connectTask;
                }

                _monitor = new HeartbeatMonitor(this, _stateLock);
                _transport = transport;

                _connectTask = Negotiate(transport);
            }

            return _connectTask;
        }
Beispiel #32
0
 public MessageService(SmartQQWrapper smartQQ, HeartbeatMonitor callbackFunc = null)
 {
     this.smartQQ = smartQQ;
     this.HeartbeatMonitorAction = callbackFunc;
 }